Contents
Operators in Java
Operators
Operators are the foundation of any programming language, enabling us to perform various computations, logic evaluations, and functions. Java offers several types of operators that are categorized based on the functions they perform. These include:
- Arithmetic Operators
- Unary Operators
- Assignment Operator
- Relational Operators
- Logical Operators
- Ternary Operator
- Bitwise Operators
- Shift Operators
This section focuses on Arithmetic Operators, which allow us to carry out mathematical operations on basic data types. These operators can either be unary (applied to one operand) or binary (applied to two operands). Let’s dive into each arithmetic operator in Java.
Arithmetic Operators in Java
1. Addition (+)
This binary operator is used to add two operands.
Syntax:
num1 + num2
Example:
int num1 = 10, num2 = 20;
int sum = num1 + num2;
Output:
num1 = 10
num2 = 20
The sum = 30
Java Code Example:
public class AdditionExample {
public static void main(String[] args) {
int num1 = 10, num2 = 20;
int sum = num1 + num2;
System.out.println("The sum = " + sum);
}
}
2. Subtraction (-)
This binary operator is used to subtract the second operand from the first operand.
Syntax:
num1 - num2
Example:
int num1 = 20, num2 = 10;
int difference = num1 - num2;
Output:
num1 = 20
num2 = 10
The difference = 10
Java Code Example:
public class SubtractionExample {
public static void main(String[] args) {
int num1 = 20, num2 = 10;
int difference = num1 - num2;
System.out.println("The difference = " + difference);
}
}
3. Multiplication (*)
This binary operator multiplies two operands.
Syntax:
num1 * num2
Example:
int num1 = 20, num2 = 10;
int product = num1 * num2;
Output:
num1 = 20
num2 = 10
The product = 200
Java Code Example:
public class MultiplicationExample {
public static void main(String[] args) {
int num1 = 20, num2 = 10;
int product = num1 * num2;
System.out.println("The product = " + product);
}
}
4. Division (/)
This binary operator divides the first operand (dividend) by the second operand (divisor) and returns the quotient.
Syntax:
num1 / num2
Example:
int num1 = 20, num2 = 10;
int quotient = num1 / num2;
Output:
num1 = 20
num2 = 10
The quotient = 2
Java Code Example:
public class DivisionExample {
public static void main(String[] args) {
int num1 = 20, num2 = 10;
int quotient = num1 / num2;
System.out.println("The quotient = " + quotient);
}
}
5. Modulus (%)
This binary operator returns the remainder when the first operand (dividend) is divided by the second operand (divisor).
Syntax:
num1 % num2
Example:
int num1 = 5, num2 = 2;
int remainder = num1 % num2;
Output:
num1 = 5
num2 = 2
The remainder = 1
Java Code Example:
public class ModulusExample {
public static void main(String[] args) {
int num1 = 5, num2 = 2;
int remainder = num1 % num2;
System.out.println("The remainder = " + remainder);
}
}
Example Program Implementing All Arithmetic Operators
The following Java program takes user input and performs addition, subtraction, multiplication, and division:
import java.util.Scanner;
public class ArithmeticOperators {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = sc.nextDouble();
System.out.print("Enter the second number: ");
double num2 = sc.nextDouble();
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
System.out.println("The sum of the two numbers is: " + sum);
System.out.println("The difference of the two numbers is: " + difference);
System.out.println("The product of the two numbers is: " + product);
System.out.println("The quotient of the two numbers is: " + quotient);
}
}
Input:
Enter the first number: 20
Enter the second number: 10
Output:
The sum of the two numbers is: 30.0
The difference of the two numbers is: 10.0
The product of the two numbers is: 200.0
The quotient of the two numbers is: 2.0
Java Unary Operator
Unary operators in Java operate on a single operand. These operators are used for tasks such as incrementing, decrementing, and negating values. Let’s explore the various unary operators and how they function.
Operator 1: Unary Minus (-
)
This operator is used to reverse the sign of a value, converting a positive value into a negative one, or vice versa.
Syntax:
-(operand)
Example:
// Java Program demonstrating Unary Minus
class UnaryMinus {
public static void main(String[] args) {
int num = 20;
System.out.println("Number = " + num);
// Applying unary minus
num = -num;
System.out.println("After applying unary minus = " + num);
}
}
Output:
Number = 20
After applying unary minus = -20
Operator 2: NOT Operator (!
)
This operator negates a boolean expression, flipping true
to false
and vice versa.
Syntax:
!(operand)
Example:
// Java Program demonstrating NOT Operator
class NotOperator {
public static void main(String[] args) {
boolean flag = true;
int a = 10, b = 1;
System.out.println("Initial flag: " + flag);
System.out.println("a = " + a + ", b = " + b);
// Applying NOT operator
System.out.println("Negated flag: " + !flag);
System.out.println("!(a < b) = " + !(a < b));
System.out.println("!(a > b) = " + !(a > b));
}
}
Output:
Initial flag: true
a = 10, b = 1
Negated flag: false
!(a < b) = true
!(a > b) = false
Operator 3: Increment (++
)
The increment operator increases the value of an operand by one. It can be used in two forms:
- Post-Increment: The operand is incremented after its current value is used.
- Pre-Increment: The operand is incremented before its current value is used.
Example:
int num = 5;
System.out.println("Post-increment: " + (num++)); // Uses current value, then increments
System.out.println("Pre-increment: " + (++num)); // Increments, then uses new value
Operator 4: Decrement (--
)
Similar to the increment operator, the decrement operator decreases the operand’s value by one and can also be used in two forms:
- Post-Decrement: Decrements the operand after its current value is used.
- Pre-Decrement: Decrements the operand before its current value is used.
Example:
int num = 5;
System.out.println("Post-decrement: " + (num--)); // Uses current value, then decrements
System.out.println("Pre-decrement: " + (--num)); // Decrements, then uses new value
Operator 5: Bitwise Complement (~
)
This operator inverts all the bits of the operand. It converts 0s to 1s and 1s to 0s.
Syntax:
~(operand)
Example:
// Java Program demonstrating Bitwise Complement Operator
class BitwiseComplement {
public static void main(String[] args) {
int num = 5;
System.out.println("Number: " + num);
// Applying bitwise complement
System.out.println("Bitwise complement: " + ~num);
}
}
Output:
Number: 5
Bitwise complement: -6
Example Program Demonstrating All Unary Operators
Here’s a comprehensive program that demonstrates the use of all basic unary operators with user input:
import java.util.Scanner;
public class UnaryOperatorsExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
// Unary plus
int result = +num;
System.out.println("Unary plus result: " + result);
// Unary minus
result = -num;
System.out.println("Unary minus result: " + result);
// Pre-increment
result = ++num;
System.out.println("Pre-increment result: " + result);
// Post-increment
result = num++;
System.out.println("Post-increment result: " + result);
// Pre-decrement
result = --num;
System.out.println("Pre-decrement result: " + result);
// Post-decrement
result = num--;
System.out.println("Post-decrement result: " + result);
sc.close();
}
}
Input:
Enter a number: 10
Output:
Unary plus result: 10
Unary minus result: -10
Pre-increment result: 11
Post-increment result: 11
Pre-decrement result: 11
Post-decrement result: 10
Java Assignment Operators
In Java, operators form the basic building blocks of programming, allowing developers to perform various types of calculations, comparisons, and logical operations. Assignment operators specifically help assign values to variables. They have right-to-left associativity, meaning the value on the right side of the operator is assigned to the variable on the left. Let’s dive into the different types of assignment operators used in Java.
Types of Assignment Operators:
1. Simple Assignment Operator (=
): The simple assignment operator is used to assign a value to a variable. The operand on the right-hand side must match the data type of the variable on the left-hand side.
Syntax:
variable = value;
Example:
public class AssignmentOperatorExample {
public static void main(String[] args) {
int num = 15;
String name = "Java";
System.out.println("num is assigned: " + num);
System.out.println("name is assigned: " + name);
}
}
Output:
num is assigned: 15
name is assigned: Java
2. Add and Assign (+=
): The compound +=
operator adds the value on the right to the value of the variable on the left and then assigns the result back to the variable on the left.
Syntax:
variable += value;
Example:
public class AddAssignExample {
public static void main(String[] args) {
int num1 = 5, num2 = 3;
num1 += num2;
System.out.println("After adding: " + num1);
}
}
Output:
After adding: 8
Note: This operator performs implicit type conversion if necessary. For instance, adding a double
to an int
using +=
will result in automatic narrowing conversion.
3. Subtract and Assign (-=
): The compound -=
operator subtracts the value on the right from the value on the left and then assigns the result back to the variable on the left.
Syntax:
variable -= value;
Example:
public class SubtractAssignExample {
public static void main(String[] args) {
int num1 = 10, num2 = 4;
num1 -= num2;
System.out.println("After subtracting: " + num1);
}
}
Output:
After subtracting: 6
4. Multiply and Assign (*=
): This operator multiplies the current value of the variable by the value on the right and assigns the result back to the variable on the left.
Syntax:
variable *= value;
a *= 2; // Equivalent to a = a * 2
Example:
public class MultiplyAssignExample {
public static void main(String[] args) {
int num1 = 4, num2 = 3;
num1 *= num2;
System.out.println("After multiplying: " + num1);
}
}
Output:
After multiplying: 12
5. Divide and Assign (/=
): This operator divides the current value of the variable by the value on the right and assigns the result back to the variable on the left.
Syntax:
variable /= value;
Example:
public class DivideAssignExample {
public static void main(String[] args) {
int num1 = 20, num2 = 4;
num1 /= num2;
System.out.println("After dividing: " + num1);
}
}
Output:
After dividing: 5
6. Modulus and Assign (%=
): This operator performs division and assigns the remainder back to the variable on the left.
Syntax:
variable %= value;
Example:
public class ModulusAssignExample {
public static void main(String[] args) {
int num1 = 17, num2 = 5;
num1 %= num2;
System.out.println("After modulus: " + num1);
}
}
Output:
After modulus: 2
Java Relational Operators
Relational operators in Java are binary operators used to compare two operands and return a boolean value indicating the result of the comparison. These operators are often used in control flow statements such as loops and conditionals.
General Syntax:
variable1 relation_operator variable2
1. Equal to (==)
The ==
operator checks if two operands are equal. If they are, it returns true
; otherwise, it returns false
.
Syntax:
var1 == var2
Example:
int var1 = 5, var2 = 10, var3 = 5;
System.out.println("var1 == var2: " + (var1 == var2)); // false
System.out.println("var1 == var3: " + (var1 == var3)); // true
Output:
var1 == var2: false
var1 == var3: true
2. Not Equal to (!=)
The !=
operator checks if two operands are not equal. It returns true
if the operands are unequal, and false
if they are equal.
Syntax:
var1 != var2
Loop Variables (Block Scope)
Variables declared inside a loop have scope limited to the loop. They cannot be accessed outside the loop.
Example:
int var1 = 5, var2 = 10, var3 = 5;
System.out.println("var1 != var2: " + (var1 != var2)); // true
System.out.println("var1 != var3: " + (var1 != var3)); // false
Output:
var1 != var2: true
var1 != var3: false
3. Greater than (>)
The >
operator checks if the left operand is greater than the right operand. If true, it returns true
; otherwise, false
.
Syntax:
var1 > var2
Example:
int var1 = 30, var2 = 20;
System.out.println("var1 > var2: " + (var1 > var2)); // true
Output:
var1 > var2: true
4. Less than (<)
The <
operator checks if the left operand is less than the right operand.
Syntax:
var1 < var2
Example:
int var1 = 10, var2 = 20;
System.out.println("var1 < var2: " + (var1 < var2)); // true
Output:
var1 < var2: true
5. Greater than or equal to (>=)
The >=
operator checks if the left operand is greater than or equal to the right operand.
Syntax:
var1 >= var2
Example:
int var1 = 20, var2 = 20;
System.out.println("var1 >= var2: " + (var1 >= var2)); // true
Output:
var1 >= var2: true
6. Less than or equal to (<=)
The <=
operator checks if the left operand is less than or equal to the right operand.
Syntax:
var1 <= var2
Example:
int var1 = 10, var2 = 10;
System.out.println("var1 <= var2: " + (var1 <= var2)); // true
Output:
var1 <= var2: true
Java Logical Operators
Logical operators are used to perform logical operations such as “AND,” “OR,” and “NOT,” similar to the functions of AND and OR gates in digital electronics. They combine two or more conditions or reverse the outcome of a given condition. An important point to remember is that in the case of the AND operator, the second condition is not evaluated if the first is false, while in the case of the OR operator, the second condition is not evaluated if the first is true. This feature is known as short-circuiting. Logical operators are commonly used in decision-making when multiple conditions need to be checked.
Logical Operators in Java
Let’s go through an example with some common logical operators in Java. Assume we have the following variables:
Syntax:
int a = 10;
int b = 20;
int c = 30;
AND Operator (&&
):
This operator returns true
if both conditions are true. Otherwise, it returns false
.
Example:
- Condition 1:
c > a
(true) - Condition 2:
c > b
(true)
Since both conditions are true, the result will be true
.
Example:
if (c > a && c > b) {
System.out.println("Both conditions are true");
} else {
System.out.println("At least one condition is false");
}
Output:
Both conditions are true
OR Operator (||
):
This operator returns true
if at least one of the conditions is true. If both conditions are false, the result is false
.
Example:
- Condition 1:
c > a
(true) - Condition 2:
c < b
(false)
Since one of the conditions is true, the result will be true
.
if (c > a || c < b) {
System.out.println("At least one condition is true");
} else {
System.out.println("Both conditions are false");
}
Output:
At least one condition is true
NOT Operator (!
):
This unary operator returns the opposite of the condition. If the condition is true, it returns false
, and vice versa.
Example:
- Condition:
c > a
(true) - Applying NOT:
!(c > a)
(false)
System.out.println(!(c > a)); // false
System.out.println(!(c < a)); // true
Output:
false
true
Short-Circuiting in AND Operator:
In cases where the first condition of an AND operation is false, the second condition will not be evaluated.
Example:
int a = 10, b = 20, c = 15;
if ((a > c) && (++b > c)) {
System.out.println("Condition met");
}
System.out.println("Value of b: " + b);
Output:
Value of b: 20
Short-Circuiting in AND Operator:
In cases where the first condition of an AND operation is false, the second condition will not be evaluated.
Example:
int a = 10, b = 20, c = 15;
if ((a > c) && (++b > c)) {
System.out.println("Condition met");
}
System.out.println("Value of b: " + b);
Output:
Value of b: 20
Short-Circuiting in OR Operator:
In cases where the first condition of an OR operation is true, the second condition will not be evaluated.
Example:
int a = 10, b = 20, c = 15;
if ((a < c) || (++b < c)) {
System.out.println("Condition met");
}
System.out.println("Value of b: " + b);
Output:
Condition met
Value of b: 20
Boolean Values and Logical Operators:
Logical operators can also be applied directly to boolean values. For example:
Example:
boolean a = true;
boolean b = false;
System.out.println("a && b: " + (a && b)); // false
System.out.println("a || b: " + (a || b)); // true
System.out.println("!a: " + !a); // false
System.out.println("!b: " + !b); // true
Output:
a && b: false
a || b: true
!a: false
!b: true
Java Ternary Operator
The ternary operator is the only operator in Java that takes three operands. It serves as a concise alternative to the traditional if-else
statement, allowing conditional logic in a single line. Although it operates similarly to if-else
, it helps to reduce code size and improve readability.
Syntax:
variable = (condition) ? expression1 : expression2;
This syntax translates to:
- If
condition
istrue
,expression1
is executed. - If
condition
isfalse
,expression2
is executed.
Here’s the equivalent structure using an if-else
statement:
if(condition) {
variable = expression1;
} else {
variable = expression2;
}
Example:
int num1 = 10;
int num2 = 20;
int result = (num1 > num2) ? (num1 + num2) : (num1 - num2);
Since num1 < num2
, the second expression is executed, so:
Syntax:
result = num1 - num2 = -10;
Example:
class TernaryExample {
public static void main(String[] args) {
int n1 = 5, n2 = 10, max;
System.out.println("First number: " + n1);
System.out.println("Second number: " + n2);
// Using ternary operator to find the maximum
max = (n1 > n2) ? n1 : n2;
System.out.println("The maximum number is: " + max);
}
}
Output:
First number: 5
Second number: 10
The maximum number is: 10
Bitwise operators
Bitwise operators are used to manipulate individual bits of a number. They are particularly useful when optimizing performance in certain cases, as they directly operate on the binary representation of numbers. Bitwise operators can be used with any integral type (e.g., char
, short
, int
). They are often employed when performing operations on Binary Indexed Trees (BITs).
Here are the common bitwise operators in Java:
1. Bitwise OR (|)
The Bitwise OR operator is represented by the symbol |
. It compares the corresponding bits of two operands, and if either of the bits is 1, the result is 1; otherwise, the result is 0.
Example:
a = 6 = 0110 (In Binary)
b = 9 = 1001 (In Binary)
Bitwise OR Operation:
0110
| 1001
_________
1111 = 15 (In decimal)
2. Bitwise AND (&)
The Bitwise AND operator is represented by &
. It compares the corresponding bits of two operands, and if both bits are 1, the result is 1; otherwise, the result is 0.
Example:
a = 6 = 0110 (In Binary)
b = 9 = 1001 (In Binary)
Bitwise AND Operation:
0110
& 1001
_________
0000 = 0 (In decimal)
3. Bitwise XOR (^)
The Bitwise XOR operator is represented by ^
. It compares the corresponding bits of two operands, and if the bits are different, the result is 1; otherwise, the result is 0.
Example:
a = 6 = 0110 (In Binary)
b = 9 = 1001 (In Binary)
Bitwise XOR Operation:
0110
^ 1001
_________
1111 = 15 (In decimal)
4. Bitwise Complement (~)
The Bitwise NOT (complement) operator is represented by ~
. It inverts all the bits of the operand, changing every 1 to 0 and every 0 to 1.
Example:
a = 6 = 0110 (In Binary)
Bitwise NOT Operation:
~ 0110
_________
1001 = -7 (In decimal, as it returns the two's complement)
Code Example:
import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = input.nextInt();
System.out.print("Enter second number: ");
int num2 = input.nextInt();
System.out.println("Bitwise AND: " + (num1 & num2));
System.out.println("Bitwise OR: " + (num1 | num2));
System.out.println("Bitwise XOR: " + (num1 ^ num2));
System.out.println("Bitwise NOT: " + (~num1));
System.out.println("Bitwise Left Shift: " + (num1 << 2));
System.out.println("Bitwise Right Shift: " + (num1 >> 2));
System.out.println("Bitwise Unsigned Right Shift: " + (num1 >>> 2));
input.close();
}
}
Input:
Enter first number: 4
Enter second number: 10
Output:
Bitwise AND: 0
Bitwise OR: 14
Bitwise XOR: 14
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1