logo codesdope

Decide if or else


Many times, we need to see a condition and then decide what to do according to the condition.

For example, if it is raining, we will take an umbrella, otherwise not. Similarly, if a number is divisible by 2, it is even, otherwise it is odd.

if and else in java {} braces for body in java

This is what if and else does in Java.

So, it means that now you can take input from a user and perform according to it using if...else and then print something on the screen for the user.

if statement


Again take the example of raining. If it is raining, a person will take an umbrella.

This type of decision taking is done using if statement in Java.

Let's have a look at the syntax of if statement before looking at its example.

if(expression)
  {
    statements
  }

If the expression written within the brackets of if statement is true, then the statements written in the body of the if ( enclosed by curly brackets ) are executed.

class D1{
public static void main(String[] args){
  int a=10,b=20;
  if(a < b){
	System.out.println("b is greater than a");
   }
}
}
Output
b is greater than a

Here, the condition of if ( a < b ) is true. So, the statement inside if got executed and b is greater than a got printed on the screen.

if...else statement


Consider the same example of raining. If it is raining, a person will take an umbrella while going out, otherwise he will take a hat with himself.

In Java, this is done by using if...else statement. Let's see how.

if(expression)
    statement 1
else
    statement 2

If the expression is true, statement 1 will be executed. Otherwise, statement 2 will be executed.

Let's see an example.

class D2{
public static void main(String[] args){
 int a=20,b=10;
 if(a < b)
	System.out.println("b is greater than a");
  else
	System.out.println("a is greater than b");
}
}
Output
a is greater than b

In the above example, the value of 'b' is greater than that of 'a'. Since the expression ( a < b ) is false, therefore the statement in the body of else i.e. 'System.out.println("a is greater than b");' will be executed.

Consider one more example.

import java.util.*;
class D3{
public static void main(String[] args){
 	System.out.println("Enter number");
	Scanner s1 = new Scanner(System.in);                 
	int n=s1.nextInt();
	if( n%2 == 0 )
		System.out.println("Number is even");
	else
		System.out.println("Number is odd");
}
}
Output
Enter number
3
Number is odd

For a number to be even, it must be divisible by 2. This means that it should give a remainder 0 if divided by 2.
We have entered 3 here and n%2 i.e. 3%2 is 1. So, else will be executed and Number is odd will be printed on the screen.

If you want to execute multiple statements if the expression is true or false, then enclose the statements within curly brackets { }.
import java.util.*;
class D4{
public static void main(String[] args){
  System.out.println("Enter your age");
  Scanner s1=new Scanner(System.in);                 
  int age=s1.nextInt();

  if ( age >= 18 ){
    System.out.println( "Your age is 18+." );
    System.out.println( "Eligible to vote" );
  }

  else{
    System.out.println( "You are not yet 18." );
    System.out.println( "not eligible to vote" );
  }
}
}
Output
Enter your age
17
Your are not yet 18.
not eligible to vote

In this example, since the user entered the age as 17, which is less than 18, so the expression age >= 18 became false. Therefore, the statements in the body of else got executed. If the user enters the age greater than 18, then the condition 'age >= 18' would be true and the statements in the body of if statement will be executed.

Nested if/else statements


We can also use if or else inside another if or else if statements.

Suppose we have to find if a number is the greatest among three numbers.

class D5{
public static void main(String[] args){
  int x = 5, y = 2, z = 8;
    if ( x > y ){
      if( x > z )
        System.out.println( "x is the greatest integer" );
      else
        System.out.println( "x is not the greatest integer" );
    }
    else
      System.out.println( "x is not the greatest integer" );
}
}
Output
x is not the greatest integer

Here, the condition x > y is true, so the statements enclosed in the curly brackets { } of the first if condition got executed. Within the curly brackets, the first statement i.e. if( x > z ) got executed first. Since this condition is false, the statement System.out.println(" x is the greatest number."); within the curly brackets of this if condition was not executed. Finally, the statement System.out.println( " x is not the greatest number. " ); of the inner else got executed.

We can also do the same by using &&

class D51{
public static void main(String[] args){
  int x = 5, y = 2, z = 8;
    if ( (x > y) && (x > z) ){
      System.out.println( "x is the greatest integer" );
    }
    else
      System.out.println( "x is not the greatest integer" );
}
}
Output
x is not the greatest integer

Here, the expression inside if will be true only if both (x > y) and (x > z) are true. If that is the case, then x will be the greatest number, otherwise not.

else if statement


Many times we fall in situations when only 'if' and 'else' are not sufficient. eg.- if you have 5 rupees, then you will buy candy, if you have 10 rupees, then chocolate and if more than 100, then cake. Java provides another tool 'else if' to get this done.

See an example to find the greatest number

import java.util.*;

