Java Expressions, Statements and Blocks
In this tutorial, we will learn about Java expressions, Java Statements, and Java blocks with the help of examples.
Java Expressions
A Java expression consists of variables, operators, literals, and method calls.
For example,
int age;
age = 23;
Above, age = 23 is an expression that returns an int.
Let us see the following example,
int x = 12, y = 4, result;
result = x + y + 10;
Here, x + y + 10 is an expression.
if (num > 10) {
System.out.println("Number is larger than 10");
}
Here, num > 10 is an expression that returns a boolean value.
Java Statements
In Java, every statement is a complete unit of execution. For example,
int x = 12 + 9;
Here above, we have a statement. The complete execution of this statement involves adding integers 12 and 9 and then assigning the result to the variable x.
Withing the above statement, we have the expression 12 + 9. In Java, expressions are part of statements.
Expression Statements
It is easy to convert an expression into a statement. It consists of terminating the expression with a semicolon ;. For example,
// expression
a = 17
// statement
a = 17;
Here above, we have the expression a = 17, and just be adding a semicolon ;, we have transformed the expression into a statement a = 17;.
Let us see another example,
// expression
++i
// statement
++i;
Similarly, ++i is an expression while ++i; is a statement.
Declaration Statements
Declaration statements are used for declaring variables in Java.
Let us consider the following example,
int age = 25;
Here above, the statement declares the variable age that is initialized to 25.
Java Blocks
In Java, a block is a group of statements (zero or more) that are enclosed in curly braces { }.
Example:
public class Main {
public static void main(String[] args) {
String text = "Hello";
if (text == "Hello") { // start of the block
System.out.print("Hello ");
System.out.println("World");
} // end of the block
}
}
Output
Hello World
Here above, we have a block if { ... }.
Inside the block, we have two statements:
System.out.print("Hello ");System.out.println("World");
In Java, a block may not have any statements. For example,
public class Main {
public static void main(String[] args) {
int x = 27;
if (x > 7) { // start of the block
} // end of the block
}
}
Here above, we have a block if { ... } even without any statement inside this block; it is a valid Java program.
Let us see another example,
public class Main {
public static void main(String[] args) { // start of the block
} // end of the block
}
Here above, we have a block public static void main() { ... }, similar to the above example, this block does not have any statement, and it is a valid Java program.
