#
Java Operators
This tutorial explains to you how to use Java Operators. There are some examples as well.
In Java, we have :
Arithmetic Operators
Logical Operators
Assignment Operators
Unary Operators
Shift Operators
Relational Operators
Bitwise Operators
Ternary Operators
#
Arithmetic Operators
Operators: +, -, *, /, % (modulo)
Example:
var x = 1 + 20 - 10;
System.out.println(x);
#
Logical Operators
&& (logical AND)
|| (logical OR)
! (logical NOT)
Example:
// Returns false
System.out.println((1==1)&&(1==2));
// Returns true
System.out.println((1==1)&&(1==1));
// Returns true
System.out.println((1==1)||(1==2));
// Returns false
System.out.println(!(1==1));
#
Assignment Operators
In Java we can use the following assignment operators:
#
Unary Operators
Unary operators are the operators used with only one operand. In Java we can use the following unary operators:
Example:
var x = 10;
++x;
// Prints 11
System.out.println(x);
--x;
// Prints 10
System.out.println(x);
#
Shift Operators
The Shift Operators(<<, >>) are used to shift all the bits in a value to the left/right side of a specified number of times.
Example:
// Shift left "10" (binary) is transformed to "1000" (binary) = 8 (decimal)
System.out.println(2 << 2);
For testing the conversion you can use this converter.
#
Relational Operators
In Java we can use the following relational operators:
#
Bitwise Operators
Bitwise operators work on bits and performs bit-by-bit operation.
In Java, we can use the following bitwise operators:
For this example we consider: a = 1000 1100 b = 0000 1101
The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1.
#
Ternary Operators
A ternary operator is a simple replacement for if-then-else statement.
Its syntax is:
condition ? expression1 : expression2;
If the condition is "true", the operator will return "expression1", if not, the "expression2".
Example:
Integer examScore = 80;
String result = (examScore > 65) ? "PASS" : "FAIL";
// It prints "You PASS the exam."
System.out.println("You " + result + " the exam.");