First Steps in Java - Part 4
Operators
0: Intro | 1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input| 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays
Our today’s topic is operators. This article focuses on the mainly used operators and leaves out information about operator precedence, operator associativity and bitwise operators. As a beginner, you might not need to study all available operators at once. If you want to get information on the operators that fall short in this article, please check the Medium article First Steps in Java - Part 4, this version includes all information.
For the example code, we create a file Operators.java. The coding instructions are given in the different sections.
An operator performs an operation with one or more operands and returns a value.
A simple example might explain more than abstract definitions:
Our operation is : x + 5.
We use an addition operator, represented by the symbol +.
Our two operands are the value 5 and the variable x.
There are different categories of operators:
CATEGORIES OF OPERATORS
We introduce the different categories briefly in this section, more details and code examples can be found further down in the article or on Medium at First Steps in Java - Part 4. The types of operators are Arithmetic, Unary, Relational, Logical, Assignment, Ternary, Bitwise.
Arithmetic
These operators are for the basic math operations: addition, subtraction, division, multiplication, and remainder. The operator takes the operands to the left and to the right and computes a result.
We distinguish between additive (+ -) and multiplicative (* / %) operators.
+ Add the number to the left side of the + symbol to the right side of it: 3 + 2 = 5.
- Subtract the number to the right side of the - symbol from the number on the right side of the ‘-’ symbol, 3 — 2 = 1.
* Multiply the number of the right side of the * symbol by the number of the left side of the * symbol, 6 * 2 = 3.
/ Divide the number of the left side of the / symbol by the number of the right side of the / symbol, 6 / 2 = 3.
% Divide the number of the left side of the % symbol by the number of the right side of the % symbol and return the remainder, 5% 2 = 1.
code:
float x = 3;
float y = 2;
float result;
result = x + y; // returns 5.0
result = x - y; // returns 1.0
result = x / y; // returns 1.5
result = x * y; // returns 6
result = x % y; // returns 1
Compare your results.
Arithmetic Operator Precedence
In mathematical operation, there is a precedence of operators, as you might remember from school. The acronym BODMAS reminds us of the order.
BODMAS stands for Brackets, Order, (of) Division, Multiplication, Addition and Subtraction. That means that any operation within brackets has precedence, before the 'of' order (exponents, i.e. power OF and root OF), followed by division, multiplication, addition, and subtraction.
Unary
The word unary comes from the Latin word “unus” and means one. The unary operator needs only one operand. It either increases a whole number (increments an integer) or decrements it. Uses a double plus symbol for incrementation (++) and the double minus for decrementation (- -).
code
int uResult = 1;
uResult - - // returns 0;
uResult++ // returns 1;
Relational
The relational operator compares the two numbers on both sides with each other. It does not compute a result but instead compares the two sides and returns the evaluation, which is a boolean false or true.
We distinguish between comparison ( smaller than < greater than > smaller than or equal to <= greater than or equal to >= an instance of the class .instanceof) and equality (equal to == not equal to !=).
code:
int a = 1;
int b = 1;
a < b; // returns false
a > b; // returns false
a <= b; // returns true
a >= b; // returns true
a == b; // returns true
a != b; // returns false
Logical
The logical operators are conditional operators. Its two operands are to the left and the right of the operator and the operation returns a boolean that evaluates to true or false.
In the case of the AND operator (&&), both expressions have to be true (or false if ! is used as a boolean NOT). If the first expression to the left of the operator evaluates to false, then the comparison is finished.
In the case of the OR operator ( || ) one of the two sides has to evaluate to true (or false if the ! is used). If the left side already evaluates to true, it returns true without evaluating the right side.
Boolean Operators
! boolean NOT
&& boolean AND
|| boolean OR
^ boolean exclusive XOR only true if one of the two sides is true
code:
int c = 3;
int d = 4;
(c < d) && (d > c) ; // returns true
!(c < d) && (d > c) ; // returns false
(c == d) || (d > c) ; // returns true
(c < d) ^ (d > c) ; // returns false
Assignment
The assignment operator works from right to left! It assigns a value, or a variable, or a method to a variable, e.g. int x = 5 or int y = x or int z = addFunction().
The following compound statements combine the assignment operator with an arithmetic operator to shorten the syntax: += -= *= /= %=
The example x = x + 5 can be written as x += 5 in a compound statement. The intial value of x is added to the value 5 and the result stored in the variable x, the initial value is then overwritten. All other operations are done in the same way.
code:
int e = 6, f = 7, g = 8, h = 9;
e += 1; // returns 7
f -= 3; // returns 4
g *= 3; // returns 24
h /= 3; // returns 3
Ternary
The ternary operation is a sugar syntax for an if&else statement. A condition is checked if it is true or not. The according statement is then applied.
(if) <statement> ? <is true: statement is executed> : (else) <is false: this statement is executed>
code:
(3 == 2) ? “3 equals 2” : “3 is not equal 2”; // returns “3 is not equal 2”
Bitwise
The bitwise operators are used to compare and modify bits in bytes. For comparison, the operators AND &, OR | and XOR ^ are available. For byte modification, use the bitwise shift operators.
Check the full version article on Medium for more information on bitwise operation.
MATHEMATICAL OPERATIONS
For mathematical operations in Java we utilize the math class, which is included in the library java.lang and, therefore does not need to be imported. There are plenty of functions available. Here is just a small selection.
double Math.pow(2, 3); // 2 raised by the power of 3; returns 8
double Math.sqrt(16); // squareroot of 16; returns 4
double Math.cbrt(27); // cuberoot of 27; returns 3
double Math.abs(-2); // the absolute value; returns 2
double Math.max(2,3); // the max value of the two provided arguments; returns 3
double Math.min(2,3); // the min value of the two provided arguments; returns 2
The code for this lesson is available at GitHub.
This lecture is also available on Medium, First Steps in Java - Part 4.