2.2 - Boolean Expressions
You can compare values using relational operators:
== // equal to != // not equal to < // less than > // greater than <= // less than or equal to >= // greater than or equal to
With primitive types,
== and != compare the actual values. With reference types (objects), they compare whether the two variables point to the same object in memory, not whether the objects look the same.int a = 5; int b = 5; System.out.println(a == b); // true, comparing actual values String s1 = new String("cat"); String s2 = new String("cat"); System.out.println(s1 == s2); // false, different objects even though content matches
To check whether two objects hold the same content (like two strings with the same characters), use the
equals method instead. That’s covered in 2.6.<, >, <=, and >= only work on numeric values, to compare their relationship.You can compare an
int with a double, like 3 < 3.5. You can’t use these operators on strings (that won’t compile). To put strings in alphabetical order, use compareTo from 1.15.int x = 7; int y = 10; System.out.println(x < y); // true System.out.println(x > y); // false System.out.println(x <= 7); // true System.out.println(y >= 11); // false System.out.println(x == y); // false System.out.println(x != y); // true System.out.println(3 < 3.5); // true, an int can be compared with a double
Any expression using these operators evaluates down to a
boolean, either true or false.boolean isAdult = age >= 18;
That
boolean result can be stored in a variable (like isAdult), printed, or used directly as the condition of an if statement or a loop.Don’t mix up
= and ==. A single = stores a value (assignment), while == asks whether two values are equal. Writing if (x = 5) won’t compile, because x = 5 isn’t a boolean expression.