Java Statements

http‮w//:s‬ww.theitroad.com

In Java, a statement is a unit of code that expresses an action to be carried out. Statements are executed sequentially in the order in which they appear in a program. There are several types of statements in Java, including:

Expression Statements

An expression statement is a statement that contains an expression. The expression is evaluated and its result is discarded. For example:
int x = 5;
int y = 10;
x = x + y;

In this example, the third line is an expression statement that evaluates the expression x + y and assigns the result to x. The value of the expression is not used for any other purpose.

Declaration Statements

A declaration statement is used to declare a variable and optionally initialize it with a value. For example:
int x;
int y = 10;
double z = 3.14;

In this example, the first line is a declaration statement that declares a variable x of type int. The second line is a declaration statement that declares a variable y of type int and initializes it with the value 10. The third line is a declaration statement that declares a variable z of type double and initializes it with the value 3.14.

Control Flow Statements

Control flow statements are used to control the flow of execution in a program. There are several types of control flow statements in Java, including:
  • if statement: used to conditionally execute a block of code.
  • switch statement: used to select one of several code blocks to execute.
  • while statement: used to repeatedly execute a block of code while a condition is true.
  • do-while statement: used to repeatedly execute a block of code at least once, and continue while a condition is true.
  • for statement: used to repeatedly execute a block of code for a fixed number of iterations.
  • break statement: used to exit a loop or switch statement.
  • continue statement: used to skip the current iteration of a loop and continue with the next iteration.

Here's an example of an if statement:

int x = 5;
if (x > 0) {
    System.out.println("x is positive");
} else if (x == 0) {
    System.out.println("x is zero");
} else {
    System.out.println("x is negative");
}

In this example, we use an if statement to conditionally execute one of three blocks of code, depending on the value of x.

Jump Statements

Jump statements are used to transfer control to another part of a program. There are two types of jump statements in Java:
  • break statement: used to exit a loop or switch statement.
  • continue statement: used to skip the current iteration of a loop and continue with the next iteration.

Here's an example of a break statement:

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

In this example, we use a for loop to iterate over the numbers from 0 to 9, and use a break statement to exit the loop when the value of i is 5.