Operators in Java

  • Last Updated: September 8, 2023
  • By: javahandson
  • Series
img

Operators in Java

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.

1. Introduction

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.

1.1 What This Article Covers

  • What an operator really is, and how operands fit in.
  • All eight operator families, mapped out in one table.
  • Arithmetic, relational, logical, and assignment operators in depth, with runnable code.
  • Short-circuit evaluation, and why it protects you from crashes.
  • Precedence rules, so 2 + 3 * 4 never surprises you again.
  • The mistakes that trip up almost every beginner.
  • Interview questions you can expect on this topic.

2. What Is an Operator?

2.1 Operators and Operands

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.

2.2 Counting the Operands

Java sorts operators by how many operands they take. This vocabulary comes up in interviews, so it is worth knowing.

  • Unary operators take one operand, like -x or count++.
  • Binary operators take two operands, like a * b. Most operators land here.
  • Ternary operators take three operands. Java has exactly one of these, the ?: operator.

3. The Eight Types of Operators

3.1 The Full Map

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.

4. Arithmetic Operators

4.1 The Five Arithmetic Operators

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.

4.2 Sample Example

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        : 6

4.3 The Integer Division Surprise

Did 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.

4.4 The Plus Operator on Strings

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: 53

Look 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.

5. Relational Operators

5.1 The Six Comparison Operators

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

5.2 Sample Example

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 block

A 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.

6. Logical Operators

6.1 And, Or, and Not

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

6.2 Sample Example

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 true

6.3 Short-Circuit Evaluation

Here 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.

  • With &&, a false left side settles it. The right side never runs.
  • With ||, 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.

7. Assignment Operators

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.

7.1 Plain Assignment

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 : 20

7.2 Compound Assignment

Compound 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.

7.3 Expression Assignment

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 : 49

7.4 Sample Example

package 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 : 660

8. The Remaining Four Operators

The 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.

8.1 Unary Operators

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.

8.2 Bitwise Operators

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.

8.3 Ternary Operator

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 : 20

Keep it for short choices. Nested ternaries turn unreadable fast. See Ternary Operator in Java.

8.4 Shift Operators

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.

9. Operator Precedence

9.1 The Precedence Order

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.

9.2 Just Use Parentheses

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.]

10. Common Mistakes and Pitfalls

Every one of these has bitten a real developer on a real project.

  • Using = 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.
  • Comparing objects with ==. Two Strings holding identical text can still fail an == check. Call equals() whenever you compare object contents.
  • Expecting a decimal from int / int. Java truncates. Cast one operand to double first.
  • Forgetting parentheses when mixing text and numbers. "Total: " + 5 + 3 prints Total: 53, which is almost never what you wanted.
  • Ignoring integer overflow. Add 1 to Integer.MAX_VALUE and the value wraps around to Integer.MIN_VALUE. No exception, no warning. Reach for long when numbers grow.
  • Putting the null check second. name.length() > 3 && name != null throws before the null check ever runs. Order matters.
  • Reaching for & instead of &&. The single ampersand evaluates both sides, which throws away short-circuit protection.

11. Putting It All Together

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?   : true

Notice 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.

12. Interview Questions

Q: What is the difference between == and equals() in Java?

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.

Q: What is the difference between & and && in Java?

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.

Q: Why does 5 / 2 print 2 instead of 2.5 in Java?

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.

Q: Why does b += 5 compile for a byte when b = b + 5 does not?

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.

Q: What is the only ternary operator in Java?

A: The conditional operator, written as condition ? valueIfTrue : valueIfFalse. It takes three operands, which makes it the single ternary operator in the language.

Q: What is the difference between i++ and ++i?

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.

Q: What happens when an int overflows in Java?

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.

Q: Does Java have a <<< operator?

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.

13. Conclusion

Let us wrap up what we covered.

  • An operator acts on operands, and every expression it builds produces a result.
  • Java groups its operators into eight families, and four of them cover most day-to-day code.
  • Arithmetic operators truncate on integer division, and + switches to concatenation the moment a String appears.
  • Relational operators always give back a boolean, but == compares references once objects are involved.
  • Logical operators short-circuit, and that behaviour is your best defence against a NullPointerException.
  • Compound assignment sneaks in an implicit cast, which is a favourite interview question.
  • Precedence decides the order, and parentheses save you from having to remember it.

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.

14. Further Reading

Leave a Comment