Comparison Operators and Type Compatibility
What you'll learn: How Java determines which types can be compared and how automatic type conversions affect relational operations.
Which Types Can Be Compared?
When you use relational operators like <, >, <=, or >=, Java needs both operands to be numeric types. The good news? You can freely compare different numeric types together—Java handles the details for you.
int age = 25;
double threshold = 18.5;
boolean result = age > threshold; // true — perfectly legal!
Implicit Widening in Comparisons
Just like in arithmetic expressions, Java automatically widens the narrower type before comparing:
byte small = 10;
long big = 100L;
boolean isLess = small < big; // byte widened to long, then compared
The byte value is promoted to long behind the scenes, making the comparison possible without any casting.
Type Compatibility Rules
- Numeric types (
byte,short,int,long,float,double,char) can all be compared with each other - boolean values cannot be compared using
<,>,<=, or>=— only==and!=work with booleans - When mixing types, Java promotes the smaller type to match the larger one (widening conversion)
int x = 5;
double y = 5.7;
boolean test = x < y; // x promoted to double (5.0), then 5.0 < 5.7 → true
Think of it like comparing measurements: you can compare 5 inches to 0.5 feet, but Java first converts both to the same unit before deciding which is larger.
Key Takeaway: Java allows comparisons between any numeric types by automatically widening the narrower type to match the wider one, but relational operators cannot be used with boolean values.