Java Conditional Statement

In Java, a conditional statement is a piece of code that executes one or more statements if a certain condition is true. Conditional statements are an essential part of programming, as they allow you to control the flow of your code based on different conditions. There are several types of conditional statements in Java, including if, if-else, and switch, which allow you to specify different code blocks to be executed depending on whether a certain condition is true or false.

Java Conditional Statement

In Java, a conditional statement is a piece of code that executes one or more statements if a certain condition is true. There are several types of conditional statements in Java, including if, if-else, and switch.

if statement

The if statement is the most basic type of conditional statement. It has the following syntax:

if (condition) {
  // code to be executed if condition is true
}

Here is an example of an if statement:

int x = 10;
if (x > 0) {
  System.out.println("x is positive");
}

This code will output “x is positive” because the condition x > 0 is true.

if-else statement

The if-else statement is an extension of the if statement that allows you to specify different code blocks to be executed depending on whether the condition is true or false. It has the following syntax:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

Here is an example of an if-else statement:

int x = 10;
if (x > 0) {
  System.out.println("x is positive");
} else {
  System.out.println("x is not positive");
}

This code will output “x is positive” because the condition x > 0 is true.

switch Statement

The switch statement is a multi-way branching statement that allows you to choose between several different code blocks based on the value of an expression. It has the following syntax:

switch (expression) {
  case value1:
    // code to be executed if expression is equal to value1
    break;
  case value2:
    // code to be executed if expression is equal to value2
    break;
  ...
  default:
    // code to be executed if expression does not match any of the values
}

Here is an example of a switch statement:

int x = 2;
switch (x) {
  case 1:
    System.out.println("x is 1");
    break;
  case 2:
    System.out.println("x is 2");
    break;
  default:
    System.out.println("x is something else");
}

This code will output “x is 2” because the value of x is 2.

This is just summary, we will see each statement in details.

Similar Posts

Leave a Reply

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