Basic Java Operators
In this post, we feature a comprehensive article about the basic Java Operators. Basic Java operators are Arithmetic, Bitwise, Assignment, Relational, Logical, Ternary, Unary, Shift, and Equality Operators.
Table Of Contents
1. Overview
If you want to learn java, java operators are a great starting point. Java Operators are symbols that operate on one or more than one operand to give an output. Operators specify to the java interpreter to perform an operation.
2. Java Operators
Java Operators are the symbols to perform an operation. They help the interpreter to execute the operation. There are multiple type of operations in java.
2.1 Prerequisites
Java 8 is required on the Linux, Windows or Mac operating system. Eclipse Oxygen can be used for this example.
2.2 Download
You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.
2.3 Setup
2.3.1 Java Setup
Below is the setup commands required for the Java Environment.
Setup
JAVA_HOME="/desktop/jdk1.8.0_73" export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
2.4 IDE
2.4.1 Eclipse Oxygen Setup
The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
2.4.2 Launching IDE
Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screenshot below:
You can select the workspace from the screen which pops up. The attached image shows how it can be selected.
You can see the eclipse workbench on the screen. The attached screenshot shows the Eclipse project screen.
Java Hello World
class prints the greetings. The screenshot below is added to show the class and execution on the eclipse.
2.5 Arithmetic Operators
Arithmetic operators are used to execute arithmetic operations on java primitive data types. The operators are listed below:
- * (Multiplication)
- / (Division)
- % (Modulus)
- + (Addition)
- – (Subtraction)
The code below shows the arithmetic operators specified above with examples.
Arithmetic Operators
public class ArithmeticOperators { public ArithmeticOperators() { } public static void main(String[] args) { int g = 50, h = 70, i = 10, j = 90, k = 80, l = 60; String u = "You are", v = "Welcome"; System.out.println("g + h = " + (g + h)); System.out.println("g - h = " + (g - h)); System.out.println("u + v = " + u + v); System.out.println("g * h = " + (g * h)); System.out.println("g / h = " + (g / h)); System.out.println("g % h = " + (g % h)); } }
The command below executes the above code snippet:
Run Command
javac ArithmeticOperations.java java ArithmeticOperations
The output of the executed command is shown below.
2.6 Bitwise Operators
Bitwise operators are used to execute operations on single bits. They can also be used with numbers of integer type. Tree operations such as update and query use bitwise operators in a binary tree. The bitwise operators are listed below:
- & (AND operator) gives the result AND of input bit values.
- | ( OR operator) gives the result OR of input bit values.
- ^ ( XOR operator) gives the result XOR of input bit values.
- ~ ( Complement Operator) gives the result of input bits reversed.
The code below shows the Bitwise operators specified above with examples.
Bitwise Operators
public class BitwiseOperators { public BitwiseOperators() { } public static void main(String[] args) { int cbit = 0x0004; int dbit = 0x0003; System.out.println("cbit&dbit = " + (cbit & dbit)); System.out.println("cbit|dbit = " + (cbit | dbit)); System.out.println("cbit^dbit = " + (cbit ^ dbit)); System.out.println("~cbit = " + ~cbit); cbit &= dbit; System.out.println("cbit= " + cbit); } }
The command below executes the above code snippet:
Run Command
javac BitwiseOperators.java java BitwiseOperators
The output of the executed command is shown below.
2.7 Assignment Operators
The assignment operator is used to specify a value to the variable. The direction of the associativity is from right to left. The assignment operator is =.
The code below shows the assignment operator specified above with examples.
Assignment Operators
public class AssignmentOperators { public AssignmentOperators() { } public static void main(String[] args) { int h = 20, i = 10, j, k, l = 10, m = 4, n = 9; j = i; System.out.println("Value of j = " + j); h = h + 1; i = i - 1; l = l * 2; m = m / 2; System.out.println("Sum of h,i,l,m = " + h + ", " + i + ", " + l + ", " + m); h = h - 1; i = i + 1; l = l / 2; m = m * 2; h += 1; i -= 1; l *= 2; m /= 2; System.out.println("h,i,l,m (" + "applying shorthand operators)= " + h + ", " + i + ", " + l + ", " + m); } }
The command below executes the above code snippet:
Run Command
javac AssignmentOperators.java java AssignmentOperators
The output of the executed command is shown below.
2.8 Relational Operators
Relational operators are used to perform relational operations. The relational operations are equal to, not equal to, greater than, less than, less than equal to, and greater than equal to. These operators give a boolean result. These operations are used in looping and conditional statements. The relational operators are listed below:
- == (Equal to) gives a boolean result true if left-hand side value is equal to right-hand-side value.
- != (Not Equal to) gives a boolean result true if left-hand side value is not equal to right-hand-side value.
- < (less than) gives a boolean result true if left-hand side value is less than the right-hand side value.
- <= (less than or equal to ) gives a boolean result true if left-hand side value is less than or equal to the right-hand side value.
- > (greater than ) gives a boolean result true if left-hand side value is greater than the right-hand-side value.
- >= (greater than or equal to ) gives a boolean result true if left-hand side value is greater than or equal to the right-hand side value.
The code below shows the relational operators specified above with examples.
Relational Operators
public class RelationalOperators { public RelationalOperators() { } public static void main(String[] args) { int c = 30, d = 20; String u = "Welcome", v = "Welcome"; int array1[] = { 1, 2, 3 }; int array2[] = { 1, 2, 3 }; boolean condvar = true; System.out.println("c == d :" + (c == d)); System.out.println("c < d :" + (c < d)); System.out.println("c <= d :" + (c d :" + (c > d)); System.out.println("c >= d :" + (c >= d)); System.out.println("c != d :" + (c != d)); System.out.println("u == v : " + (u == v)); System.out.println("array1 == array2 : " + (array1 == array2)); System.out.println("condvar==true :" + (condvar == true)); } }
The command below executes the above code snippet:
Run Command
javac RelationalOperators.java java RelationalOperators
The output of the executed command is shown below.
2.9 Logical Operators in Java
Logical operators are used to execute logical operations such as AND and OR operations. These operations are based on digital gate operations. Given two conditions, the second condition is not executed during the operation if the first condition is false in the case of AND operation. These operators are listed below:
- && (AND) gives a boolean result true when both conditions are true.
- || (OR) gives a boolean result true if at least one condition is true.
The code below shows the logical operator (&&) in a Java example.
Logical Operators
public class LogicalOperators { public LogicalOperators() { } public boolean login(String username, String password, String u, String v) { if ((username.equals(u) && password.equals(v)) || (username.equals(v) && password.equals(u))) { return true; } else { return false; } } public void printMessage(boolean check) { if(check) { System.out.println("User is authenticated"); } else { System.out.println("Wrong uid or password"); } } public static void main(String[] args) { String u = "thomas"; String v = "password"; LogicalOperators logic = new LogicalOperators(); String username = "thomas"; String password = "password"; boolean check = logic.login(username, password, u, v); System.out.println("user"+username); logic.printMessage(check) ; username = "william"; password = "passwo1d"; check = logic.login(username, password, u, v); System.out.println("user"+username); logic.printMessage(check) ; } }
The command below executes the above code snippet related to the logical operator in Java:
Run Command
javac LogicalOperators.java java LogicalOperators
The output of the executed command is shown below.
2.10 Ternary Operators
Ternary operators are related to the if-else statement. It consists of three operands. Ternary refers to three operators. The operator format is typically like ‘condition ? if condition is true : if condition isfalse ‘
The code below shows the ternary operator example.
Ternary Operators
public class TernaryOperators { public TernaryOperators() { } public static void main(String[] args) { int d = 40, e = 20, f = 50, output; output = ((d > e) ? (d > f) ? d : f : (e > f) ? e : f); System.out.println("Maximum of three given numbers is " + output); } }
The command below executes the above code snippet:
Run Command
javac TernaryOperators.java java TernaryOperators
The output of the executed command is shown below.
2.11 Unary Operators
Unary operators have one operand. The operators are used for incrementing, decrementing, and negating the value. The operators are listed below:
- – (Unary minus) negates the input values.
- + (Unary plus) converts the input value to positive
- ++ (Increment) increments the input value by 1. Post Increment does increment after calculating the result. Pre-Increment increments first and then it computes the result.
- — (Decrement) decrements the input value by 1. Post decrement does decrement after calculating the result. Pre-decrement decrements first and then it computes the result.
- ! (Logical not) inverts the input value
The code below shows the unary operators specified above with examples.
Arithmetic Operators
public class UnaryOperators { public UnaryOperators() { // TODO Auto-generated constructor stub } public static void main(String[] args) { int g = 40, h = 14, i = 21, j = 33, k = 87, l = 56; boolean condvar = true; i = ++g; System.out.println("Value of i (++g) = " + i); i = h++; System.out.println("Value of i (h++) = " + i); i = --j; System.out.println("Value of i (--j) = " + i); i = k--; System.out.println("Value of i (k--) = " + i); System.out.println("Value of !condvar =" + !condvar); } }
The command below executes the above code snippet:
Run Command
javac UnaryOperators.java java UnaryOperators
The output of the executed command is shown below.
2.12 BitShift Operators
BitShift operators perform shift (left or right) operations on the bits. They are used for multiplying or dividing the input value by a number which is a power of two. The shift operators are :
- << (Left shift operator) performs the left shift on the bit. If the input is void, the result will be 0. It is used for multiplying the input value by a number which is a power of two.
- >>(Signed Right shift operator) performs the right shift on the bit. If the input is void, the result will be 0. It is used for dividing the input value by a number which is a power of two.
- >>> (UnSigned Right shift operator) performs the right shift on the bit. If the input is void, the result will be 0. The leftmost bit is set to zero value.
The code below shows the bitshift operators specified above with examples.
BitShift Operators
public class BitShiftOperators { public BitShiftOperators() { } public static void main(String[] args) { int c = 0x0003; int d = -30; System.out.println("c<<2 = " + (c << 2)); System.out.println("c>>2 = " + (c >> 2)); System.out.println("d>>>2 = " + (d >>> 2)); } }
The command below executes the above code snippet:
Run Command
javac BitShiftOperators.java java BitShiftOperators
The output of the executed command is shown below.
2.13 Instance Of
The instanceof operator takes the input object and checks the object type to a specified type. It is used for checking if the input object is an instance of a class, subclass, and an instance of a class that implements an interface.
The code below shows the instance of operator specified above with examples.
InstanceOf Operators
public class InstanceOfOperators { public InstanceOfOperators() { // TODO Auto-generated constructor stub } public static void main(String[] args) { Employee employee = new Employee(); Employee manager = new Manager(); System.out.println("employee instanceof Employee: " + (employee instanceof Employee)); System.out.println("employee instanceof Manager: " + (employee instanceof Manager)); System.out.println("employee instanceof Delegate: " + (employee instanceof Delegate)); System.out.println("manager instanceof Employee: " + (manager instanceof Employee)); System.out.println("manager instanceof Manager: " + (manager instanceof Manager)); System.out.println("manager instanceof Delegate: " + (manager instanceof Delegate)); } } class Employee { } class Manager extends Employee implements Delegate { } interface Delegate { }
The command below executes the above code snippet:
Run Command
javac InstanceOfOperators.java java InstanceOfOperators
The output of the executed command is shown below.
2.14 Precedence Rules
Precedence and associativity rules are applied if there are multiple operators. The rules help in finding which operators need to be executed before the other. The operators are listed below:
Operator | Precedence Rule | Associativity |
postfix | ++,– | right to left |
unary | ++, –,+,-,~,! | right to left |
multiplication, division, modulus | *, /, % | left to right |
addition | +,- | left to right |
shift | <<, >>, >>> | left to right |
relational | <, >, <=, >=, instanceof | left to right |
equal | ==, != | left to right |
AND (bitwise) | & | left to right |
Exclusive OR | ^ | left to right |
Inclusive OR | | | left to right |
AND | && | left to right |
OR | || | left to right |
ternary | ?, : | right to left |
assignment | = , += | right to left |
The operators are mentioned in the table above in the precedence order. Precedence is higher if the operator is at the top. Operators with higher precedence are executed first and then the operators with lower precedence. Operators in a row have equal precedence value. When operators have equal in an expression, the binary operators are executed from left to right and then the assignment operators from right to left.
The code below shows the precedence rules specified above with examples.
Precedence Rules
public class PrecedenceRules { public PrecedenceRules() { } public static void main(String[] args) { int g = 31, h = 43, i = 4, j = 54, k = 87, l = 98; System.out.println("g+h/j = " + (g + h / j)); System.out.println("g+h*j-k/l = " + (g + h * j - k / l)); } }
The command below executes the above code snippet:
Run Command
javac PrecedenceRules.java java PrecedenceRules
The output of the executed command is shown below.
3. Download the Source Code
You can download the full source code of this example here: Basic Java Operators