Java Arena
Step 3 of 6

Comparison operators

A condition is usually a comparison. Java has six comparison operators, and each one gives true or false:

Operator Means Example that's true
> greater than 5 > 3
>= greater than or equal to 3 >= 3
< less than 2 < 7
<= less than or equal to 7 <= 7
== equal to 4 == 4
!= not equal to 4 != 5

== compares, = assigns

Comparing uses two equals signs. With one, Java reads it as an assignment. An assignment has a value too, the value it stores: here that's the int 5, and an if needs true or false:

public class Main {
    public static void main(String[] args) {
        int number = 5;
        if (number = 5) {
            System.out.println("Five!");
        }
    }
}
What javac prints
Main.java:4: error: incompatible types: int cannot be converted to boolean
        if (number = 5) {
                   ^
1 error

With numbers the compiler catches this mistake. With a boolean variable (the next module introduces them) it can't: if (done = true) stores true in done, compiles without a warning, and the block always runs. To compare, always use ==.

These operators compare numbers. Comparing text is different, and the next module shows how.

Your task

Challenge 1 of 3

Read a number and print Correct! when it's exactly 7. Then always print Game over. For the input 7 the program prints:

Guess the number:
Correct!
Game over.

Challenge 2

Read a year and print That's before Unix time began. when it's earlier than 1970. (Unix time, which many computers use to count time, starts on 1 January 1970.) Always finish with Thanks! For the input 1969 the program prints:

Year:
That's before Unix time began.
Thanks!

Challenge 3

Read a status code. When it isn't 0, print Error code: and the code. When it's 500 or more, also print Server error. Always finish with Checked. For the input 503 the program prints:

Error code: 503
Server error
Checked.