Types of Statements in Java (Best Example)

Types of Statements in Java: –In Java, there are several types of statements that can be used to control the flow of execution in a program. Here are some of the most common types of statements, along with examples of how they can be used:

Types of Statements in Java

Declaration Statements

Declaration statements are used to declare variables and specify their data types. For example:

int x;
double y = 3.14;
String name = "John";

Expression Statements

Expression statements are used to evaluate an expression and possibly assign its value to a variable. For example:

x = 5;
y = x * 2;
System.out.println("Hello, " + name);

Control Flow Statements

Control flow statements are used to control the order in which statements are executed in a program. Some common control flow statements include:

  • If/Else Statements: Used to execute code based on a condition. For example:
if (x > 10) {
    System.out.println("x is greater than 10");
} else {
    System.out.println("x is less than or equal to 10");
}

Related Article –

  • For Loops: Used to execute a block of code a specified number of times. For example:
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
  • While Loops: Used to execute a block of code while a condition is true. For example:
while (x < 100) {
    x = x * 2;
}
  • Switch Statements: Used to execute code based on the value of a variable. For example:
switch (dayOfWeek) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    // and so on...
}
  • Jump Statements

Jump statements are used to transfer control to another part of the program. Some common jump statements include:

  • Break: Used to exit a loop or switch statement. For example:
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}
  • Continue: Used to skip to the next iteration of a loop. For example:

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

  • Return: Used to exit a method and optionally return a value. For example:
public int add(int a, int b) {
    return a + b;
}

These are some of the most common types of statements in Java. Understanding how to use them effectively is key to writing clear and concise code.

Leave a Comment