Precedences of operators
We have seen arithmetic operators, boolean operators, and relational operators.
They can all be used in one expression, so we need to know their precedences.
The following table gives the precedences, with the highest precedence operators
first and the lowest ones last. For completeness, we include two operators that
we have not yet explained: ++ and -- .
Unary operators: + - ++ -- ! typecast
Binary arithmetic operators: */%
Binary arithmetic operators: +-
Arithmetic relations: <><=>=
Equality relations: == !=
Logical and: &&
Logical or: ||
Here are some examples of the use of precedences to eliminate parentheses.
(3 + 5) > (4 - 6) can be written as 3 + 5 > 4 - 6 ,
because + and - have higher precedence than > .
( true && (3<5)) == (4>5) is the same as true && 3<5 == 4>5 .
Functions and function calls (or function invocations) are common in mathe-
matics. For example, the square root function is used frequently. The function
call sqrt(25.0) yields the square root of 25.0 , which is 5.0 . Here, sqrt is the
name of the function and 25.0 is the argument of the function call. Java allows
function calls as well, although Java names for the mathematical functions are a
bit longer than those in mathematics.
In Java, functions are defined in classes . The Java class Math contains def-
initions of many mathematical functions. Other examples of classes are Date ,
which contains functions related to dates, and File , which contains functions
related to the file system on your computer.
Here is a Java function call to obtain the square root of 37.0 :
The prefix “ Math. ” is needed to indicate where the function resides: in class
Some of the function names in class Math are overloaded , which means that
the same name is used for two or more different functions. The type of the argu-
ment is used to distinguish between them. Functions with the same name gener-
ally do the same thing but on arguments of different types. Also, the type of the
result depends on the types of the arguments. For example, we have: