Use basic arithmetic operators to manipulate data including +, -, *, /, and %
Use increment and decrement operators
Use relational operators including ==, !=, >, >=, <, and <=
Use arithmetic assignment operators
Use conditional operators including &&, ||, and ?
Describe the operator precedence and use of parenthesis
Operators are special symbols that perform specific functions
They work on operands and give a result
Rich collection of operators in Java
Mathematical
Comparison
Equality
Assignment
Bit manipulation
We've already seen a few:
= assignment
+ addition/concatenation
. object access
VIDEO
Expressions combine operators and operands
Again, to produce a single result
Examples:
-34
weight * 2.73
2 * PI * r
a - (7 - b)
1 + 2 + 3 + 4
(x + y) * (2 - z + (5 - q)) / (1 - x)
The arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% modulo (remainder after division)
As in school, multiplication and division have precedence over addition and subtraction
If two numeric primitives, + adds them
Result will be:
A primitive
At least as wide as the widest operand
Remember the automatic "upcast" that occurs when mixing types
At least int because of promotion(!)
byte and short first get promoted to int, then added
Remember the primitives chart
byte a = 3;
byte b = 4;
byte sum = a + b; // ERROR: result is int, must downcast
byte sumOK = (byte) a + b; // OK
If either side is a String, + concatenates them together
The other side is automatically converted to a String if necessary
Example: String str = "Hello" + 2;
2 initially seen as an int
2 converted to a String
str will be assigned value "Hello2"
String s = "2";
int r = 2;
System.out.println(r + s); // what will the output be?
VIDEO
The modulo operator returns the remainder of a dividend and a divisor
int two = 11 % 3
// 3 fits into 11 a total of 3 times, leaving 2 as a remainder
int one = 29 % 2
// 2 fits into 29 a total of 14 times, leaving 1 as a remainder
int six = 13 % 7
// 7 fits into 13 a total of 1 time, leaving 6 as a remainder
Modulus is commonly used to determine whether a variable is even or odd
int number = 7;
int evenOrOdd = number % 2;
If "number" is an odd number, the result will be 1
If "number" is an even number, the result will be 0
Create a class called "MathMagic"
Within the main method, declare an int called "myNumber" and set the value to any whole number of your
choosing
Declare another double called "magic" and set the value to "myNumber" plus 2
Reassign "magic" to "magic" multiplied by 2
Reassign "magic" to "magic" subtracted by 2
Reassign "magic" to "magic" divided by 2
Reassign "magic" to "magic" subtracted by "myNumber"
Reassign "magic" to "magic" modulo 1
Print the value of "magic"
No matter the value of "myNumber," the result of "magic" should always be 0.0
VIDEO
The increment and decrements operators:
Modify value by 1
When used in an expression or assignment, they have "pre" or "post" behavior
If ++before, increment before
If after++, increment after
int x;
int y = 0;
x = y++; // what is the value of x after this line? ("post")
int x;
int y = 0;
x = ++y; // what is the value of x after this line? ("pre")
VIDEO
Create a class called "IncrementsAreWeird"
Within the main method, declare an int called "myNumber" and set the value to 8
Print the value of "myNumber" with a pre-increment
Print the value of "myNumber" with a post-increment
Print the value of "myNumber" with a pre-decrement
Print the value of "myNumber" with a post-decrement
Declare another int called "newNumber" and assign the value to "myNumber" with a post-increment
Print the value of "newNumber"
Reassign "newNumber" to "myNumber" with a pre-increment
Print the value of "newNumber"
Before you run this program, make a prediction for the value of each print statement in a comment
Notice each value that is printed to the console
Were you correct in all your predictions? Why or why not?
VIDEO
The relational operators:
> - Greater than
>= - Greater than or equal to
< - Less than
<= - Less than or equal to
== - Equal
!= - Not equal
Operate on numbers and return a boolean: true or false
Common mistake for beginners:
You don't use = to test equality in Java, you use ==
Remember, = is for assignment
== won't do what you think on Strings
It compares the two object references
You use .equals (the equals() method) (more later)
int age = 34;
boolean isMinor = (age < 21); // () not required, but looks cleaner
VIDEO
The conditional operators:
&& - Short-circuit AND
& - AND
|| - Short-circuit OR
| - OR
^ - Exclusive OR
! - Logical Complement (NOT)
Operate on booleans and return a boolean
&& and || work "short-circuit" style
Evaluate the first operand and only evaluate the second if necessary ("short-circuiting" it)
Since false AND <anything> is false, don't look at <anything>
Likewise for true OR <anything>
Why is there no short-circuit ^ operator?
VIDEO
Expressions that use multiple operators do not just flow left to right
They have an order of operation based on precedence
Think P.E.M.D.A.S. from math class, but not exactly
Parenthesis override all other precedence
int a = 2 + 9 * 3;
// "a" equals 29 and not 33 because multiplication has higher precedence than addition
int a = (2 + 9) * 3;
// "a" equals 33 because parenthesis have higher precedence than
// multiplication
VIDEO
We know that = is for assignment
We can do an operation and an assignment in one step
We'll call this "op="
op= can be any non-boolean operator
Examples are: +=, -=, *=, /=
y += 5 is the same as y = y + 5
NOTE: assignment is still right to left, op= doesn't change that
VIDEO
Create a class called "Precedence"
To demonstrate your understanding of precedence, rewrite the operations from the "MathMagic" class, but
complete the declaration, assignment, and operations regarding the "magic" int on a single line
You are limited to using only two sets of parenthesis to override precedence
On the second line, print the value of magic and make sure that it still equals 0
Your main method should only have 2 lines of code!
int magic = [your number] [all the operations];
System.out.println(magic);
VIDEO
"Upcasts" to a larger type are implicit and automatic
"Upcasts" or conversions may occur during operations
"Downcasts" to a smaller type must be made explicitly
Because you might lose data and/or precision
int + long -> long // int converted to long
float + double -> double // float converted to double
int + float -> float // int converted to float
float length = 2.1F; // 2.1F is shorthand for (float) 2.13
float width = 4.51F;
double area = length * width; // auto upcast to double
float approxArea = (float) area; // explicit downcast to float
Any type smaller than an int will automatically be promoted to an int during an operation
byte + byte -> int // bytes converted to int
short + short -> int // shorts converted to int
short + byte -> int // byte and short converted to int
Any operation in which you do not intend to receive an int will need to be explicitly cast back down
byte + byte -> (byte) byte // bytes converted back to byte
short + short -> (short) short // shorts converted back to short
short + byte -> (short) short // byte and short converted to short
When downcasting from a higher precision data type to a lower precision data type, the value can change
For example, downcasting from a double to an int
double high = 1.9;
double low = 1.1;
int newHigh = (int) high; // "newHighRange" equals 1
int newLow = (int) low; // "newLowRange" equals 1
Downcasting from a floating-point to an integer will always round down
VIDEO