Operators in Java
-
Last Updated: September 8, 2023
-
By: javahandson
-
Series
Learn Java in a easy way
Operators in Java are the symbols that make your code actually do something. They add numbers, compare values, combine conditions, and push results into variables. Learn these well and the rest of Java gets much easier, because every loop, every if check, and every calculation you ever write leans on them.
Think about a pocket calculator. The digits are the data. The plus and minus keys are what turn that data into an answer. Java works the same way. Your variables hold the data, and operators are the keys you press.
Java gives you eight families of operators. Four of them show up in almost every program you write, so we will spend most of our time there. The other four are more specialised, and each one already has its own deep-dive article on this site.
2 + 3 * 4 never surprises you again.An operator is a symbol that performs an action on one or more values. The values it acts on are the operands. That is the whole idea.
Look at a + b. The + is the operator. The variables a and b are the operands. Together they form an expression, and every expression produces a result.
int a = 20; int b = 7; int sum = a + b; // '+' is the operator, 'a' and 'b' are the operands System.out.println(sum); // Output: 27
Operands do not have to be variables. Literals work too, and so do method calls. 7 + getScore() is a perfectly good expression.
Java sorts operators by how many operands they take. This vocabulary comes up in interviews, so it is worth knowing.
-x or count++.a * b. Most operators land here.?: operator.Here is the complete picture before we zoom in. Keep this table handy while you read the rest of the article.
| Type | Symbols | What It Does |
|---|---|---|
| Arithmetic | + – * / % | Does the maths |
| Relational | > >= < <= == != | Compares two values, gives back true or false |
| Logical | && || ! | Combines or flips boolean conditions |
| Assignment | = += -= *= /= %= | Puts a value into a variable |
| Unary | ++ — + – ! | Acts on a single operand |
| Bitwise | & | ^ ~ | Works on individual bits |
| Ternary | ?: | Picks one of two values based on a condition |
| Shift | << >> >>> | Slides bits left or right |
Sections 4 through 7 cover the first four in detail. Section 8 introduces the rest and points you to the dedicated article for each.
Arithmetic operators do exactly what you learned in school, with one twist we will get to shortly. All five take two operands, which makes them binary operators.
To see them in action, take int a = 20 and int b = 7.
| Operator | Name | Purpose | Example | Result |
|---|---|---|---|---|
| + | Addition | Adds the two operands | a + b | 27 |
| – | Subtraction | Subtracts the right operand from the left | a – b | 13 |
| * | Multiplication | Multiplies the two operands | a * b | 140 |
| / | Division | Divides and gives the quotient | a / b | 2 |
| % | Modulus | Divides and gives the remainder | a % b | 6 |
The modulus operator earns its keep more often than beginners expect. Need to know whether a number is even? Check n % 2 == 0. Need every third item in a loop? Check i % 3 == 0.
package com.java.handson;
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 20;
int b = 7;
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 : 27
// Subtraction : 13
// Multiplication : 140
// Division : 2
// Modulus : 6Did the division result bother you? Twenty divided by seven is roughly 2.857, but Java printed 2. That is not a bug.
When both operands are integers, Java performs integer division and throws the fractional part away. It does not round. It simply truncates toward zero.
To get a decimal answer, at least one operand has to be a floating-point value.
int a = 20; int b = 7; System.out.println(a / b); // Output: 2 System.out.println((double) a / b); // Output: 2.857142857142857 System.out.println(20.0 / 7); // Output: 2.857142857142857
One more trap lives here. Dividing an integer by zero throws ArithmeticException at runtime. Dividing a double by zero does not, and quietly hands you Infinity instead.
The + operator wears two hats. Give it numbers and it adds. Give it a String on either side and it joins text together instead.
String str1 = "Java";
String str2 = "HandsOn";
System.out.println(str1 + str2); // Output: JavaHandsOn
// Careful. Java evaluates left to right.
System.out.println(5 + 3 + " points"); // Output: 8 points
System.out.println("Score: " + 5 + 3); // Output: Score: 53Look closely at those last two lines. In the first, Java adds 5 and 3 before it ever meets a String, so you get 8. In the second, "Score: " + 5 already produced a String, so the 3 just gets glued on the end.
Wrap the maths in parentheses whenever you mix numbers and text. "Score: " + (5 + 3) prints what you meant.
Relational operators compare two values and hand back a boolean, so the answer is always true or false. Many developers call them comparison operators, and the two names mean the same thing.
You will meet them mostly inside conditions, feeding an if…else statement or a loop.
Take int a = 20, int b = 7, and int c = 20.
| Operator | Name | Purpose | Example | Result |
|---|---|---|---|---|
| > | Greater than | True when the left value exceeds the right | a > b | true |
| >= | Greater than or equal to | True when the left value is at least the right | a >= c | true |
| < | Less than | True when the left value falls below the right | a < b | false |
| <= | Less than or equal to | True when the left value is at most the right | a <= c | true |
| == | Equal to | True when both values match | a == c | true |
| != | Not equal to | True when the values differ | a != c | false |
package com.java.handson;
public class RelationalOperators {
public static void main(String[] args) {
int a = 20;
int b = 7;
int c = 20;
System.out.println("a > b : " + (a > b));
System.out.println("a >= c : " + (a >= c));
System.out.println("a < b : " + (a < b));
System.out.println("a <= c : " + (a <= c));
System.out.println("a == c : " + (a == c));
System.out.println("a != c : " + (a != c));
if (a >= b) {
System.out.println("20 is at least 7, so we are inside the if block");
}
}
}
// Output:
// a > b : true
// a >= c : true
// a < b : false
// a <= c : true
// a == c : true
// a != c : false
// 20 is at least 7, so we are inside the if blockA warning about ==. On primitives like int, it compares values, which is what you want. On objects, it compares references, so it asks whether two variables point at the very same object in memory. For Strings and other objects, reach for equals() instead. Our guide to String comparison in Java digs into why.
One condition is rarely enough. Real programs ask things like “is the user logged in and does the cart have items?” Logical operators glue those conditions together.
All three work only on booleans, and all three produce a boolean.
| Operator | Name | Purpose |
|---|---|---|
| && | and | True only when both sides are true |
| || | or | True when at least one side is true |
| ! | not | Flips the value. True becomes false, false becomes true |
package com.java.handson;
public class LogicalOperators {
public static void main(String[] args) {
int value = 10;
int x = 5;
int y = 8;
if (x < value && y < value) {
System.out.println("&& : both conditions are true");
}
if (x < value || y > value) {
System.out.println("|| : at least one condition is true");
}
if (!(x > value)) {
System.out.println("! : x is not greater than value, so this flipped to true");
}
}
}
// Output:
// && : both conditions are true
// || : at least one condition is true
// ! : x is not greater than value, so this flipped to trueHere is the part that separates people who have read a tutorial from people who have shipped code.
&& and || are lazy on purpose. They stop as soon as they know the answer.
&&, a false left side settles it. The right side never runs.||, a true left side settles it. Again, Java skips the right side.That laziness is not just a speed trick. It is a safety net, and you will lean on it constantly.
String name = null;
// Safe. 'name != null' is false, so Java never calls length().
if (name != null && name.length() > 3) {
System.out.println("Long name");
}
// Swap the order and this line throws NullPointerException.
// if (name.length() > 3 && name != null) { ... }Java also ships non-short-circuit cousins, & and |. Those always evaluate both sides, even when the answer is already settled. Skip them for conditions, and keep them for the bitwise work we mention in section 8.
The single equals sign stores a value in a variable. You will type it more than any other operator in your career. It comes in three flavours.
Drop a value straight into a variable. You can also copy one variable into another.
int a = 20;
int b = a; // b gets a copy of the value in a
System.out.println("Value of b is : " + b); // Output: Value of b is : 20Compound assignment pairs a binary operator with the equals sign. It reads the variable, applies the operation, and writes the result back.
int a = 20; a += 10; // same as a = a + 10 System.out.println(a); // Output: 30 int p = 2; p *= 10; // same as p = p * 10 System.out.println(p); // Output: 20
These operators hide a detail that interviewers love. A compound assignment performs an implicit cast back to the variable’s type, so it compiles in places where the long form refuses.
byte b = 10; b += 5; // Compiles. The hidden cast keeps the compiler happy. // b = b + 5; // Compiler error: int cannot be converted to byte System.out.println(b); // Output: 15
Why does the long form fail? Java widens byte to int before adding, and it will not silently squeeze an int back into a byte. Our article on type casting in Java covers those rules properly.
Java solves the whole expression on the right first, then assigns the single result to the variable on the left.
int b = 5;
int c = 7;
int a = (2 + b) * c; // (2 + 5) * 7 = 49
System.out.println("Value of a is : " + a); // Output: Value of a is : 49package com.java.handson;
public class AssignmentOperators {
public static void main(String[] args) {
int a = 20;
System.out.println("Value of a is : " + a);
int b = a;
System.out.println("Value of b is : " + b);
int c = 10;
c += 20; // c = c + 20
System.out.println("Value of c is : " + c);
int d = (2 + b) * c; // (2 + 20) * 30
System.out.println("Value of d is : " + d);
}
}
// Output:
// Value of a is : 20
// Value of b is : 20
// Value of c is : 30
// Value of d is : 660The four families below deserve more room than one section can give them, so each has its own article. Here is enough to recognise them in code.
Unary operators act on a single operand. The increment and decrement pair, ++ and --, drive nearly every loop you will write.
int i = 5; System.out.println(i++); // Output: 5 (prints, then increments) System.out.println(i); // Output: 6 System.out.println(++i); // Output: 7 (increments, then prints)
Position matters. Read the full story in Unary Operators in Java.
Bitwise operators ignore the number you see and work on the individual bits underneath. They power flags, masks, and low-level tricks.
& keeps a bit only when both sides have it set.| keeps a bit when either side has it set.^ keeps a bit when exactly one side has it set.~ flips every bit.Full walkthrough with binary examples: Bitwise Operators in Java.
The ternary operator squeezes a small if...else onto one line. Java has exactly one operator that takes three operands, and this is it.
int a = 20;
int b = 7;
int max = (a > b) ? a : b; // condition ? valueIfTrue : valueIfFalse
System.out.println("Max is : " + max); // Output: Max is : 20Keep it for short choices. Nested ternaries turn unreadable fast. See Ternary Operator in Java.
Shift operators slide the bits of a number left or right. Java offers three of them.
<< shifts left, which doubles the value for each position.>> shifts right and preserves the sign bit.>>> shifts right and pulls in zeros, ignoring the sign.int n = 8; // binary 1000 System.out.println(n << 1); // Output: 16 (binary 10000) System.out.println(n >> 2); // Output: 2 (binary 10)
There is no <<< operator in Java. A left shift already pushes zeros in from the right, so the unsigned variant would add nothing.
What does 2 + 3 * 4 give you? The answer is 14, not 20. Multiplication binds more tightly than addition, so Java handles it first.
Precedence is simply the pecking order. Operators near the top of this table run before operators near the bottom.
| Level | Operators |
|---|---|
| 1 (highest) | ++ — (postfix) |
| 2 | ++ — + – ! ~ (unary), cast |
| 3 | * / % |
| 4 | + – |
| 5 | << >> >>> |
| 6 | < <= > >= instanceof |
| 7 | == != |
| 8 | & then ^ then | |
| 9 | && then || |
| 10 | ?: (ternary) |
| 11 (lowest) | = += -= *= /= %= |
When two operators share a level, associativity breaks the tie. Almost everything runs left to right. Assignment is the odd one out and runs right to left, which is why x = y = 5 gives both variables the value 5.
Nobody will hand you a prize for memorising all eleven levels. Parentheses beat memory every time.
// Technically correct, but the reader has to pause and think. boolean ok = age > 18 && score > 50 || isAdmin; // Same result, zero doubt. boolean clear = (age > 18 && score > 50) || isAdmin;
Write the second version. Your future self, reading this at 2 a.m. during an outage, will thank you.
[Image placeholder: operator precedence pyramid, highest at the top narrowing down to assignment at the base.]
Every one of these has bitten a real developer on a real project.
= where you meant ==. Writing if (x = 5) assigns instead of comparing. Java rejects it for ints, but a boolean variable slips right through and creates a silent bug.==. Two Strings holding identical text can still fail an == check. Call equals() whenever you compare object contents.int / int. Java truncates. Cast one operand to double first."Total: " + 5 + 3 prints Total: 53, which is almost never what you wanted.Integer.MAX_VALUE and the value wraps around to Integer.MIN_VALUE. No exception, no warning. Reach for long when numbers grow.name.length() > 3 && name != null throws before the null check ever runs. Order matters.& instead of &&. The single ampersand evaluates both sides, which throws away short-circuit protection.Let us pull every operator family into one small program. It grades a student, and each line below uses something we covered.
package com.java.handson;
public class GradeCalculator {
public static void main(String[] args) {
int marks = 0; // assignment
marks += 78; // compound assignment
int totalMarks = 100;
double percentage = (double) marks / totalMarks * 100; // arithmetic
boolean isPass = percentage >= 40; // relational
boolean isDistinction = percentage >= 75 && isPass; // logical
String grade = isDistinction ? "Distinction" // ternary
: isPass ? "Pass"
: "Fail";
System.out.println("Percentage : " + percentage);
System.out.println("Passed : " + isPass);
System.out.println("Grade : " + grade);
System.out.println("Even marks? : " + (marks % 2 == 0)); // modulus
}
}
// Output:
// Percentage : 78.0
// Passed : true
// Grade : Distinction
// Even marks? : trueNotice the cast on the percentage line. Without it, marks / totalMarks would be integer division, 78 divided by 100 would collapse to 0, and every student in your school would fail.
Notice too that isDistinction short-circuits. If percentage >= 75 comes back false, Java never bothers to look at isPass.
A: On primitives, == compares the actual values. On objects, == compares references, so it only returns true when both variables point at the same object in memory. The equals() method compares contents instead, which is what you almost always want for Strings and other objects.
A: Both give the same boolean answer, but && short-circuits. It skips the right operand once the left operand is false. The single & always evaluates both sides, and it also doubles as the bitwise AND operator on integers.
A: Both operands are integers, so Java performs integer division and truncates the fractional part. Cast one operand to double, as in (double) 5 / 2, and you get 2.5.
A: Compound assignment operators perform an implicit narrowing cast back to the variable’s type. The long form does not. Java widens the byte to an int before adding, and it refuses to shrink that int back into a byte without an explicit cast.
A: The conditional operator, written as condition ? valueIfTrue : valueIfFalse. It takes three operands, which makes it the single ternary operator in the language.
A: Both add one to i. The postfix form, i++, returns the old value and then increments. Write ++i instead and Java increments first, then hands back the new value. That difference only shows up when you use the result inside the same expression.
A: The value wraps around silently. Adding 1 to Integer.MAX_VALUE gives you Integer.MIN_VALUE, with no exception and no warning. Use a long, or call Math.addExact() when you want an exception on overflow.
A: No. Java has <<, >>, and >>>. A left shift already fills the vacated positions with zeros, so an unsigned left shift would behave identically to the signed one and would serve no purpose.
Let us wrap up what we covered.
+ switches to concatenation the moment a String appears.== compares references once objects are involved.Operators look simple, and that is exactly why they catch people out. Type these examples into your editor, change the numbers, and watch what happens. Ten minutes of that beats an hour of reading.