Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java 'If' statment

  • The 'if' statement is used to test a condition.
  • When 'if' condition is true, then it executes a set of instructions enclosed within curly brackets of 'if' statement.
  • Suppose, you want to display a message "Dear Learner" when variable a = 1, then the 'if' statement looks like
    if (a==1)
    {
      System.out.println("Dear Learner");
    }
    
  • 'if' statement uses double equal sign (==) for comparison.
  • Format of 'if' statement is
      
    if (condition)
    {
       statement
    	.
    	.
    	.
    }
    

Example

Program: Display the message "Dear Learner" when user gives input 1.

import java.util.*;
class progGreatertwo {
	     public static void main (String args [])
		 {
			 Scanner userinput = new Scanner(System.in);
			 System.out.println("Please enter your choice: ");
			 int choice = userinput.nextInt();
			 if (choice == 1)
			 {
				 System.out.println("Dear Learner");
			 }
		 }	 
}

Explanation of the program

  • Class progGreatertwo is created.
  • It consists of one variable userinput .
  • The value of variable userinput is taken from user.
  • Scanner class is used to take input from the user.
  • If the value of variable userinput is 1, then the program displays message Dear Learner .
  • Here, we can understand that statements within 'if' statement are executed only when 'if' condition is true.

Output of the program

Please enter your choice: 1
Dear Learner





© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.