Understanding Java Comparison Operators: Equal, Greater, Less and More - Quiz

Total: 5 questions

1. 

What type does a comparison operator return in Java?

Every comparison operator in Java returns a value of the primitive type boolean: either true or false. This result can be stored in a boolean variable or used directly as a condition in an if statement or a loop.

2. 

What is the difference between == and equals() when comparing objects?

The == operator compares references: it returns true only if both variables point to the same object in memory. The equals() method compares the logical content of objects. Two different String objects with the same text are equal by equals() but not by ==.

3. 

Which types can be compared with the ordering operators <, >, <=, >=?

Only primitive numeric types: byte, short, int, long, float, double and char (characters are compared by their Unicode values). Applying an ordering operator to boolean values or to objects is a compile-time error; for strings use compareTo().

4. 

Why does 0.1 + 0.2 == 0.3 evaluate to false in Java?

Because double stores numbers in binary form, 0.1 and 0.2 have no exact binary representation, and their sum is 0.30000000000000004. To compare floating-point values, check that the difference is smaller than a small tolerance (epsilon) or use BigDecimal for exact decimal arithmetic.

5. 

Why can == return false for two Integer objects with the same value?

Autoboxing caches Integer objects only for values from minus 128 to 127. Inside that range both variables refer to the same cached object, so == returns true; outside it two distinct objects are created and == compares different references. Always compare wrapper objects with equals().

Page 1 of 1