Operators play a crucial role in the functionality of programming languages. In Java, operators are symbolic representations utilized for executing various operations, such as addition, subtraction, multiplication, and division. These symbols are fundamental for manipulating variables and values effectively. The subsequent section will delve into the diverse categories of operators employed in Java programming.
There are mainly eight types of operators in Java:
- Unary Operator
- Arithmetic Operator
- Relational Operator
- Ternary Operator
- Assignment Operator
- Bitwise Operator
- Logical Operator
- Shift Operator
Java Unary Operator
Unary operators in Java are operators that work with only one operand. These operators are utilized for different tasks such as increasing/decreasing a value by one, reversing an expression, and changing the value of a Boolean. Take a look at the table below.
| Operator | Name | Description |
|---|---|---|
+ |
Unary Plus | Unary plus operator; indicates positive value (numbers are positive without this, however) |
- |
Unary Minus | The Unary Minus operator can be used to make a positive value negative. |
! |
Logical Complement Operator | The Not operator is used to convert a boolean value. In other words, it is used to reverse the logical state of an operand. |
++ |
Increment | It is used to increase the value of an operand by one. It can be done in two possible ways. One is post-increment (operand++) and other is pre-increment (++operand).In post-increment, the value of the operand is used first, then its value is increased by one.In pre-increment, the value of the operand is incremented first by one, then the incremented value of the operand is used. |
-- |
Decrement | It is used to decrease the value of an operand by one. It can be done in two possible ways. One is post-decrement (operand--) and other is pre-decrement (--operand).In post-decrement, the value of the operand is used first, then its value is decreased by one.In pre-increment, the value of the operand is decrement first by one, then the decremented value of the operand is used. |
In pre-increment, the value of the operand is incremented first by one, then the incremented value of the operand is used.
In the case of pre-increment, the operand's value is first decreased by one, and then the updated value of the operand is utilized.
Java Unary Operator Example: ++ and --
Example
public class Main {
public static void main(String args[]) {
int x=+10;
System.out.println(x); //10
System.out.println(-x); //-10
}
}
Output:
10
-10
Java Unary Operator Example: Pre-increment and Post-increment
Example
public class Main {
public static void main(String args[]) {
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
}
}
Output:
10
12
Java Unary Operator Example: Pre-decrement and Post-decrement
Example
public class Main {
public static void main(String args[]) {
System.out.println(x--); //10
System.out.println(--x); //8
}
}
Output:
Java Unary Operator Example: Logical Complement Operator and Negation
Example
public class Main {
public static void main(String args[]) {
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Output:
-11
9
false
true
To read more: Unary Operators in Java
Java Arithmetic Operators
Arithmetic operators in Java are essential for executing addition, subtraction, multiplication, division, and modulo operations. These operators are fundamental for mathematical calculations.
| Operator | Name | Description |
|---|---|---|
+ |
Addition | Adds two numbers. |
- |
Subtraction | Subtracts one number from another number. |
* |
Multiplication | Multiplies two numbers. |
/ |
Division | Divides one number by another number. |
% |
Modulus | Divides and returns the remainder of two numbers. |
Java Arithmetic Operator Example
Example
public class Main {
public static void main(String args[]) {
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
Example
public class Main {
public static void main(String args[]) {
System.out.println(10*10/5+3-1*4/2);
}
}
Output:
To read more: Arithmetic Operators in Java
Java Shift Operators
The Java shift operator manipulates data at the bit level by moving the bits of a number either to the left or to the right. Below is a table illustrating the various types of shift operators available in Java.
| Operator | Operator Name | Description |
|---|---|---|
>> |
Right Shift Operator (Signed) | All of the bits shift to right by a given number using this operator. |
>>> |
Unsigned Right Shift Operator | It is similar to the right shift operator (signed). However, the vacant leftmost position is occupied with 0 in place of the signed bit |
Java Left Shift Operator
The Java operator << is used to shift all of the bits in a value to the left side of a specified number of times.
Java Left Shift Operator Example
Example
public class Main {
public static void main(String args[]) {
int x=+10;
System.out.println(x); //10
System.out.println(-x); //-10
}
}
Output:
10
-10
Java Right Shift Operator
The Java right shift operator >> is known as the left shift operator, which shifts the bits of the left operand to the left by the number of positions indicated by the right operand.
Java Right Shift Operator Example
Example
public class Main {
public static void main(String args[]) {
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2
Java Shift Operator Example: >> vs >>> (Unsigned Shift)
Example
public class Main {
public static void main(String args[]) {
// For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
// For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Output:
5
5
-5
1073741819
To read more: Shift Operators in Java
Java Relational Operators
In Java, relational or conditional operators are employed to assess the connection between two operands, including comparisons like less than, less than or equal to, greater than, greater than or equal to, equal to, and not equal to. These operators, also referred to as equality operators, yield Boolean outcomes of either true or false.
| Operator | Name | Description | ||||
|---|---|---|---|---|---|---|
|
> | Greater Than | If the value of the first operand is greater than the value of the second operand, the Greater Than operator returns true, otherwise false. | Greater Than | If the value of the first operand is greater than the value of the second operand, the Greater Than operator returns true, otherwise false. | |
|
>= | Greater Than or Equal to | When the value of the first operand is greater than or equal to the value of the second operand, the Greater Than or Equal to operator returns true, otherwise false. | = | Greater Than or Equal to | When the value of the first operand is greater than or equal to the value of the second operand, the Greater Than or Equal to operator returns true, otherwise false. |
== |
Equal to | Equal to operator checks whether the given operands are equal or not. If they are equal, they return true otherwise false. | ||||
!= |
Not Equal to | Not Equal to operator works just opposite to Equal to operator. It returns false if the operands are equal in value, otherwise true. |
Java Relational Operator Example
Example
public class Main {
public static void main(String args[]) {
int a=10;
int b=20;
System.out.println("(a < b) : " + (a<b));
System.out.println("(a > b) : " + (a>b));
System.out.println("(a <= b) : " + (a<=b));
System.out.println("(a >= b) : " + (a>=b));
System.out.println("(a == b) : " + (a==b));
System.out.println("(a != b) : " + (a!=b));
}
}
Output:
(a < b) : true
(a > b) : false
(a <= b) : true
(a >= b) : false
(a == b) : false
(a != b) : true
To read more: Relational Operators in Java
Java Bitwise Operators
In Java, bitwise operators are utilized for manipulating individual bits within a number across different integer types. These operators are particularly handy for executing update and query tasks within Binary Indexed Trees.
| Operator | Operator Name | Description |
|---|---|---|
| |
Bitwise OR | It is a binary operator which gives OR of the input values bit by bit. |
& |
Bitwise AND | It is a binary operator which gives AND of the input values bit by bit. |
^ |
Bitwise XOR | It is a binary operator which gives XOR of the input values bit by bit. |
~ |
Bitwise Complement | The Bitwise Complement operator is also a unary operator. It makes every bit 0 to 1, and 1 to 0. |
Java Bitwise OR (|) Operator Example
Example
public class Main {
public static void main(String args[]) {
int a = 10; // binary representation 1010
int b = 5; // binary representation 0101
// a | b = 1010 | 0101 = 1111
// the value of 1111 in decimal representation is 15
System.out.println("The value of a | b is: " + (a | b));
}
}
Output:
The value of a | b is: 15
Java Bitwise AND (&) Operator Example
Example
public class Main {
public static void main(String args[]) {
int a = 11; // binary representation 1011
int b = 5; // binary representation 0101
// a & b = 1011 & 0101 = 0001
// the value of 0001 in decimal representation is 1
System.out.println("The value of a & b is: " + (a & b));
}
}
Output:
The value of a & b is: 1
Java Bitwise XOR (^) Operator Example
Example
public class Main {
public static void main(String args[]){
int a = 11; // binary representation 1011
int b = 5; // binary representation 0101
// a ^ b = 1011 ^ 0101 = 1110
// the value of 1110 in decimal representation is 14
System.out.println("The value of a ^ b is: " + (a ^ b));
}
}
Output:
The value of a ^ b is: 14
Java Bitwise Complement Operator Example
Example
public class Main {
public static void main(String args[]){
int a = 5; // binary representation 0101
// ~a = 1010 which will be represented as 10 in decimal format
// The compiler will give 2's complement of this number which is -6
System.out.println("The value of ~a is: " + (~a));
}
}
Output:
The value of ~a is: -6
To read more: Bitwise Operators in Java
Java Logical Operators
Logical operators play a crucial role in multiple programming languages, enabling the execution of Logical NOT, OR, and AND operations that mirror the functions of OR and AND gates in the realm of digital electronics.
| Operator | Name | Description |
|---|---|---|
&& |
Conditional AND | The logical && operator does not check the second condition if the first condition is false. It checks the second condition only if the first one is true. |
|| |
Conditional OR | The logical OR operator does not check the second condition if the first condition is true. It checks the second condition only if the first one is false. |
! |
Logical NOT | The NOT operator is used to reverse the value of a Boolean expression. |
Java Logical AND (&&) Operator Example
Example
public class Main {
public static void main(String args[]) {
int a = 10;
int b = 5;
int c = 20;
// (a < b) evaluates to false. Therefore, (a < c) condition will not executed.
// Hence, the value of a will remain 10
if((a < b) && (++a < c))
System.out.println("if block is executed.");
else
System.out.println("else block is executed.");
System.out.println("The value of a is: " + a);
}
}
Output:
else block is executed.
The value of a is: 10
Java Logical OR (||) Operator Example
Example
public class Main {
public static void main(String args[]) {
int a = 10;
int b = 5;
int c = 20;
// the first condition (a > b) evaluates to true. Therefore, (a++ < c) will not be executed.
// Hence, the value of a will remain 10.
System.out.println(a > b || a++ < c);
System.out.println("The value of a is: " + a);
// the first condition (a < b) evaluates to false. Therefore, (a++ < c) will be executed.
// Hence, the value of a will be 11.
System.out.println(a < b || a++ < c);
System.out.println("The value of a is: " + a);
}
}
Output:
true
The value of a is: 10
true
The value of a is: 11
Java Logical NOT or Bitwise Complement (!)Operator Example
Example
public class Main {
public static void main(String args[]) {
int a = 10;
int b = 5;
// the condition (a > b) evaluates to true. After applying NOT operator, the true value
// changes to false.
System.out.println(!(a > b));
// the condition (a < b) evaluates to false. After applying NOT operator, the false value
// changes to true.
System.out.println(!(a < b));
}
}
Output:
false
true
To read more: Logical Operators in Java
Java Ternary Operator
The Java Ternary operator serves as a concise alternative to the if-then-else statement and is commonly utilized in Java development. This operator uniquely requires three operands, distinguishing it as the sole conditional operator of its kind in Java programming.
Java Ternary Operator Example
In the provided illustration, the comparison is made between two numbers to determine the maximum value.
Example
public class Main {
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Let's see another example.
In the demonstration below, we showcase how to determine the highest value among three numbers by employing the ternary operator. It's important to observe that this approach involves nesting ternary operators.
Example
public class Main {
public static void main(String args[]) {
int a = 10;
int b = 15;
int c = 13;
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("The maximum between the three numbers " + a + ", " + b + ", " + c + " " + "is: " + max );
}
}
Output:
The maximum between the three numbers 10, 15, 13 is: 15
Note: Though writing code using ternary operator takes less amount of code as compared to if-else statements, it is not always a good way to write code using ternary operator. Usually in complex logic or conditions, if-else statements take precedence over the ternary operator. Using ternary operator in complex logic makes the code difficult to understand.
To read more: Ternary Operators in Java
Java Assignment Operator
The assignment operator in Java is widely used for assigning the value from the right side to the variable on the left side. It is important to ensure that both operands have the same data type to avoid compiler errors. The associativity of assignment operators is from right to left, indicating that values on the right side are assigned to the left side.
Types of Assignment Operator
There exist two categories of assignment operators, namely:
- Single Assignment operator: This type involves the use of just the symbol (=).
- Compound Assignment operator: This category utilizes symbols like -, +, /, * in conjunction with the (=) operator.
Illustrated in the table below are the operations performed by various assignment operators.
| Operator | Name | Description |
|---|---|---|
= |
Simple Assignment | Assigns the value of the right side to the variable on the left side. |
+= |
Add and Assign | Adds the right operand to the left operand and assigns the result to the left operand. |
-= |
Subtract and Assign | Subtracts the right operand from the left operand and assigns the result to the left operand. |
*= |
Multiply and Assign | Multiplies the left operand by the right operand and assigns the result to the left operand. |
/= |
Divide and Assign | Divides the left operand by the right operand and assigns the quotient to the left operand. |
%= |
Modulus and Assign | Divides the left operand by the right operand and assigns the remainder to the left operand. |
Java Assignment Operator Example
Example
public class Main {
public static void main(String[] args) {
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
a %= 3; // 9 % 3 = 0
System.out.println(a);
}}
Output:
13
9
18
9
0
Note: In Java, the compound assignment operator performs implicit typecasting. The following program illustrates the same.
Java Assignment Operator Example: Adding Short
In this instance, we have utilized the compound operator +=. Likewise, we can apply the same approach to the remaining compound operators.
Example
public class Main {
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine. It is because implicit typecasting has occurred.
a=a+b; // Compile time error because 10+10=20 now int, and int can't be assigned to a shot without typecast
System.out.println(a);
}}
Output:
Compile time error
After Type Cast:
Example
public class Main {
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
To read more: Assignment Operators in Java
Java Operator Precedence
| Operator Type | Precedence |
|---|---|
| Unary | expr++ expr-- |
| Prefix | ++expr --expr +expr -expr ~ ! |
| Multiplicative | * / % |
| Additive | + - |
| Shift | <td> << </td>> >>> |
| Relational | <td> < </td> > <td> instanceof </td>= instanceof |
| Equality | == != |
| Bitwise AND | & |
| Bitwise XOR | ^ |
| Bitwise OR | | |
| Logical AND | && |
| Logical OR | || |
| Ternary | ? : |
| Assignment | = += -= *= /= %= &= ^= |= >=>= >>>= |
Conclusion
Java programming heavily relies on operators, which allow programmers to execute a wide range of tasks, from basic mathematical calculations to intricate bitwise manipulations. Proficiency in knowing the diverse categories of operators and their order of precedence is essential for crafting Java code that is both optimized and powerful. This segment furnishes an extensive exploration along with hands-on illustrations to initiate your journey into leveraging operators within Java programming.
Multiple Choice Questions
1) The output of relational operators is _______________.
- Double
- Characters
- Integer
- Boolean
Relational operators yield a Boolean value in programming.
2) Choose the odd one out of from the following.
In the provided choices, the unary operator is exclusively represented by the symbol -. On the other hand, the other three symbols are specifically intended for bitwise operations.
3) What will the result of the given print command be?
System.out.println("The output is: " + (1 || true));
- The output is: 1
- The output is: true
- Error
- The output is: false
In the OR (II) operator, it is necessary for both operands to be Boolean values. The initial operand in the print statement is an integer type, which will result in an error being thrown.
4) What is the result of shifting 5 by 2 positions to the left in Java?
- None of the above
To illustrate, if we take the binary number 5 represented as 00101 and perform a right shift operation by 2 positions, the result will be 10100. Converting 10100 from binary to decimal gives us the value 20.
5) What operator is typically used to determine if a number is even or odd solely through bitwise operations?
Odd numbers are distinguished by having 1 as the leftmost bit, whereas even numbers have 0 in that position. By applying the bitwise AND operation with 1 to a number, we can determine its parity. A result of 0 indicates an even number, while a result of 1 signifies an odd number.