Java Syntax Notes
Java Syntax Notes
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. In our example, we named the class Main. A
class should always start with an uppercase first letter.
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
The main() method is required and you will see it in every Java program:
Any code inside the main() method will be executed. Don't worry about the keywords before and after
main. 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:
public static void main(String[] args) {
System.out.println("Hello World");
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about System, out and println(). Just know that you need them together to print
stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Print Text
You learned from the previous chapter that you can use the println() method to output values or print
text in Java:
System.out.println("Hello World!");
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!");
Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "".
Example
The only difference is that it does not insert a new line at the end of the output:
Example
Note that we add an extra space (after "Hello World!" in the example above), for better readability.
In this tutorial, we will only use println() as it makes it easier to read the output of code.
Print Numbers
System.out.println(3);
System.out.println(358);
System.out.println(50000);
You can also perform mathematical calculations inside the println() method:
Example
System.out.println(3 + 3);
Example
System.out.println(2 * 5);
Java Comments
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
Any text between // and the end of the line is ignored by Java (will not be executed).
// This is a comment
System.out.println("Hello World");This example uses a single-line comment at the end of a line of code:
Example
This example uses a multi-line comment (a comment block) to explain the code:
Example
System.out.println("Hello World");
Java Variables
Java Variables
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
To create a variable, you must specify the type and assign it a value:
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":
System.out.println(name);
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);
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
System.out.println(myNum);
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
myNum = 20; // will generate an error: cannot assign a value to a final variable
Other Types
Example
int myNum = 5;
Display Variables
You can also use the + character to add a variable to another variable:
Example
System.out.println(fullName);
For numeric values, the + character works as a mathematical operator (notice that we use int (integer)
variables here):
Example
int x = 5;
int y = 6;
To declare more than one variable of the same type, you can use a comma-separated list:
Instead of writing:
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);
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Java Identifiers
Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable
code:
// Good
int m = 60;
Names should start with a lowercase letter and it cannot contain whitespace
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like Java keywords, such as int or boolean) cannot be used as names
As explained in the previous chapter, a variable in Java must be a specified data type:
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)
A primitive data type specifies the size and type of variable values, and it has no additional methods.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Numbers
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:
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
System.out.println(myNum);
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
int myNum = 100000;
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);
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);
Double Example
System.out.println(myNum);
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:
Java Characters
Characters
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
System.out.println(myGrade);
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);
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);
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.
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
Type casting is when you assign a value of one primitive data type to another type.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
int myInt = 9;
System.out.println(myInt); // Outputs 9
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
}
Java Operators
Java Operators
In the example below, we use the + operator to add together two values:
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
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
A list of all assignment operators:
= x=5 x=5
+= x += 3 x = x + 3
-= x -= 3 x=x-3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
Comparison operators are used to compare two values (or variables). This is important in programming,
because it helps us to find answers and make decisions.
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;
== Equal to x == y
!= Not equal x != y
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are truex < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)