Java notes 1
Java notes 1
Java notes 1
Java is a widely-used programming language that has undergone significant evolution since its
inception. Here’s a brief history:
1. Origins (1991)
- Java was developed at Sun Microsystems by James Gosling and his team.
- Initially, it was called Oak, designed for interactive television. However, it was not adopted due
to the limitations of the technology at that time.
Conclusion
Java's history reflects its adaptability and resilience, maintaining relevance in a rapidly changing
technology landscape. Its emphasis on portability, performance, and community support has
solidified its status as a cornerstone in modern software development.
Java Introduction
What is Java?
Java is a popular programming language, created in 1995.
It is used for:
To check if you have Java installed on a Windows PC, search in the start bar for
Java or type the following in Command Prompt (cmd.exe):
If Java is installed, you will see something like this (depending on version):
If you do not have Java installed on your computer, you can download it for free
at oracle.com.
Note: In this tutorial, we will write Java code in a text editor. However, it is
possible to write Java in an Integrated Development Environment, such as IntelliJ
IDEA, Netbeans or Eclipse, which are particularly useful when managing larger
collections of Java files.
Java Quickstart
In Java, every application begins with a class name, and that class must match
the filename.
Let's create our first Java file, called Main.java, which can be done in any text
editor (like Notepad).
The file should contain a "Hello World" message, which is written with the
following code:
Main.java
System.out.println("Hello World");
Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code above.
This will compile your code. If there are no errors in the code, the command
prompt will take you to the next line. Now, type "java Main" to run the file:
Hello World
Congratulations! You have written and executed your first Java program.
Main.java
public class Main {
System.out.println("Hello World");
Java Syntax
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used
the following code to print "Hello World" to the screen:
Main.java
System.out.println("Hello World");
Example explained
Every line of code that runs in Java must be inside a class. And the class name
should always start with an uppercase first letter. In our example, we named the
class Main.
The name of the java file must match the class name. When saving the file, save
it using the class name and add ".java" to the end of the filename. To run the
example above on your computer, make sure that Java is properly installed: Go
to the Get Started Chapter for how to install Java. The output should be:
Hello World
Any code inside the main() method will be executed. Don't worry about the
keywords before and after it. You will get to know them bit by bit while reading
this tutorial.
For now, just remember that every Java program has a class name which must
match the filename, and that every program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of
text to the screen:
System.out.println("Hello World");
Print Text
You learned from the previous chapter that you can use the println() method
to output values or print text in Java:
Example
System.out.println("Hello World!");
Try it Yourself »
You can add as many println() methods as you want. Note that it will add a
new line for each method:
Example
System.out.println("Hello World!");
System.out.println("It is awesome!");
Try it Yourself »
Double Quotes
Text must be wrapped inside double quotations marks "".
Try it Yourself »
The only difference is that it does not insert a new line at the end of the output:
Example
Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double quotes:
Example
System.out.println(3);
System.out.println(358);
System.out.println(50000);
Try it Yourself »
You can also perform mathematical calculations inside the println() method:
Example
System.out.println(3 + 3);
Example
System.out.println(2 * 5);
Java Comments
❮ Previous
Next ❯
Java Comments
Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes ( //).
Any text between // and the end of the line is ignored by Java (will not be
executed).
Example
// This is a comment
System.out.println("Hello World");
Try it Yourself »
Example
This example uses a multi-line comment (a comment block) to explain the code:
Example
System.out.println("Hello World");
Java Variables
❮ Previous
Next ❯
Java Variables
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
Syntax
Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to assign
values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John".
Then we use println() to print the name variable:
String name = "John";
System.out.println(name);
Try it Yourself »
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
System.out.println(myNum);
Try it Yourself »
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
System.out.println(myNum);
Try it Yourself »
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
System.out.println(myNum);
Try it Yourself »
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final
keyword (this will declare the variable as "final" or "constant", which means
unchangeable and read-only):
Example
Try it Yourself »
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
Display Variables
The println() method is often used to display variables.
To combine both text and a variable, use the + character:
Example
Try it Yourself »
You can also use the + character to add a variable to another variable:
Example
System.out.println(fullName);
Try it Yourself »
int x = 5;
int y = 6;
Try it Yourself »
Example
int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Try it Yourself »
Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Java Identifiers
❮ Previous
Next ❯
Identifiers
All Java variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Example
// Good
int m = 60;
Try it Yourself »
The general rules for naming variables are:
Real-Life Examples
Often in our examples, we simplify variable names to match their data type
(myInt or myNum for int types, myChar for char types, and so on). This is done
to avoid confusion.
Example
// Student data
// Print variables
Try it Yourself »
Example
int length = 4;
int width = 6;
int area;
Example
● Primitive data types - includes byte, short, int, long, float, double,
boolean and char
● Non-primitive data types - such as String, Arrays and Classes (you will
learn more about these in a later chapter)
Java Numbers
❮ Previous
Next ❯
Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you
should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int
(for whole numbers) and double (for floating point numbers). However, we will describe
them all as you continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that
the value will be within -128 and 127:
Example
System.out.println(myNum);
Try it Yourself »
Short
The short data type can store whole numbers from -32768 to 32767:
Example
System.out.println(myNum);
Try it Yourself »
Int
The int data type can store whole numbers from -2147483648 to 2147483647.
In general, and in our tutorial, the int data type is the preferred data type when
we create variables with a numeric value.
Example
System.out.println(myNum);
Try it Yourself »
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Example
System.out.println(myNum);
Try it Yourself »
Floating Point Types
You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you
should end the value with an "f" for floats and "d" for doubles:
Float Example
System.out.println(myNum);
Try it Yourself »
Double Example
System.out.println(myNum);
Try it Yourself »
The precision of a floating point value indicates how many digits the value can have
after the decimal point. The precision of float is only six or seven decimal digits, while
double variables have a precision of about 16 digits. Therefore it is safer to use double
for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Boolean Types
Very often in programming, you will need a data type that can only have one of
two values, like:
● YES / NO
● ON / OFF
● TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or
false:
Example
Java Characters
❮ Previous
Next ❯
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
System.out.println(myGrade);
Try it Yourself »
Alternatively, if you are familiar with ASCII values, you can use those to display
certain characters:
Example
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Try it Yourself »
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
System.out.println(greeting);
Try it Yourself »
The String type is so much used and integrated in Java, that some call it "the special
ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The
String object has methods that are used to perform certain operations on strings. Don't
worry if you don't understand the term "object" just yet. We will learn more about strings
and objects in a later chapter.
Real-Life Example
Here's a real-life example of using different data types, to calculate and output
the total cost of a number of items:
Example
The main difference between primitive and non-primitive data types are:
● Primitive types in Java are predefined and built into the language, while
non-primitive types are created by the programmer (except for String).
● Non-primitive types can be used to call methods to perform certain
operations, wheras primitive types cannot.
● Primitive types start with a lowercase letter (like int), while non-primitive
types typically starts with an uppercase letter (like String).
● Primitive types always hold a value, wheras non-primitive types can be
null.
Examples of non-primitive types are Strings, Arrays, Classes etc. You will learn
more about these in a later chapter.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a
larger size type:
Example
int myInt = 9;
System.out.println(myInt); // Outputs 9
}
}
Try it Yourself »
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses ()
in front of the value:
Example
System.out.println(myInt); // Outputs 9
Try it Yourself »
Real-Life Example
Here's a real-life example of type casting where we create a program to
calculate the percentage of a user's score in relation to the maximum score in a
game.
We use type casting to make sure that the result is a floating-point value, rather
than an integer:
Example
Java Operators
❮ Previous
Next ❯
Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
Try it Yourself »
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
Try it Yourself »
Java divides the operators into the following groups:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
In the example below, we use the assignment operator ( =) to assign the value
10 to a variable called x:
Example
int x = 10;
Try it Yourself »
Example
int x = 10;
x += 5;
Try it Yourself »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
The return value of a comparison is either true or false. These values are
known as Boolean values, and you will learn more about them in the Booleans
and If..Else chapter.
In the following example, we use the greater than operator ( >) to find out if 5 is
greater than 3:
Example
int x = 5;
int y = 3;
Try it Yourself »
Operator Name Example Try it
== Equal to x == y Try it »
Logical operators are used to determine the logic between variables or values: