CORE JAVA

ProwessApps Learning Portal

If-else Statement in Java


If block contains the condition, if condition is true, then the statements of if block will execute and if the condition is false then the statement of else block will execute.

Syntax :


if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}               
                                    

Block Diagram :

prowessapps.com

Example:

Program to check the number is positive or negative.
Test.java Copy Code
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc; // Declare a Scanner object
        sc = new Scanner(System.in); // Initialize the Scanner object to read input from the console
        int x; // Declare an integer variable 'x'

        System.out.print("Enter any number: "); // Prompt the user to enter a number
        x = sc.nextInt(); // Read an integer input from the user and store it in 'x'

        // Check if the entered number is greater than or equal to 0
        if (x >= 0) {
            System.out.print("X is Positive"); // If true, print "X is Positive"
        } else {
            System.out.print("X is Negative"); // If false, print "X is Negative"
        }
    } // main method closed
}
OUTPUT 1:
Enter any number: 12
X is Positive
OUTPUT 2:
Enter any number: -12
X is Negative

Explanation:

  1. We import the Scanner class from the java.util package to facilitate user input.

  2. Inside the main method:

    • We declare a Scanner object sc to read input from the console.

    • We declare an integer variable x to store the user input.

    • We prompt the user to enter a number using System.out.print("Enter any number: ").

    • We read an integer input from the user using sc.nextInt() and store it in x.

    • We use an if-else statement to check if the value of x is greater than or equal to 0.

      • If true, we print "X is Positive".

      • If false, we print "X is Negative".

  3. The program terminates after executing the main method.





advertisement