Arithmetic Operators
Java supports the same basic arithmetic operations and precedence rules (BEDMAS) as you are used to from math class:
The operators above are called binary operators because they require two numeric operands to work, one on the left of the operator and one on the right. You may sometimes need to use parentheses ( and ) to control the order of evaluation, and to improve readability as well. Here’s an example to demonstrate:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class ArithmeticOps { public static void main( String[] args ) { int a = 5; int b = 2; int c = a - b; System.out.println( "a + b = " + (a + b) ); System.out.println( "a - b = " + c ); System.out.println( "a * b = " + (a * b) ); System.out.println( "a / b = " + (a / b) ); System.out.println( "a % b = " + (a % b) ); } } |
a + b = 7
a – b = 3
a * b = 10
a / b = 2
a % b = 1
If you look at line 7 you’ll notice that I’ve used parentheses to perform the arithmetic operation (a+b) before concatenating it to the output string. Just like regular math, operations with the same precedence level are performed in order from left to right. Without the parentheses, line 7 would output 52 instead of the correct result of 7.
Lines 10 and 11 are also interesting. When operating on integer operands the division (/) and modulus (%) operators produce integer results (think of it like long division). In this case, the quotient of 5 / 2 is 2, and the remainder (modulus) is 1. Forgetting this can lead to tricky logic errors. A logic error occurs when your code compiles (i.e., no syntax errors) but it does not give the result(s) that you expect. For example, the quotient of 3 / 5 would be 0 (not 0.6) and the remainder 3.
In the code above, if a and/or b were declared as double variables instead, then the quotient would be 2.5 (as you would get on your calculator) and the remainder 1.0.
Compound Assignment Operators
Evaluating an arithmetic expression and then assigning the result to some variable is so common that Java supports special shorthand operators known as compound assignment operators.
Note that the right side of the expression is evaluated fully before the arithmetic operation on the left of the assignment operator (=) is applied.
Increment and Decrement Operators
Java also provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable. These are the unary increment ++, and unary decrement −− operators.
A unary operator only has one operand. The ++ and −− operators may be placed before or after a numeric variable. If it is prefixed (placed before) a variable it’s referred to as the prefix increment (++) or prefix decrement (−−) operator. If it is postfixed (placed after) a variable it’s referred to as the postfix increment (++) or postfix decrement (−−) operator.
There is a subtle but very important difference between postfix and prefix in terms of the order of evaluation:
Here is a short program to demonstrate the difference between the two. Try it!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class IncrementDecrement { public static void main( String[] args ) { int num = 3; System.out.println( "POSTFIX Increment Demo:" ); System.out.println( num ); // print 3 System.out.println( num++ ); // print 3 THEN postincrement System.out.println( num ); // print 4 System.out.println( "PREFIX Increment Demo:" ); num = 3; // re-assign 3 to num System.out.println( num ); // print 3 System.out.println( ++num ); // preincrement THEN print 4 System.out.println( num ); // print 4 } } |
POSTFIX Increment Demo:
3
3
4
PREFIX Increment Demo:
3
4
4
This subtle difference can lead to very hard to find logic errors. I suggest that you only use them in postfix form for consistency. By the way, the C++ language is based on a language called C, but it added some additional Object-Oriented Programming (OOP) features. Can you C why it was named C++? Strange but true!
CONSTANTS
In math, certain values (e.g., π) are constant values that should never change. Similarly, in programming, it can be useful to declare a variable as being unchangeable after it has been initialized. To do this in Java you need to add the keyword final before the data type, for example:
1 2 |
final double PI = 3.14; PI = PI * 2; // this now causes a compiler error |
You can see that if an attempt is made to modify a constant you will get a compiler error. In terms of style, constant names are always ALL_UPPERCASE and more than one word is separated by an underscore (_) character. This makes them stand out from regular variables and makes your code more readable.
The Math Class
Apart from the rich set of arithmetic operators above, Java also has a class called Math that contains methods for exponents, square root, and trigonometry. For now, you can think of a method as a function, and a class as a collection of methods – more on this later.
Here is a summary of commonly used methods in the Math class:
More information about the Math class can be found in the Java API. To use one of these methods, you must start with Math. followed by the name of the method. For example, we could call the square root method like so:
1 |
double root = Math.sqrt( 9.0 ); |
The Math class also declares two constant values that are commonly useful: Math.PI and Math.E.
You Try!
-
- Add an entry for “1-3 Arithmetic Operations” in your Learning Journal and answer the following questions:
- Try and predict the output of the following four statements, then try them in a program. Explain the order of operations in each case. Which one gives the most surprising result? Fix it using parentheses.
1234System.out.println( 1 + 2 + 3 );System.out.println( 1 + 2 + "Hello" );System.out.println( "Hello" + 2 + 3 );System.out.println( 1 + "Hello" + 3 ); - Try and predict the output of the following code, then try it in Dr.Java to see if your analysis is correct. If you were incorrect, explain what mistake(s) you made.
1234567int a = 11;int b = 3;int c = 5;System.out.println("result = " + (a % b + 5 / c));System.out.println("result = " + (c * (-5 / 2) + b % 3));System.out.println("result = " + ((c + a % 4) * 4 - b)); - There is a logic error in this program. The correct result should be 98.6F not 69.0F. Explain what is wrong with the code? Fix it!
12345678910public class TempConverter {public static void main( String[] args ) {double celsius = 37.0;double fahrenheit;fahrenheit = celsius * (9 / 5) + 32;System.out.println( celsius + "C is " + fahrenheit + "F" );}} - There is a method called random() in the Math class. Read about it in the Java API and then experiment with it in Dr Java. How could you use some basic arithmetic and explicit casting to generate a random integer between 1 and 6 (inclusive) using Math.random()? Thoroughly test your solution. Include your solution code in your Learning Journal.
- Update your glossary with terms you are unfamiliar with from the notes above.
- Try and predict the output of the following four statements, then try them in a program. Explain the order of operations in each case. Which one gives the most surprising result? Fix it using parentheses.
- Add an entry for “1-3 Arithmetic Operations” in your Learning Journal and answer the following questions: