Calculate Age in Java
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.
Java Program
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
Core Logic
Subtracting the birth year from the current year gives the age directly, with no loop or condition needed.
- 1
birthYearholds2000andcurrentYearholds2024. - 2
currentYear - birthYearevaluates to24. - 3The result is stored in
ageand printed with a label.
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
Approach 2: Java 8
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
Core Logic
The subtraction can be wrapped in a named lambda, turning 'compute an age' into a small reusable function.
- 1
IntBinaryOperator ageFrom = (current, birth) -> current - birth;stores the subtraction logic as a lambda. - 2
ageFrom.applyAsInt(currentYear, birthYear)calls it, returning the same result the inline subtraction would. - 3The result is printed exactly as before.
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.