Chapter 4: Conditionals in Java

Introduction to Conditionals

Sometimes we want to watch comedy videos on YouTube if the day is Sunday

Sometimes, we order junk food if it is our friend's birthday in the hostel

You might want to buy an Umbrella if it's raining and you have the money

You order the meal if also or your favorite bhindi is listed on the menu.

All these are decisions which depends on a certain condition being met.

In Java, we can execute instructions on a condition being met.

Decision making Instructions in Java

If-Else Statement

The syntax of an If-Else statement in Java looks like that of C++ and JavaScript. Java has a similar syntax too.

Syntax:

IfElseSyntax.java
if (condition-to-be-checked) {
    // Statements if condition is true;
} else {
    // Statements if condition is false;
}

Code Example:

IfElseExample.java
int a = 29;
if (a > 18) {
    System.out.println("You can drive");
}

Note: The else block is optional

Relational Operators in Java

Relational operators are used to evaluate conditions (true or false) inside the if statements.

Operator Description Example
== Equals a == b
>= Greater than or equal to a >= b
> Greater than a > b
< Less than a < b
<= Less than or equal to a <= b
!= Not equals a != b

Note: '=' is used for assignment whereas '==' is used for equality check.

The condition can be either true or false.

Logical Operators

&&, || and ! are most commonly used logical operators in Java

These are read as:

  • && → AND
  • || → OR
  • ! → NOT
  • Used to provide logic to our Java programs

    AND Operator (&&)

    Evaluates to true if both the conditions are true

    Y && Y=Y
    Y && N=N
    N && Y=N
    N && N=N

    Y → true, N → false

    OR Operator (||)

    Evaluates to true when at least one of the conditions is true

    Y || Y=Y
    Y || N=Y
    N || Y=Y
    N || N=N

    Y → true, N → false

    NOT Operator (!)

    Negates the given logic (true becomes false and false becomes true)

    !Y=N
    !N=Y

    Y → true, N → false

    Else If Clause

    Instead of using multiple if statements, we can also use else if along with if thus forming an if-else-if-else ladder

    Using such kind of logic reduces indents. Last else is executed only if all the conditions fail.

    Syntax:

    ElseIfSyntax.java
    if (condition1) {
        // Statements;
    } else if (condition2) {
        // Statements;
    } else if (condition3) {
        // Statements;
    } else {
        // Statements;
    }

    Switch Case Control Instruction

    Switch-Case is used when we have to make a choice between number of alternatives for a given variable

    Syntax:

    SwitchSyntax.java
    switch (var) {
        case C1:
            // Code;
            break;
        case C2:
            // Code;
            break;
        case C3:
            // Code;
            break;
        default:
            // Code;
    }

    Note:

  • Var can be an integer, character or String in Java.
  • A switch can occur within another but in practice this is rarely done.
  • Practice Set

    1. Student Pass/Fail Program

    StudentResult.java
    import java.util.Scanner;
    
    public class StudentResult {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            
            System.out.print("Enter marks for subject 1: ");
            int sub1 = scanner.nextInt();
            System.out.print("Enter marks for subject 2: ");
            int sub2 = scanner.nextInt();
            System.out.print("Enter marks for subject 3: ");
            int sub3 = scanner.nextInt();
            
            double total = (sub1 + sub2 + sub3) / 3.0;
            
            if (total >= 40 && sub1 >= 33 && sub2 >= 33 && sub3 >= 33) {
                System.out.println("Student Passed");
            } else {
                System.out.println("Student Failed");
            }
            
            scanner.close();
        }
    }

    2. Income Tax Calculator

    IncomeTax.java
    import java.util.Scanner;
    
    public class IncomeTax {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            
            System.out.print("Enter your income: ");
            double income = scanner.nextDouble();
            double tax = 0;
            
            if (income <= 250000) {
                tax = 0;
            } else if (income <= 500000) {
                tax = (income - 250000) * 0.05;
            } else if (income <= 1000000) {
                tax = 250000 * 0.05 + (income - 500000) * 0.20;
            } else {
                tax = 250000 * 0.05 + 500000 * 0.20 + (income - 1000000) * 0.30;
            }
            
            System.out.println("Income Tax: " + tax);
            scanner.close();
        }
    }

    Chapter 4 - Practice Set

    1. Student Pass/Fail

    Write a program to find out whether a student is pass or fail; if it requires total 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as input from the user.

    2. Income Tax Calculator

    Calculate income tax paid by an employee to the government as per the slabs: 2.5L-5.0L (5%), 5.01-10.0L (20%), Above 10.01 (30%). No tax below 2.5L.

    3. Day of the Week

    Write a Java program to find out the day of the week given the number [1 for Monday, 2 for Tuesday ... and so on!]

    4. Leap Year

    Write a Java program to find whether a year entered by the user is a leap year or not.

    5. Website Type

    Write a program to find out the type of website from the URL: .com → Commercial website, .org → Organization website, .in → Indian Website

    ← Previous: Strings Next: Loops →