class D6{
public static void main(String[] args){
  int x,y,z;
  Scanner s = new Scanner(System.in);

  System.out.println("Enter first number");
  x = s.nextInt();

  System.out.println("Enter second number");
  y = s.nextInt();

  System.out.println("Enter third number");
  z = s.nextInt();

    if ( (x > y) && (x > z) ){
      System.out.println( x+" is the greatest integer" );
    }
    else if ( (y > x) && (y > z) ){
      System.out.println( y+" is the greatest integer" );
    }
    else
      System.out.println( z+" is the greatest integer" );
}
}
Output
Enter first number
4
Enter second number
5
Enter third number
1
5 is the greatest integer

We can give condition in else if also. First, the condition of if is checked. If it is false, then the condition of else if is checked and if that is also wrong, then the body of else will be executed.

In the above example, we are given three numbers x, y and z and we have to find the highest among them. For that, first we will compare the first number with the other numbers i.e. 'x' with both 'y' and 'z'. Now, if the condition (x>y && x>z) is true (if both are true, means a is the greatest ), then the statements enclosed in the curly brackets {} of the first if condition will are executed. If not so, then it will go to else if and check for (y>x && y>z). If it is true, then corresponding statements will be executed otherwise it go to else.

See one more example:

class D7{
public static void main(String[] args){
  char grade = 'A';
    if( grade == 'A' ){
      System.out.println( "Excellent !" );
    }
    else if(grade == 'B'){
      System.out.println( "Outstanding !" );
    }
    else if(grade == 'C'){
      System.out.println( "Good !" );
    }
    else if(grade == 'D'){
      System.out.println( "Can do better" );
    }
    else if(grade == 'E'){
      System.out.println( "Just passed" );
    }
    else if(grade == 'F'){
      System.out.println( "You failed" );
    }
    else{
      System.out.println( "Invalid grade" );
    }
  }
}
Output
Excellent !

First the condition of if is checked. If it is true, then only statements inside that if are executed, otherwise it checks the condition inside else if. If it is true, then its body is executed, otherwise next else if is checked. If none of them are true, then the body of else is executed.

We can also solve the above example using switch..case, which makes the code much simpler.

Switch..case


Normally, if we have to choose one case among many choices, nested if-else is used. But if the number of choices is large, switch..case is a better option as it makes code neat and easier.

Let's have a look at its syntax.

switch(expression)
  {
    case constant1:
        statement(s);
        break;
    case constant2:
        statement(s);
        break;
    /* you can give any number of cases */
    default:
        statement(s);
  }

In switch...case, value of the expression enclosed in the brackets ( ) following switch is checked. If the value of the expression matches the value of the constant in case, the statement(s) corresponding to that case will be executed.

If the expression does not match any of the constant values, then the statements corresponding to default are executed.

Now, let's see the previous example using switch..case.

class D8{
  public static void main(String[] args){
  char grade = 'B';
  switch ( grade )
  {
    case 'A':
      System.out.println( " Excellent ! " );
      break ;
    case 'B':
      System.out.println( " Outstanding ! " );
      break ;
    case 'C':
      System.out.println( " Good ! " );
      break ;
    case 'D':
      System.out.println( " Can do better " );
      break ;
    case 'E':
      System.out.println( " Just passed " );
      break ;
    case 'F':
      System.out.println( " You failed " );
      break ;
    default :
      System.out.println( " Invalid grade " );
  }
}
}
Output
Outstanding !

In this example, the value of grade is B. Since the value of the constants of the first case is not 'B', so the first case will not be executed. Now, since the value of the constant of the second case is 'B', so case 'B' will be executed and 'Outstanding !' will be printed. Then break statement will terminate the loop without checking the rest of the cases. This is how it works.

No need to write break in the default case because the loop automatically terminates once default statements are executed.

Note that we added break after each case so that the loop terminates once the case is executed.

Now let's see what happens when we don't add break after the cases.

class D9{
  public static void main(String[] args){
  char grade = 'B';
  switch ( grade )
  {
    case 'A':
      System.out.println( " Excellent ! " );
    case 'B':
      System.out.println( " Outstanding ! " );
    case 'C':
      System.out.println( " Good ! " );
    case 'D':
      System.out.println( " Can do better " );
    case 'E':
      System.out.println( " Just passed " );
    case 'F':
      System.out.println( " You failed " );
    default :
      System.out.println( " Invalid grade " );
  }
}
}
Output
Outstanding !
Good !
Can do better
Just passed
You failed
Invalid grade

In the above example, the value of grade is 'B', so the control jumped to case 'B'. Since there is no break statement after any case, so all the statements after case 'B' will also be executed.

If you want to execute only that case whose constant value equals the value of the expression of the switch statement, then use the break statement.
Always enclose the character values within   '   '

Let's see another example where the value of the expression is an integer.

class D10{
public static void main(String[] args){
  int i = 2 ;
  switch ( i )
    {
      case   1:
         System.out.println( "Number is 1" )   ;
         break ;
      case   2:
         System.out.println( "Number is 2" )   ;
         break ;
      default :
         System.out.println( "Number is greater than 2" )   ;
    }
}
}
Output
Number is 2

Don't worry about failure. You only have to be right once.
-Drew Houston

Share what you know
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.