Java ProgramsBasics & I/OCalculate Age

Calculate Age in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Age is just the difference between the current year and the birth year — a single subtraction, as long as both years are known.

Given a birth year and the current year, calculate the person's age in years.

Input
birthYear = 2000, currentYear = 2024
Output
Age: 24

Java Program

Java
public class CalculateAge { public static void main(String[] args) { int birthYear = 2000; int currentYear = 2024; int age = currentYear - birthYear; // difference in years System.out.println("Age: " + age); } }

Output

Age: 24

Core Logic

Subtracting the birth year from the current year gives the age directly, with no loop or condition needed.

How It Works
  1. 1birthYear holds 2000 and currentYear holds 2024.
  2. 2currentYear - birthYear evaluates to 24.
  3. 3The result is stored in age and printed with a label.
With birthYear = 2000 and currentYear = 2024, currentYear - birthYear gives 24.
💡

Key Point: This assumes the birthday has already passed this year — a fully accurate calculator would also compare the birth month and day, which is why real-world age calculations often use java.time.Period instead of plain subtraction.

Key Concepts

intsubtractionvariables

Approach 2: Java 8

Java
import java.util.function.IntBinaryOperator; public class CalculateAgeLambda { public static void main(String[] args) { int birthYear = 2000; int currentYear = 2024; // The subtraction logic is stored as a lambda, named for what it computes IntBinaryOperator ageFrom = (current, birth) -> current - birth; int age = ageFrom.applyAsInt(currentYear, birthYear); System.out.println("Age: " + age); } }

Output

Age: 24

Core Logic

The subtraction can be wrapped in a named lambda, turning 'compute an age' into a small reusable function.

How It Works
  1. 1IntBinaryOperator ageFrom = (current, birth) -> current - birth; stores the subtraction logic as a lambda.
  2. 2ageFrom.applyAsInt(currentYear, birthYear) calls it, returning the same result the inline subtraction would.
  3. 3The result is printed exactly as before.
With currentYear = 2024 and birthYear = 2000, ageFrom.applyAsInt(2024, 2000) returns 24.
💡

Key Point: Naming the lambda ageFrom makes the call site read like a sentence, which is worth doing whenever a lambda is stored in a variable rather than passed inline.

Key Concepts

IntBinaryOperatorfunctional interfacelambda expression

Related Programs