Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculation and functions be it logical, arithmetic, relational etc. They are classified based on the functionality they provide. Here are a few types:
- Arithmetic Operators
- Unary Operators
- Assignment Operator
- Relational Operators
- Logical Operators
- Ternary Operator
- Bitwise Operators
- Shift Operators
This article explains all that one needs to know regarding the Logical Operators.
Logical Operators
These operators are used to perform logical “AND”, “OR” and “NOT” operation, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Let’s look at each of the logical operators in a detailed manner:
- ‘Logical AND’ Operator(&&): This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. For example, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero).
Syntax:condition1 && condition2
Example:
a = 10, b = 20, c = 20 condition1: a < b condition2: b == c if(condition1 && condition2) d = a+b+c // Since both the conditions are true d = 50.
Output:Var1 = 10 Var2 = 20 Var3 = 20 The sum is: 50
- 'Logical OR' Operator(||): This operator returns true when one of the two conditions under consideration are satisfied or are true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false.
Syntax:condition1 || condition2
Example:
a = 10, b = 20, c = 20 condition1: a < b condition2: b > c if(condition1 || condition2) d = a+b+c // Since one of the condition is true d = 50.
Output:Var1 = 10 Var2 = 1 Var3 = 10 Var4 = 30 One or both the conditions are true
- 'Logical NOT' Operator(!): Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false.
Syntax:
!(condition)
Example:
a = 10, b = 20 !(a<b) // returns false !(a>b) // returns true
Output:Var1 = 10 Var2 = 1 !(a < b) = true !(a > b) = false
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
a + b;
Here, the +
operator is used to add two variables a and b. Similarly, there are various other arithmetic operators in Java.
Operator | Operation |
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo Operation (Remainder after division) |
Example 1: Arithmetic Operators
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 17 a - b = 7 a * b = 60 a / b = 2 a % b = 2
In the above example, we have used +
, -
, and *
operators to compute addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a / b
in our program. The /
operator is the division operator.
If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.
In Java,
(9 / 2) is 4
(9.0 / 2) is 4.5
(9 / 2.0) is 4.5
(9.0 / 2.0) is 4.5
Java Unary Operator Examples
The unary operator works on a single operand. Following are the examples of unary operators supported in java. Assume A = 60 and B = 20.
Operator | Description | Example |
---|---|---|
~ (bitwise compliment) | Binary One's Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. |
++ (Increment) | Increases the value of operand by 1. | B++ gives 21 |
-- (Decrement) | Decreases the value of operand by 1. | B-- gives 19 |
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=
) to assign the value 10 to a variable called x:
Example
int x = 10;
The addition assignment operator (+=
) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 |
Relational Operators in Java
Relational Operators Supported Data Types
- The == and != operators can be used with any primitive data types as well as objects.
- The <, >, <=, and >= can be used with primitive data types that can be represented in numbers. It will work with char, byte, short, int, etc. but not with boolean. These operators are not supported for objects.
Relational Operators Example
package com.journaldev.java;
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
// objects support == and != operators
System.out.println(new Data1() == new Data1());
System.out.println(new Data1() != new Data1());
}
}
class Data1 {
}
Output:
Ternary Operator in Java
A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.
It's syntax is:
condition ? expression1 : expression2;
Here, condition is evaluated and
- if condition is
true
, expression1 is executed. - And, if condition is
false
, expression2 is executed.
The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the name ternary operator.
Example: Java Ternary Operator
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// take input from users
Scanner input = new Scanner(System.in);
System.out.println("Enter your marks: ");
double marks = input.nextDouble();
// ternary operator checks if
// marks is greater than 40
String result = (marks > 40) ? "pass" : "fail";
System.out.println("You " + result + " the exam.");
input.close();
}
}
Output 1
Enter your marks: 75 You pass the exam.
Suppose the user enters 75. Then, the condition marks > 40
evaluates to true
. Hence, the first expression pass is assigned to result.
Output 2
Enter your marks: 24 You fail the exam.
Now, suppose the user enters 24. Then, the condition marks > 40
evaluates to false
. Hence, the second expression fail is assigned to result.
When to use the Ternary Operator?
In Java, the ternary operator can be used to replace certain types of if...else
statements. For example,
You can replace this code
class Main {
public static void main(String[] args) {
// create a variable
int number = 24;
if(number > 0) {
System.out.println("Positive Number");
}
else {
System.out.println("Negative Number");
}
}
}
with
class Main {
public static void main(String[] args) {
// create a variable
int number = 24;
String result = (number > 0) ? "Positive Number" : "Negative Number";
System.out.println(result);
}
}
Output
Positive Number
Bitwise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree.
- Bitwise OR (|) –
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 ________ 0111 = 7 (In decimal)
- Bitwise AND (&) –
This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0.
For example,a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise AND Operation of 5 and 7 0101 & 0111 ________ 0101 = 5 (In decimal)
- Bitwise XOR (^) –
This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
For example,a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise XOR Operation of 5 and 7 0101 ^ 0111 ________ 0010 = 2 (In decimal)
- Bitwise Complement (~) –
This operator is unary operator, denoted by ‘~’. It returns the one’s compliment representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1, and every 1 to 0.
For example,a = 5 = 0101 (In Binary) Bitwise Compliment Operation of 5 ~ 0101 ________ 1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.
Output :
a&b = 5 a|b = 7 a^b = 2 ~a = -6 a= 5
Shift Operators: These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. General format:
number shift_op number_of_places_to_shift;
- Signed Right shift operator (>>) –
Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of dividing the number with some power of two.
For example,Example 1: a = 10 a>>1 = 5 Example 2: a = -10 a>>1 = -5 We preserve the sign bit.- Unsigned Right shift operator (>>>) –
Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is signed, and will extend the sign bit.
For example,Example 1: a = 10 a>>>1 = 5 Example 2: a = -10 a>>>1 = 2147483643 DOES NOT preserve the sign bit.- Left shift operator (<<) –
Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.
For example,a = 5 = 0000 0101 b = -10 = 1111 0110 a << 1 = 0000 1010 = 10 a << 2 = 0001 0100 = 20 b << 1 = 1110 1100 = -20 b << 2 = 1101 1000 = -40- Unsigned Left shift operator (<<<) –
Unlike unsigned Right Shift, there is no “<<<" operator in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical.Output :
a<<2 = 20 b>>2 = -3 b>>>2 = 1073741821