C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Age Difference Calculator Using Expressions

Problem Statement

Calculate the age difference between two people using arithmetic expressions and display who is older and by how many years.

import java.util.Scanner;

 

public class AgeDifferenceCalculator {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter first person's age: ");

        int age1 = sc.nextInt();

 

        System.out.print("Enter second person's age: ");

        int age2 = sc.nextInt();

 

        int difference = Math.abs(age1 - age2); // absolute difference

 

        System.out.println("\n------ Age Difference Result ------");

 

        if (age1 > age2) {

            System.out.println("First person is older by " + difference + " years");

        }

        else if (age2 > age1) {

            System.out.println("Second person is older by " + difference + " years");

        }

        else {

            System.out.println("Both persons are of the same age");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1:

INPUT :
Enter first person's age: 30
Enter second person's age: 24

OUTPUT :
------ Age Difference Result ------
First person is older by 6 years

OUTPUT 2:
 
INPUT :
Enter first person's age: 18
Enter second person's age: 25

OUTPUT :
------ Age Difference Result ------
Second person is older by 7 years


OUTPUT 3:
 
INPUT :
Enter first person's age: 40
Enter second person's age: 40

OUTPUT :
------ Age Difference Result ------
Both persons are of the same age

Explanation

1. Input Collection

int age1 = sc.nextInt();

int age2 = sc.nextInt();

  • Reads ages of two persons from the user.

2. Age Difference Using Expression

int difference = Math.abs(age1 - age2);

  • Uses an arithmetic expression
  • Math.abs() ensures the difference is always positive

3. Conditional Comparison

if (age1 > age2)

  • Checks who is older
  • Displays age difference accordingly

4. Same Age Condition

else

  • If both ages are equal, prints an appropriate message

Key Concepts Used

Arithmetic expressions
Math.abs() function
if–else conditions
User input using Scanner

📌 Short Exam Answer

This program calculates the age difference between two persons using arithmetic expressions. It compares both ages and displays who is older or if both are of the same age.