java tutorial - Java Nested if statement - tutorial java - java programming - learn java - java basics - java for beginners



Java nested statement if

Learn Java - Java tutorial - Java nested statement if - Java examples - Java programs

  • The nested if-else statements, means that you will use one if or else statement inside another if statement or else.

Syntax

The syntax of if..else embedded statement in Java is:


            if (Boolean expression 1) {
   // Execute if Boolean expression 1 is true
   if (Boolean expression 1) {
      // Executed if logical expression 2 is true
   }
}
click below button to copy the code. By - java tutorial - team

You can do the nesting else if ... else in the same way we did the nested if statement in Java.

Sample Code

public class Test {

   public static void main(String args[]){
      int x = 30;
      int y = 10;

      if( x == 30 ){
         if( y == 10 ){
             System.out.print("X = 30 and Y = 10");
          }
       }
    }
}
click below button to copy the code. By - java tutorial - team

Output

X = 30 and Y = 10

The conditional operator if

  • Creating branching in programs, making decisions, checking conditions, exceptional situations, checking for errors.
    • name: if (condition) then operators_T else operators_F end if name
    • name: if (condition) then operators_T end if name
    • if (condition) operator_T
  • Nested if statements are multiple branching.
  • There are several possible uses if.
  • Option number 1

    ! ------------------------Option number 1
      if (x > 0) then
        if (x > -5) then ! ----------------
          fx = 0					!
        else					!
          fx = -2					!
        end if         ! ----------------
      else
        if (x > 3) then  ! ----------------
          fx = 3					!
        else					!
          fx = 1					!
        end if         ! ----------------
      end if
    Click the button below to copy the code. - from - java tutorials - команда

    Option number 2

    ! ------------------------ Option number 2
     if (x > 3) then
       fx = 3
     else
    
       if (x > 0) then
         fx = 1
       else
    
         if (x > -5) then
           fx = 0
         else
           fx = -2
         end if
    
       end if
    
     end if
    
    You can simplify using elseif.
    
    ! ------------------------Option number 2 a, elseif
     if (x > 3) then
       fx = 3
    
     elseif (x > 0)  then
       fx = 1
    
     elseif (x >- 5) then
       fx = 0
    
     else
       fx = -2
     end if
    click below button to copy the code. By - java tutorial - team

    Related Searches to Java Nested if statement