CORE JAVA

ProwessApps Learning Portal

If Statement in Java


Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in Java programs using a decision control instruction.

In decision making structure programmer specifies one or more conditions to be evaluated or checked by the program, on the basis of result i.e. either true or false , statements get executed.

Below is the abstract representation of decision making statement ..

prowessapps.com

Java programming handles decision-making by supporting the following statements,

      1. Simple if Statement

      2. if-else Statement    

      3. if-else Ladder Statement    

      4. Nested if-else Statement    

      5. switch ... case Statement    


Simple if Statement :

If block contains the condition, if condition is true, then the statement will execute and if the condition is not true then the statement will not execute.

Syntax :


if(boolean_expression){
/*statements will execute if the boolean expression is true */
}               
                                    

Block Diagram :

prowessapps.com

Example:

Test.java Copy Code
public class Test
{
 public static void main(String []arg)
 {
  // local variable declaration:
  int a = 10; 
  // check the boolean condition
  if( a < 20 ) {
/* if condition is true then print the following */

    System.out.print("a is less than 20");
   }
  System.out.print("\nvalue of a is : "+a);
 }
}           

Explanation:

  • We declare a class named Test.
  • Inside the class, we define the main method, which is the entry point of the program.
  • We declare an integer variable a and initialize it with the value 10.
  • We use an if statement to check if the value of a is less than 20. If true, it executes the block of code within the if statement.
  • Inside the if statement, we print the message "a is less than 20".
  • After the if statement, we print the value of a.
  • The program terminates after executing the main method.

  • When you run this program, the output will be:

    
    a is less than 20
    value of a is : 10
                

    This output confirms that the condition in the if statement is true, so the message "a is less than 20" is printed, followed by the value of a.





advertisement