Java Operators
The forms of the assignment operator
Suppose you want to add some value to a variable. You may write something like this:
int n = 10;
n = n + 4; // The final value will be 14
The assignment operator =
has several forms. When combining it with an operation to avoid repeating the variable, it will look like this:
int n = 10;
n += 4; // The final value will be 14
As you can see, this form looks more concise. There are a few other possible forms such as *=
, /=
, %=
.
Reading numbers from the standard input
As a rule, to solve a problem you need to read some data from the outside world, process it, and output the result. The following program reads two numbers from the standard input with the help of the Scanner
class. It then adds them, and prints the sum.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum = a + b;
System.out.println(sum);
}
}
If we are certain that the input numbers can be quite large, we can read numbers as long
instead of int
:
long a = scanner.nextLong();
long b = scanner.nextLong();
long sum = a + b;
See? No more lines need to be changed in this code.
Arithmetic operators
In real life, we often perform arithmetic operations. They help us to determine the change returned after a purchase, calculate the area of a room, count the number of people in a queue, and so on. The same operations are used in programs. In Java, arithmetic operations are mathematical calculations that can be performed using arithmetic operators.
Binary arithmetic operators
The Java programming language provides operators to perform arithmetic operations:
- addition
+
- subtraction
-
- multiplication
*
- division
/
- remainder
%
These are called binary because they take two values as operands.
The following example prints the results of addition, subtraction, and multiplication.
System.out.println(13 + 25); // prints 38
System.out.println(20 + 70); // prints 90
System.out.println(70 - 30); // prints 40
System.out.println(30 - 70); // prints -40
System.out.println(21 * 3); // prints 63
System.out.println(20 * 10); // prints 200
The /
operator returns the integer part of the division of two integer numbers. Any fractional part, if it exists, is discarded.
System.out.println(8 / 3); // prints 2
System.out.println(41 / 5); // prints 8
The %
in Java is the modulo or remainder operator. It returns the remainder of the division of two numbers. Note, that when the dividend is less than the divisor, the quotient is zero and the remainder equals the dividend.
System.out.println(10 % 3);// prints 1, because 10 divided by 3 leaves a remainder of 1
System.out.println(12 % 4);// prints 0, because 12 divided by 4 leaves no remainder
System.out.println(5 % 9);// prints 5, because 5 divided by 9 leaves a remainder of 5
Writing complex expressions
The operations can be combined to create more complex expressions:
System.out.println(1 + 3 * 4 - 2); // prints 11
The order of operations follows the standard arithmetic rules. Multiplication has a higher priority level than addition and subtraction, so the operation 3 * 4
is calculated first.
To specify the order of execution, we can use parentheses:
System.out.println((1 + 3) * (4 - 2)); // prints 8
As in arithmetic, parentheses can be nested. You can also use them to group operations for clarity.
Unary operators
A unary operator takes a single value as the operand.
- The unary plus operator indicates a positive value. It's an optional operator.
System.out.println(+5); // prints 5
- The unary minus operator negates a value or an expression.
System.out.println(-8); // prints -8
System.out.println(-(100 + 4)); // prints -104
They both have a higher level of precedence than the multiplication and division operators.
The precedence order
In Java, precedence refers to the order of performing and grouping operations in an expression. Operations with higher precedence are performed before those with lower precedence. For example, multiplication and division have a higher precedence than addition and subtraction.
There is a precedence order of all arithmetic operators, including parentheses. The list below is sorted from the highest to the lowest precedence level:
- parentheses;
- unary plus/minus;
- multiplication, division, modulo;
- addition, subtraction.
Boolean type and operations
The boolean
is a data type that has only two possible values: false
and true
. This is also known as the logical type.
This type is a common way in programming languages to represent something that has only two opposite states like on or off, yes or no, etc.
If you are writing an application that keeps track of opening and closing a door you'll find it natural to use a boolean
to store the current door state.
boolean open = true;
boolean closed = false;
System.out.println(open); // true
System.out.println(closed); // false
Keep in mind, you cannot assign an integer value to a boolean
variable. In Java, 0 is not the same as false
.
Logical operators
Variables of the boolean
type are often used to build logical expressions using logical operators. Java has four logical operators NOT, AND, OR and XOR:
- NOT is a unary operator (an operator that performs an operation on a single operand) that reverses the
boolean
value. It is denoted as!
.
boolean f = false; // f is false
boolean t = !f; // t is true
- AND is a binary operator (a type of operator that takes two operands and performs an operation on them) that returns true if both operands are
true
, otherwise, it returnsfalse
. It is denoted as&&
.
boolean b1 = false && false; // false
boolean b2 = false && true; // false
boolean b3 = true && false; // false
boolean b4 = true && true; // true
- OR is a binary operator that returns
true
if at least one operand istrue
. Otherwise, it returnsfalse
. It is denoted as||
.
boolean b1 = false || false; // false
boolean b2 = false || true; // true
boolean b3 = true || false; // true
boolean b4 = true || true; // true
- XOR (exclusive OR) is a binary operator that returns
true
if boolean operands have different values, otherwise, it returnsfalse
. It is denoted as^
.
boolean b1 = false ^ false; // false
boolean b2 = false ^ true; // true
boolean b3 = true ^ false; // true
boolean b4 = true ^ true; // false
The precedence of logical operators
Here are the logical operations sorted in order of decreasing priorities in expressions: !
(NOT), ^
(XOR), &&
(AND), ||
(OR).
The following variable is true
:
boolean b = true && !false; // true, because !false is evaluated before &&
To change the order of execution you can use parentheses (...)
.
Comparing values using relational operators
Relational operators in Java are used for comparing values. They help in determining relationships between variables, such as checking if one value is greater than another or if two values are equal. These operators are essential for making decisions and controlling program flow based on specific conditions.
Java provides six relational operators to compare numbers:
==
(equal to)!=
(not equal to)>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)
The result of applying a relational operator to its operands will be a boolean value (true
or false
) regardless of the types of operands.
Comparing integer numbers
Relational operators allow you to easily compare, among other things, two integer numbers. Here are some examples:
int one = 1;
int two = 2;
int three = 3;
int four = 4;
boolean oneIsOne = one == one; // true
boolean res1 = two <= three; // true
boolean res2 = two != four; // true
boolean res3 = two > four; // false
boolean res4 = one == three; // false
Relational operators can be used in mixed expressions together with arithmetic operators. In such expressions, relational operators have lower priorities than arithmetic operators.
In the following example, first of all, two sums are calculated, and then they are compared using the >
operator.
int number = 1000;
boolean result = number + 10 > number + 9; // 1010 > 1009 is true
The result
is true
.
Joining relational operations using logical operators
In Java, you cannot write an expression like a <= b <= c. Instead, you should join two boolean expressions using logical operators like ||
and &&
.
Here is an example:
number > 100 && number < 200; // it means 100 < number < 200
Also, we can write parts of the expression in parentheses to improve readability:
(number > 100) && (number < 200);
But parentheses are not necessary here because relational operators have a higher priority than logical operators.
Here is a more general example of variables.
int number = ... // it has a value
int low = 100, high = 200; // borders
boolean inRange = number > low && number < high; // joining two expressions using AND.
The code checks if the value of number
belongs to a range.
So, logical operators allow you to join a sequence of relational operations into one expression.