Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Java statements

In Java, statements are individual instructions or commands that perform a specific action. Each statement typically ends with a semicolon (;) to mark its completion.

Here are some common types of statements in Java:

1. Variable Declaration and Assignment:

int age; // Variable declaration
age = 25; // Variable assignment

This statement declares an integer variable named age and assigns the value 25 to it.

2. Expression Statements:

int result = 10 + 5; // Expression statement
System.out.println("The result is: " + result); // Method invocation statement

Expression statements perform operations or function calls. The first statement adds 10 and 5, and assigns the result to the variable result. The second statement calls the println method to display a message along with the value of result.

3. Control Flow Statements:

  • Conditional Statements (if-else):
int number = 7;
if (number % 2 == 0) {
    System.out.println("The number is even.");
} else {
    System.out.println("The number is odd.");
}

This statement checks if number is divisible by 2. If the condition is true, it prints “The number is even.”; otherwise, it prints “The number is odd.”

  • Looping Statements (for, while, do-while):
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}

int count = 0;
while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}

int value = 0;
do {
    System.out.println("Value: " + value);
    value++;
} while (value < 3);

These statements demonstrate different types of loops. The for loop executes a block of code repeatedly for a specified number of iterations. The while loop continues execution until a certain condition is met. The do-while loop first executes the code block and then checks the condition for further iterations.

4. Jump Statements:

  • break and continue statement:
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exit the loop when i equals 5
    }
    System.out.println("Value: " + i);
}

- `continue` statement:
```java
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue; // Skip the current iteration when i equals 5
    }
    System.out.println("Value: " + i);
}

The break statement is used to exit a loop prematurely, while the continue statement skips the current iteration and moves to the next iteration of a loop.