# Conditionals and Equality

Source: https://cca.twango.dev/AP-Computer-Science/logical-operators

# Conditionals and Equality

## If–else

Schematic syntax:

```text
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.

```java
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](https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html#jls-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 inherited `Object.equals(...)` implementation compares identity.

> [!warning] 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.

```java
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](https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.21.3), [Object.equals](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-).

Related: [[logic|Logical operators]] · [[strings-and-characters|Strings and characters]]
