Java Expressions, Statements and Blocks

Java Tutorials

Summary: In this tutorial, you will about expressions, statements and blocks in Java with examples.

Expressions in Java

In Java, an expression is a combination of one or more values, variables, and operators that results in a value. Expressions can be used to perform a calculation, to assign a value to a variable, or to produce a side effect.

Here are some examples of expressions in Java:

  1. 3 + 4 is an expression that calculates the sum of 3 and 4, resulting in the value 7.
  2. x = 3 + 4 is an expression that calculates the sum of 3 and 4, and assigns the result to the variable x.
  3. System.out.println("Hello, world!") is an expression that produces a side effect by printing a message to the console.

Statements in Java

A statement is a complete instruction in a Java program. A statement can be a simple statement, which consists of a single expression, or a compound statement, which consists of multiple statements enclosed in curly braces.

Here are some examples of statements in Java:

int x = 3 + 4;

This is a simple statement that declares a variable x and assigns it the value of the expression 3 + 4.

if (x > 5) { 
    System.out.println("x is greater than 5");
    x = x - 1;
}

This is a compound statement that consists of an if statement and two simple statements.

Blocks in Java

A block is a group of statements that are enclosed in curly braces. Blocks can be used to define the body of a method, the body of a loop, or the branches of a control statement, such as an if statement or a switch statement.

Here is an example of a block in Java:

for (int i = 0; i < 10; i++) {
   System.out.println(i);
}

This block defines the body of a for loop, which consists of a single statement that prints the value of the loop variable i. The block will be executed 10 times, with i taking on the values 0 through 9.

You will read more about loops in later post.


Leave a Reply

Your email address will not be published. Required fields are marked *