Java Conditional Statements: A Comprehensive Guide

conditional Statements

Java conditional statements are used to execute different actions based on whether a certain condition evaluates to true or false.

  • IF
  • IF-ELSE
  • ELSE-IF
  • SWITCH
  • NESTED-IF
cs

IF Statement Syntax:-

  if(condition)

  {

       if body;

  }

if

Note:- 

  • Whenever we are taking single statements the curly brasses are optional.
  • Whenever we are taking multiple statement the curly brasses are mandatory.

IF – ELSE Statement Syntax:-

  if(condition)

  {

        if body;(true)

  }

  else

  {

      esle body;(false) 

  }

mn

ELSE-IF Statement Syntax:-

  if (condition1)

  {
  execute if condition1 is true
  }

  else if (condition2)

  {
  execute if condition2 is true and condition1 is false
  }

  else if (condition3)

  {
  if condition3 is true and both condition1 and condition2 are false
  }

  else

  {
  execute if none of the above conditions are true
  }

SWITCH Statement Syntax:-

  switch (argument)
  {
            Case lable1: System.out.println(“—-”);
                                   Break;
            Case lable2: System.out.println(“—-”);
                                   Break;
            Case lable3: System.out.println(“—-”);
                                   Break;
 
            Default: System.out.println(“—–”);
                                   Break;
 
  }
ght
  • The switch statement is used to take multiple selections.
  • Inside the switch it is possible to declare any number of cases but it is possible to declare only one default.
  • Curly brasses are mandatory if we are not taking we are getting compilation error.
  • Float and double and long is not allowed for a switch argument (float and double is having infinity number of possibilities).
  • If the case is matched particular case will be executed if there is no case is matched default case is executed.

Switch is taking the argument the allowed arguments are :-

  • Byte
  • Short
  • Int
  • Char
  • String(in 1.7 version)

NESTED-IF Statement Syntax:-

  if (condition1)

  {
  // Outer if block

  if (condition2)

  {
  // Inner if block
  execute if both condition1 and condition2 are true
  }

  else

  {
  execute if condition1 is true but condition2 is false
  }
  }

  else

  {
  execute if condition1 is false

  }

Leave a Comment

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