java tutorial - Java ifelse statement - java programming - learn java - java basics - java for beginners



Java operator if else

Learn Java - Java tutorial - Java operator if else - Java examples - Java programs

The if statement in java can be followed by extra else statement, that is executed when the logical expression is false.

Syntax

The syntax for Java ifelse statement is:


if (Boolean expression)
{
   // Execute if true
} else {
   // Executed if false
}
click below button to copy the code. By - java tutorial - team
  • If the boolean expression is true, then the if code block will be executed, otherwise the else code block will be executed.

Process description

 if-else-operator

Learn java - java tutorial - if-else-statement - java examples - java programs

Sample Code

public class Test {

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

      if( y < 20 ){
         System.out.print("This is an operator if");
      }else{
         System.out.print("This is an operator else");
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

This is an operator else

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 of 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 below button to copy the code. By - java tutorial - team

    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 ifelse statement