In Java, operators are special symbols or keywords that perform specific operations like mathematical calculations, logical comparisons, data manipulation, or controlling the flow of the program. It tells the compiler to perform specific actions on one or more values, known as operands.
Operators are a tool that work with data to generate a result. For example:
- + operator adds two numbers
- == operator checks if two values are equal or not.
- The && operator verifies if multiple conditions are true or not.
Operators are an essential part of Java expressions because, without operators, writing efficient and meaningful programs would be impossible.
See this simple example:
int a = 10;
int b = 5;
int sum = a + b; // '+' is the addition operator
boolean isEqual = (a == b); // '==' is the equality operator
In this code:
- The + operator adds the a and b values and stores the result in sum.
- The == operator compares whether a and b have the same value and then returns true or false.
Types of Java Operators
Here are the multiple operators available in Java, such as:
- Arithmetic Operators
- Assignment Operators
- Relational (Comparison) Operators
- Logical Operators
- Bitwise Operators
- Unary Operators
- Ternary Operator
- Shift Operators
Let’s explore each operator in detail with examples.
1. Arithmetic Operators
These operators are useful for basic operations, such as addition, subtraction, multiplication, and division. See the following table:
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
– | Subtraction | a – b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (Remainder) | a % b |
1) Example Code:
public class ArithmeticExample {
public static void main(String[] args) {
int a = 20, b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
Output:
Addition: 23
Subtraction: 17
Multiplication: 60
Division: 6
Modulus: 2
- You can see, we have calculated all the arithmetic operations.
2) Java Arithmetic Operators Example: Apples and Friends
public class ArithmeticExample {
public static void main(String[] args) {
int apples = 15, friends = 4;
System.out.println("Total Apples: " + apples);
System.out.println("Apples per friend: " + (apples / friends));
System.out.println("Leftover apples: " + (apples % friends));
}
}
Program Output
Total Apples: 15
Apples per friend: 3
Leftover apples: 3
- This example shows you how arithmetic operators work on division ( / ) and modulus ( % ).
2. Assignment Operators
This operator is used to assign values to a variable. It can also be combined with arithmetic operations. Below, we describe all the assignment symbols:
Operator | Description | Example |
---|---|---|
= | Assigns a value | a = b |
+= | Adds and assigns | a += b |
-= | Subtracts and assigns | a -= b |
*= | Multiplies and assigns | a *= b |
/= | Divides and assigns | a /= b |
%= | Calculates remainder and assigns | a %= b |
Example Code:
public class AssignmentExample {
public static void main(String[] args) {
int score = 10;
score += 5; // score = score + 5
System.out.println("Updated Score: " + score);
}
}
The output will be:
Updated Score: 15
3. Relational (Comparison) Operators
These operators give only two results. Relational operators compare two values for equality and return a Boolean result (true or false).
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
See this example:
public class RelationalExample {
public static void main(String[] args) {
int age = 18;
System.out.println("Is adult? " + (age >= 18));
}
}
Output:
Updated Score: 15
4. Logical Operators
Logical operators are useful to combine multiple conditions. Below we describe the symbols:
Operator | Description | Example |
---|---|---|
&& | Logical AND | (a > b) && (b < c) |
` | ` | |
! | Logical NOT | !(a > b) |
Example Code:
public class LogicalExample {
public static void main(String[] args) {
boolean hasID = true;
boolean hasTicket = false;
System.out.println("Can enter? " + (hasID && hasTicket));
}
}
Output of this program:
Can enter? false
- This program checks whether two values are true or false and then prints the results.
5. Bitwise Operators
Bitwise operators perform operations at the binary level. See the binary symbols in the following table:
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
` | ` | Bitwise OR |
^ | Bitwise XOR | a ^ b |
~ | Bitwise Complement | ~a |
Example Code:
public class BitwiseExample {
public static void main(String[] args) {
int x = 6; // binary: 110
int y = 3; // binary: 011
System.out.println("Bitwise AND: " + (x & y)); // 010 -> 2
}
}
Output of this program:
Bitwise AND: 2
6. Unary Operators
Unary operators perform on a single value
Operator | Description | Example |
---|---|---|
+ | Positive | +a |
– | Negative | -a |
++ | Increment | ++a |
— | Decrement | –a |
! | Logical Complement | !a |
Example Code:
public class UnaryExample {
public static void main(String[] args) {
int count = 5;
System.out.println("Before: " + count);
count++;
System.out.println("After Increment: " + count);
}
}
Output:
Before: 5
After Increment: 6
- See this code, ++ adds 1 to a number. First it displays the original value, then the increased value.
7. Ternary Operator
The ternary operator is a shorthand for if-else statements.
Syntax of the ternary operator:
condition ? value_if_true : value_if_false;
Example Code:
public class TernaryExample {
public static void main(String[] args) {
int marks = 75;
String result = (marks >= 50) ? "Pass" : "Fail";
System.out.println("Result: " + result);
}
}
8. Shift Operators
Shift operators in Java move the binary bits of a number to the left or right. They’re used for fast multiplication, division, or bit manipulation.
Operator | Description | Example |
---|---|---|
<< | Left Shift | a << 2 |
>> | Right Shift | a >> 2 |
>>> | Unsigned Right Shift | a >>> 2 |
Example Code:
public class ShiftExample {
public static void main(String[] args) {
int num = 4; // binary: 100
System.out.println("Left Shift by 1: " + (num << 1)); // 1000 -> 8
}
}
The output will be:
Left Shift by 1: 8
In this code:
- num = 4 → binary 100
- num << 1 shifts all bits one position to the left, adding a 0 on the right: 100 → 1000
- 1000 (binary) = 8 (decimal).
Learn Further Topics:
- How we can use Variables in Java?
- How we can use Operators in Java?
- What are the Strings in Java?
- What are the Methods in Java?
- What are the Data Types in Java?
Real-Life Project
“Coffee Shop Bill Calculator”
Idea
A coffee shop wants a simple program to:
- Take the quantity of coffee and snacks
- Use arithmetic operators to calculate total
- Use assignment operators to apply a discount
- Use comparison operators to check if the bill crosses a certain amount for a gift
- Use logical operators to decide on offers
Program Code:
import java.util.Scanner;
public class CoffeeShopBill {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prices
int coffeePrice = 50; // per cup
int snackPrice = 30; // per item
// Input from user
System.out.print("Enter cups of coffee: ");
int coffeeQty = sc.nextInt();
System.out.print("Enter number of snacks: ");
int snackQty = sc.nextInt();
// Arithmetic operators (+, *)
int total = (coffeeQty * coffeePrice) + (snackQty * snackPrice);
// Assignment operator (+=)
total += 10; // adding packing charge
// Comparison operator (>)
if (total > 200) {
System.out.println("Congrats! You get a free cookie");
}
// Logical operators (&&, ||)
if (coffeeQty >= 2 && snackQty >= 1) {
System.out.println("Special Offer: 10% discount applied!");
total -= total * 10 / 100; // 10% discount
} else if (coffeeQty >= 3 || snackQty >= 3) {
System.out.println("Small Combo Offer: ₹15 off");
total -= 15;
}
// Output final bill
System.out.println("Final Bill: ₹" + total);
}
}
Try to understand this code by yourself, and write the same code in your logic without taking help.