You can compare values using the many different operators. Integers, doubles, floats, and chars are the values that can be compared with these operators. You generally don’t use these operators to test or compare Objects. We’ll learn how to do that in future sections.
The == operator plus its two operands forms an expression. This kind of expression evaluates to a boolean value. A boolean value is either true or false. The two numbers being compared are either equal to each other or they are not equal.
The counterpart to the == operator is the != (not equal) operator.
Let’s take a look at a quick piece of code that compares two numbers with the equality operator.
The following operators can be used in Java to compare values between numbers.
Each of these operators plus its two operands forms an expression. This kind of expression evaluates to a boolean value. A boolean value is either true or false. The relation between the two numbers being compared is either true or false. For example, in the expression, a > b, a is either greater than b or it is not.
These operators can be used to find out whether a comparison between two numbers is true or false:
In mathematics, division returns a quotient and a remainder. In computing, sometimes we are interested in just the remainder. Modulo division returns the remainder and uses the modulo operator (%).
You can use the modulo operator to test whether a number is even or odd by finding out if its division by 2 results in a remainder of 0 or greater than 0.
// Test if a number is positive
(number > 0)
//Test if a number is negative
(number < 0)
//Test if a number is even by seeing if the remainder is 0 when divided by 2
(number % 2 == 0)
//Test if a number is odd by seeing if there is a remainder when divided by 2
(number % 2 > 0)
//Test if a number is a multiple of x (or divisible by x with no remainder)
(number % x == 0)