Like any other programming language, Java has expressions. Expressions are series of one or more literals and/or variables, connected by operators, that yield a value. For example, in this line:
a = (b + c) * d;
+ and * are operators, and “(b + c) * d” is an expression. Expressions are evaluated using the same rules as arithmetic: values within parentheses first, then multiplication and division, then addition and subtraction.
Note: for an excellent tutorial on these topics, visit W3Schools Java Operators.
Arithmetic Expressions
The operators used for arithmetic in Java are:
Operator | Function |
+ | Addition |
– | Subtraction, or a minus sign to multiply by -1 |
* | Multiplication |
/ | Division |
% | Modular arithmetic |
++ | Increment. When placed before a numeric value, the value is first incremented by 1 and then evaluated; when placed after a numeric value, the value is evaluated and then incremented by 1. |
– – | Similar to ++, but the value is decremented by 1 rather than incremented. |
| | Bitwise “or.” Each bit of the expression on the left is matched to the corresponding bit of the expression on the right. The corresponding bit in the result is 1 if either of the source expression bits is 1; otherwise the result is 0. For example, the expression 1 | 2 has the value 3. |
& | Bitwise “and.” Each bit of the expression on the left is matched to the corresponding bit of the expression on the right. The corresponding bit in the result is 1 if both of the source expression bits are 1; otherwise the result is 0. For example, the expression 1 & 2 has the value 0. |
And of course, expressions that use the arithmetic operators produce numeric values.
Assignment Operators
These operators change the value of a variable.
Operator | Effect |
x = y | Sets x equal to y |
x += y | Equivalent to x = x + y |
x -= y | Equivalent to x = x – y |
x *= y | Equivalent to x = x * y |
x /= y | Equivalent to x = x / y |
x |= y | Equivalent to x = x | y |
x &= y | Equivalent to x = x & y |
Because the “x” in each of the above examples is itself a value after assignment, Java also lets you use the results in more assignments within a single statement, proceeding right to left. For example, this code:
int a = 3;
int b = 3;
int c = 3;
a *= b += c;
System.out.println("a=" + a + " b=" + b + " c=" + c);
displays the result:
a=18 b=6 c=3
First, c is added to b (3 + 3), making b equal to 6. Then a is multiplied by the new value of b (3 * 6), making a equal to 18.
We hasten to point out, though, that nobody does this except with the “=” operator; anything else is much too confusing. Just because a thing can be done doesn’t mean it must be done.
Logical Expressions
Computer programs have to make decisions, of course, and these are based on logical expressions: expressions whose value is either true or false.
A boolean by itself may be such an expression; remember the variable “shouldPrint” in the first lesson? But often logical expressions are the result of comparisons and other combinations of comparison operators and logical operators. Just as in arithmetic expressions, parentheses can be used to affect the order in which the parts of the expression are evaluated and hence the ultimate value of the expression.
Here are the comparison operators used in Java:
Operator | Meaning |
== | True if the expression on the left side is equal to the expression on the right; otherwise false. For example, 3 == 1 + 2 is true. |
!= | True if the expression on the left side is unequal to the expression on the right; otherwise false. For example, 3 != 1 + 2 is false. |
< | True if the value on the left is less than the value on the right. |
> | True if the value on the left is greater than the value on the right. |
<= | True if the value on the left is less than or equal to the value on the right. |
>= | True if the value on the left is greater than or equal to the value on the right. |
And here are the logical operators:
Operator | Meaning |
|| | Or. x || y is true if either x or y is true. |
&& | And. x && y is true if both x and y are true. |
! | Not. For example, if x is true, !x returns false. |
instanceof | Used with and Object on the left and a class or interface name on the right, returns true if the operand on the left is an instance of the named class or one of its superclasses, or an implementation of the named interface or one of its superinterfaces. (We’ll get to interfaces later.) For example: wonderWoman instanceof Superhero would probably be true. |
Of course, comparison operators and logical operators can be combined to create logical expressions, such as:
a == b || c >= d
Logical expressions are evaluated left to right, with && having precedence over || (although expressions in parentheses are evaluated first, of course).
Furthermore, Java will stop evaluating the expression once the outcome is inevitable. If two operands are joined by || and the left side is true, Java won’t try to evaluate the right side; conversely, if two operands are joined by && and the left side is false, Java won’t try to evaluate the right side.
Logical operations can be grouped by parentheses, and the “not” operator can apply to a parenthesized expression. For example:
boolean a;
boolean b;
boolean c;
boolean d;
.
.
.
boolean b1 = !a && !b;
boolean b2 = !(a || b);
Thanks to DeMorgan’s laws, b1 and b2 are equivalent.
Concatenation
Finally, the String class has its own operator: +, used to concatenate strings, which you met in the previous section. When a String (or String literal) is used on either side of a plus sign, the result is the two operands, converted automatically to String if necessary, concatenated. For example,
String string1 = "Now is the time for all good men to be ";
boolean boolean1 = (1 + 1) == 2;
System.out.println(string1 + boolean1);
produces the line:
Now is the time for all good men to be true
Casting
Even more finally, there are times when you want to treat a variable or literal like something it doesn’t match but with which it is compatible. For example, you might want to assign an int value to a long. The compiler won’t let you do that, even though an int can fit into a long. One way to handle that is by casting–the temporary treatment of a value as belonging to another type. Casting is done by prefixing the value in question by the temporary type in parentheses. For example:
long l = 1;
int i;
i = l;
will be rejected because l is not an int, even though its value can fit into an int. You can solve this problem by changing the last line to
i = (int) l;
Exercise
- In your Eclipse workspace, create a new Java project named “Lesson-02-Exercise-02.”
- In the src folder, create a package named “org.practicaljava.lesson02.exercise-02”.
- Right-click on the package name and select New/Class from the popup menu. Name the class Lesson02Exercise02, check the box marked “public void static main(String[] args)”, and click Finish.
- The editor now shows your new class. Here’s what you need to do.
- At the class level, define two static boolean variables named theWorldIsRound and theWorldIsFlat.
- At the class level, define a static Long (note the capitalization–this is an object, not a primitive) variable named earthCircumference. Do not initialize this variable.
- At the class level, define a static int variable named onePm, initialized to 13.
- In the main() method:
- set theWorldIsRound to true;
- set theWorldIsFlat to the opposite of theWorldIsRound;
- call a method named showEarthCircumference;
- set earthCircumference to 24000;
- call showEarthCircumference a second time;
- display “The world is round: “, followed by the value of theWorldIsRound, on the console;
- display “The world is flat: “, followed by the value of theWorldIsFlat, on the console;
- display “The time is “, followed by the value of onePm modulo 12, followed by ” pm”, on the console.
- In the showEarthCircumference method, if the value of earthCircumference is greater than 0, display “earthCircumference = “, followed by the value of earthCircumference, on the console. (See the HelloWorldClass class for an example of an if statement you can adapt to test the value of earthCircumference.)
This is the result to expect:
earthCircumference = 24000
The world is round: true
The world is flat: false
The time is 1 pm
Did you get this instead?
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because "org.practicaljava.lesson02.exercise02.Lesson02Excercise02.earthCircumference" is null
at org.practicaljava.lesson02.exercise02.Lesson02Excercise02.showEarthCircumference(Lesson02Excercise02.java:23)
at org.practicaljava.lesson02.exercise02.Lesson02Excercise02.main(Lesson02Excercise02.java:13)
If so, you forgot to check if earthCircumference was null before you checked its value. Use the “and” operator to add a test for null before the test of earthCircumference’s value.
Having trouble? You can download a solution here to import into Eclipse.
Now let’s learn about Naming Conventions.