Operators in Java

Operators in Java are special symbols or keywords used to perform operations on variables and values. They play a crucial role in manipulating data and controlling program flow. Understanding operators is essential for writing efficient and logical code. This tutorial provides a comprehensive overview of Java operators, their types, and examples to illustrate their usage.

Contents:

  1. What are Operators in Java?
  2. Types of Operators in Java
  3. Arithmetic Operators
  4. Relational Operators
  5. Logical Operators
  6. Bitwise Operators
  7. Assignment Operators
  8. Unary Operators
  9. Ternary Operator
  10. Shift Operators
  11. Operator Precedence
  12. FAQs on Operators in Java

What are Operators in Java?

Operators in Java are special symbols used to perform operations on variables and values. They help in mathematical calculations, decision-making, and data manipulation. Java provides different types of operators, each serving a specific purpose.

Types of Operators in Java

Java operators are classified into the following types:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Unary Operators
  • Ternary Operator
  • Shift Operators

advertisement

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

Operator Meaning Example (a = 20, b = 2) Result
+ Addition a + b 22
Subtraction a – b 18
* Multiplication a * b 40
/ Division a / b 10
% Modulus (Remainder) a % b 0

Example Program:

public class ArithmeticExample
{
    public static void main(String[] args)
    {
        int a = 20, b = 2;
        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:

Free 30-Day C Certification Bootcamp is Live. Join Now!
Addition: 22
Subtraction: 18
Multiplication: 40
Division: 10
Modulus: 0

Relational Operators

Relational operators compare two values and return a boolean result (true or false).

Types:

Operator Meaning Example (a = 15, b = 7) Result
== Equal to a == b false
!= Not equal to a != b true
> Greater than a > b true
< Less than a < b false
>= Greater than or equal to a >= b true
<= Less than or equal to a <= b false

Example Program:

public class RelationalExample
{
    public static void main(String[] args)
    {
        int a = 15, b = 7;
        System.out.println("a == b: " + (a == b));
        System.out.println("a != b: " + (a != b));
        System.out.println("a > b: " + (a > b));
        System.out.println("a < b: " + (a < b));
        System.out.println("a >= b: " + (a >= b));
        System.out.println("a <= b: " + (a <= b));
    }
}

Output:

a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false

Logical Operators

Logical operators are used to perform logical operations, mainly in conditional statements. They return true or false based on the conditions.

Types:

Operator Description Example
&& (AND) Returns true if both conditions are true (a > 5 && b < 10)
|| (OR) Returns true if at least one condition is true (a > 5 || b > 10)
! (NOT) Reverses the logical state of a condition !(a > 5)

Example Program:

advertisement
public class LogicalOperatorsExample
{
    public static void main(String[] args)
    {
        int a = 10, b = 5, c = 20;
 
        // Logical AND (&&)
        System.out.println(a > b && a < c);
 
        // Logical OR (||)
        System.out.println(a < b || a < c);
 
        // Logical NOT (!)
        System.out.println(!(a > b));
    }
}

Output:

true
true
false

Bitwise Operators

Bitwise operators operate on binary representations of numbers.

Operator Description
& (AND) Performs a bitwise AND operation
| (OR) Performs a bitwise OR operation
^ (XOR) Performs a bitwise XOR operation
~ (NOT) Performs a bitwise complement

Example:

public class BitwiseOperatorsExample
{
    public static void main(String[] args)
    {
        int x = 5, y = 3; // 5 = 0101, 3 = 0011
 
        System.out.println(x & y); // Bitwise AND
        System.out.println(x | y); // Bitwise OR
        System.out.println(x ^ y); // Bitwise XOR
        System.out.println(~x);  // Bitwise NOT
    }
}

Output:

1
7
6
-6

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Example Equivalent To
= a = 10 Assigns value 10 to a
+= a += 5 a = a + 5
-= a -= 5 a = a - 5
*= a *= 5 a = a * 5
/= a /= 5 a = a / 5
%= a %= 5 a = a % 5

Example:

public class AssignmentOperators
{
    public static void main(String[] args)
    {
        int a = 10;
        System.out.println("Initial value: a = " + a);
 
        a += 5; // Equivalent to a = a + 5
        System.out.println("a += 5 → " + a);
 
        a -= 3; // Equivalent to a = a - 3
        System.out.println("a -= 3 → " + a);
 
        a *= 2; // Equivalent to a = a * 2
        System.out.println("a *= 2 → " + a);
 
        a /= 4; // Equivalent to a = a / 4
        System.out.println("a /= 4 → " + a);
 
        a %= 3; // Equivalent to a = a % 3
        System.out.println("a %= 3 → " + a);
    }
}

Output:

Initial value: a = 10
a += 5 → 15
a -= 3 → 12
a *= 2 → 24
a /= 4 → 6
a %= 3 → 0

Unary Operators

Unary operators are those that operate on a single operand. Java provides the following unary operators:

Operator Description Example
+ Unary plus (positive value, optional) +a (if a = 10)
- Unary minus (negates value) -a (if a = 10)
++ Increment (adds 1) a++ (post-increment) or ++a (pre-increment)
-- Decrement (subtracts 1) a-- (post-decrement) or --a (pre-decrement)
! Logical NOT (negates boolean value) !true
~ Bitwise Complement (inverts bits) ~5

Example:

public class UnaryOperatorsExample
{
    public static void main(String[] args)
    {
        int a = 10;
 
        System.out.println(+a);
        System.out.println(-a);
 
        int b = 5;
        System.out.println(++b);
        System.out.println(b--);
        System.out.println(b);
    }
}

Output:

10
-10
6
6
5

Ternary Operator

The ternary operator (? :) is a shorthand for if-else statements. It has the following syntax:

condition ? expression1 : expression2;
  • If condition is true, expression1 is executed.
  • If condition is false, expression2 is executed.

Example:

public class TernaryOperatorExample
{
    public static void main(String[] args)
    {
        int a = 10, b = 20;
 
        // Using the ternary operator to find the maximum number
        int max = (a > b) ? a : b;
        System.out.println("The maximum number is: " + max);
 
        // Checking if a number is even or odd using the ternary operator
        int num = 7;
        String result = (num % 2 == 0) ? "Even" : "Odd";
        System.out.println(num + " is " + result);
 
        // Checking eligibility to vote using the ternary operator
        int age = 18;
        String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
        System.out.println("Age " + age + ": " + eligibility);
    }
}

Output:

The maximum number is: 20
7 is Odd
Age 18: Eligible to vote

Shift Operators

Shift operators are used to shift the bits of a number left or right. Java provides the following shift operators:

Operator Description
<< (Left Shift) Shifts bits to the left, filling with 0s from the right. Equivalent to multiplying by 2^n.
>> (Right Shift) Shifts bits to the right, keeping the sign bit (Arithmetic shift). Equivalent to dividing by 2^n.
>>> (Unsigned Right Shift) Shifts bits to the right, filling with 0s (Logical shift). Does not preserve sign bit.
public class ShiftOperators
{
    public static void main(String[] args)
    {
        int a = 5, b = -20;
 
        System.out.println("a << 2 = " + (a << 2));
        System.out.println("a >> 1 = " + (a >> 1));
        System.out.println("b >> 2 = " + (b >> 2));
        System.out.println("b >>> 2 = " + (b >>> 2));
    }
}

Output:

a << 2 = 20
a >> 1 = 2
b >> 2 = -5
b >>> 2 = 1073741819

Operator Precedence

It defines the order in which different operators in an expression are evaluated.
Example:

result = 2 + 3 * 4

Here, multiplication (*) has higher precedence than addition (+), so: First, 3 * 4 = 12, then 2 + 12 = 14.

Common Precedence Levels (from highest to lowest)

Precedence Operators Description
1 () Parentheses for grouping expressions
2 ., [], () (method call) Member access, array access, method invocation
3 expr++, expr-- Post-increment, post-decrement
4 ++expr, --expr, +expr, -expr, !expr, ~expr, (type) Pre-increment, pre-decrement, unary plus/minus, logical NOT, bitwise NOT, type cast
5 *, /, % Multiplication, division, modulus
6 +, - Addition, subtraction
7 <<, >>, >>> Bitwise shifts (left, signed right, unsigned right)
8 <, >, <=, >=, instanceof Relational and type comparison
9 ==, != Equality operators
10 & Bitwise AND
11 ^ Bitwise XOR
12 | Bitwise OR
13 && Logical AND
14 || Logical OR
15 ?: Ternary conditional operator
16 =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= Assignment operators

FAQs on Data Types in Java

1. What are operators in Java?

Operators in Java are special symbols used to perform operations on variables and values. They help in performing calculations, comparisons, and logical operations.

2. How many types of operators are there in Java?

Java has 8 types of operators: Arithmetic, Relational, Logical, Bitwise, Assignment, Unary, Ternary, and Shift operators.

3. What is the difference between == and = in Java?

= is an assignment operator (assigns values), while == is a relational operator (compares values).

4. What is the default value of an uninitialized operator result?

In Java, an uninitialized operator result does not have any default value because local variables must be explicitly initialized before use. If any operand in an operation is uninitialized, the compiler throws a compilation error.

5. Are Java operators evaluated left to right?

Most operators are left to right, except assignment (=) and ternary (?:), which are right to left.

6. What is the difference between && and &?

&& (Logical AND) short-circuits, stopping evaluation if the first condition is false. & (Bitwise AND) always evaluates both conditions.

Key Points to Remember

Here is the list of key points we need to remember about the "Operators in Java".

  • Operators in Java perform operations on variables and values, playing a crucial role in data manipulation and program flow control.
  • Java provides various operators, including arithmetic, relational, logical, bitwise, assignment, unary, ternary, and shift operators.
  • Logical operators help in decision-making, while bitwise operators work at the binary level to manipulate data efficiently.
  • The ternary operator simplifies conditional statements, whereas assignment operators allow concise value updates.
  • Shift operators adjust bit positions to optimize calculations, commonly used in performance-sensitive applications.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.