AP-Computer-Science ScienceAP
Conditionals and Equality Conditionals and Equality
If–else
Schematic syntax:
if (condition1) {
body1
} else if (condition2) {
body2
} else {
body3
}
Braces can be omitted for a single controlled statement, but using them helps avoid ambiguity.
Switch statements
The traditional colon-style switch can fall through into following cases. Use break to leave the switch.
switch (choice) {
case 1:
System.out.println("First");
break;
case 2:
System.out.println("Second");
break;
default:
System.out.println("Other");
}
Source: Java Language Specification §14.11.
Equality
==compares primitive values. For objects, it compares references..equals(...)is a method whose behavior depends on the class.String.equals(...)compares text; the inheritedObject.equals(...)implementation compares identity.
Correction to the original notes
The original claim that
==is equivalent to.equals(obj)is false in general. Two different objects can have equal contents.
String first = new String("Hello");
String second = new String("Hello");
System.out.println(first == second); // false
System.out.println(first.equals(second)); // true
Sources: Reference equality, Object.equals.
Related: Logical operators · Strings and characters