First Steps in Java — Part 4

mike dietz
7 min readMay 6, 2020

--

Operators

1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input | 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays

Photo by Science in HD on Unsplash

Our today’s topic is operators. With them, we can perform operations on variables and values. For the example code, 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. 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 the right and computes a result.
We distinguish between additive (+ -) and multiplicative (* / %) operators.

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 (— -).

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 (< > <= >= instanceof) and equality (== !=).

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 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.

Assignment
The assignment operator works from right to left! It assigns a value, or a variable, or a method to a variable.

The following compound statements combine the assignment operator with an arithmetic operator to shorten the syntax.
+= -= *= /= %=

The compound statements can also be applied to bitwise operators. For bitwise operators see below.
^=
|= <<= >>= >>>=

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>

Bitwise
The bitwise operators compare bits in bytes and return 1 for true and 0 for false. All 8 bits of two bytes are compared and evaluated so that the result of the comparison is a new byte.

AND Operator &
If both bits have a value of 1, the value of 1 is returned.

OR Operator |
If one of the bits has a value of 1, the value 1 is returned

XOR Operator ^
Only if one of the two bits has a value of 1, the value 1 is returned

Complement Operator ~
It reverses the bit values of the byte

Operator Precedence

If more than one operator is involved in an expression, there is an order in which the operators are evaluated. As we follow an order of precedence in arithmetic operations (brackets before of operations (power of and root of) before division before multiplication before addition before subtraction), there is an order of precedence for all operators.
The list starts with the operator with the most precedence:

[] access array element, . access object member, () parenthesis

  1. unary operators
  2. new object creation
  3. * / %
  4. + -
  5. << >> >>> bitwise shift
  6. relational
  7. equality
  8. bitwise
  9. ternary
  10. assignment

Operator Associativity

If two operators have the same precedence, they are evaluated in the order of their associativity, i.e. some are evaluated from left to right and others from right to left.

Right to Left
unary + and -
!
and ~
=
+=
and -=
*= and /= and %=
<<= and >>=
&= and ^=
++
and — —

Left to Right
arithmetic + and
* and / and %
<< and >> and <= and >=

== and != (is equal to and is NOT equal to)
& (bitwise and), | (bitwise or), ^ (bitwise XOR) and
&& (logical and), || (logical or)

Now, that we introduced the different categories of operators, we provide some examples.

ARITHMETIC

All the rules for the basic arithmetic operations apply.

+ Add the number to the left side of the + symbol to the right side of the + symbol, 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.

Arithmetic Operator Precedence

In mathematical operation, there is a precedence of operators, as you learned in school. The acronym BODMAS reminds us of the order.

BODMAS stands for Brackets, Order, (of) Division, Multiplication, Addition, Subtraction. That means that any operation within brackets has precedence, before the order (exponents, i.e. power OF and root OF), followed by division, multiplication, addition, and subtraction.

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

UNARY OPERATOR

Unary operators need only one operand to perform any operation. There are 5 different unary operators:

+ indicates a positive value,

- negates an expression

+ + increments a value by one; can be used as a post or a pre

- — decrements a value by one; can be used as a post or a pre

! logical complement

The unary + and will increment/decrement the value by one.

code:
int uResult = 1;
uResult — // returns 0;
uResult++ // returns 1;

RELATIONAL

Comparative Operators
< and > and <= and >= and == and !=
2 > 1 // returns false

Equality Operators
3 == 3 // returns true
3 != 3 // returns false

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

aka boolean expressions, always evaluate to true or false

Boolean Operators
! boolean NOT

&& boolean AND
|| boolean OR

^ boolean exclusive XOR only true if one side true and other side false

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 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
An if -else statement can be written as a ternary.
<expression> ?(if is true) <execute this expression> :(else) <execute this expression>

code:
(3 == 2) ? “3 equals 2” : “3 is not equal 2”;

BITWISE

Bitwise operators are used to compare individual bits of a byte. They can be used with the integer types char, short, int, long, and byte. For a refresher, check the data types in part 2 again.

The bitwise operators work like logical operators but apply to two bits instead of two statements.

& AND return 1, if both operands equal 1
| OR returns 1, if one of the two (and also both) equal(s) 1
^ XOR returns 1, if one, and only, one of the two bits equals 1
~ Complement reverses 0s and 1s

For our examples, we use two binary numbers.

code:
int number1 = 12; // in binary: 0000 1100
int number1 = 9; // in binary: 0000 1001

We will compare each bit of the two numbers with each other.
12 & 9 = 8 // binary: 0000 1000
12 | 9 = 13 // binary: 0000 1101
12 ^ 9 = 5 // binary: 0000 0101
number1>>1 = 6 / 0000 0110
number1>>2 = 3 / 0000 0011
number1<<1 = 24 / 0001 1000
number1<<2 = 48 / 0000 0011

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.
Create a file MathMethods.java and practice the following methods.

double Math.pow(2, 3); // returns 8
double Math.exp(2); // returns e²
double Math.sqrt(16); // returns 4
double Math.cbrt(27); // returns 3
double Math.abs(-2); // returns 2
double Math.max(2,3); // returns 3
double Math.min(2,3); // returns 2

Get the code for this lesson at GitHub.

Tomorrow, our attention will be focused on strings. So long.

--

--