CS Engineering Gyan

Operators in Java

Operators are special symbols in Java that perform operations on variables and values. Whether you are adding two numbers, comparing marks, or checking whether a condition is true, operators are the building blocks that make these calculations and comparisons possible.

Java provides a rich collection of operators, each designed for a specific purpose. Some perform simple mathematical calculations, while others help make logical decisions or manipulate individual bits of data. Understanding how these operators work is essential before moving on to conditional statements and loops.

In this tutorial, you will learn about the different categories of operators available in Java, how each one works, and how to use them correctly with practical examples.


What is an Operator in Java?

An operator is a symbol that tells the compiler to perform a specific mathematical, relational, or logical operation on one or more values, known as operands. The combination of operators and operands forms what is called an expression.

Example

public class OperatorExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 50000;

        int newSubscribers = 2500;

        int total = subscribers + newSubscribers;

        System.out.println(channel + " total subscribers: " + total);

    }

}

Output

CS Engineering Gyan total subscribers: 52500

In this example, the plus symbol acts as an arithmetic operator, combining the values of subscribers and newSubscribers into a single result stored in total.


Categories of Operators in Java

Java operators are broadly grouped into several categories based on the type of operation they perform.

Category Purpose
Arithmetic Operators Perform basic mathematical calculations.
Relational Operators Compare two values and return a boolean result.
Logical Operators Combine multiple conditions to form complex logic.
Assignment Operators Assign values to variables, often combined with calculations.
Unary Operators Operate on a single operand to increase, decrease, or negate a value.
Bitwise Operators Work directly on the individual bits of a value.
Ternary Operator Provides a shorthand way to write simple if-else logic.

Each of these categories serves a distinct purpose, and most Java programs use several of them together to perform meaningful tasks.


1. Arithmetic Operators

Arithmetic operators are used to perform standard mathematical operations such as addition, subtraction, multiplication, division, and finding the remainder of a division.

Operator Description
+ Adds two values together.
- Subtracts the second value from the first.
* Multiplies two values.
/ Divides the first value by the second.
% Returns the remainder after division.

Example

public class ArithmeticExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int mondayViews = 4200;

        int tuesdayViews = 3100;

        int totalViews = mondayViews + tuesdayViews;

        int viewDifference = mondayViews - tuesdayViews;

        int averageViews = totalViews / 2;

        System.out.println(channel + " total views: " + totalViews);

        System.out.println(channel + " view difference: " + viewDifference);

        System.out.println(channel + " average views: " + averageViews);

    }

}

Output

CS Engineering Gyan total views: 7300

CS Engineering Gyan view difference: 1100

CS Engineering Gyan average views: 3650

Arithmetic operators are among the most frequently used operators in any Java program, forming the basis for calculations involving prices, scores, counts, and much more.


2. Relational Operators

Relational operators are used to compare two values and always return a boolean result, either true or false. These operators are especially important when writing conditional statements.

Operator Description
== Checks whether two values are equal.
!= Checks whether two values are not equal.
> Checks whether the first value is greater than the second.
< Checks whether the first value is less than the second.
>= Checks whether the first value is greater than or equal to the second.
<= Checks whether the first value is less than or equal to the second.

Example

public class RelationalExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int targetSubscribers = 100000;

        int currentSubscribers = 87500;

        boolean targetReached = currentSubscribers >= targetSubscribers;

        System.out.println(channel + " target reached: " + targetReached);

    }

}

Output

CS Engineering Gyan target reached: false

Relational operators are commonly used inside if statements and loops, since program logic frequently depends on comparing one value against another.


3. Logical Operators

Logical operators allow you to combine multiple conditions into a single expression, making it possible to build more complex decision-making logic within your programs.

Operator Description
&& Returns true only if both conditions are true (logical AND).
|| Returns true if at least one condition is true (logical OR).
! Reverses the result of a condition (logical NOT).

Example

public class LogicalExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        boolean hasUploadedToday = true;

        boolean hasCommentsEnabled = true;

        boolean readyToPublish = hasUploadedToday && hasCommentsEnabled;

        System.out.println(channel + " ready to publish: " + readyToPublish);

    }

}

Output

CS Engineering Gyan ready to publish: true

Logical operators are extremely useful when a decision in your program depends on more than one condition being satisfied at the same time.


4. Assignment Operators

Assignment operators are used to assign values to variables. Java also provides compound assignment operators that combine a calculation with an assignment in a single step.

Operator Description
= Assigns a value to a variable.
+= Adds a value to the variable and assigns the result.
-= Subtracts a value from the variable and assigns the result.
*= Multiplies the variable by a value and assigns the result.
/= Divides the variable by a value and assigns the result.

Example

public class AssignmentExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 50000;

        subscribers += 1500;

        System.out.println(channel + " updated subscribers: " + subscribers);

    }

}

Output

CS Engineering Gyan updated subscribers: 51500

Compound assignment operators like += make code shorter and easier to read compared to writing the full expression separately.


5. Unary Operators

Unary operators work with a single operand and are commonly used to increase or decrease a value, or to reverse a boolean result.

Operator Description
++ Increases the value of a variable by one.
-- Decreases the value of a variable by one.
- Reverses the sign of a numeric value.
! Reverses a boolean value.

Example

public class UnaryExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int videoCount = 120;

        videoCount++;

        System.out.println(channel + " video count: " + videoCount);

    }

}

Output

CS Engineering Gyan video count: 121

The increment and decrement operators are frequently used inside loops to control how many times a block of code repeats.


6. Bitwise Operators

Bitwise operators work directly on the binary representation of numeric values, performing operations bit by bit. These operators are used less frequently in everyday programs but are important in performance-focused or low-level applications.

Operator Description
& Performs a bitwise AND operation.
| Performs a bitwise OR operation.
^ Performs a bitwise XOR operation.
~ Inverts all bits of a value.
<< Shifts bits to the left.
>> Shifts bits to the right.

Example

public class BitwiseExample {

    public static void main(String[] args) {

        int a = 6;

        int b = 3;

        int result = a & b;

        System.out.println("Bitwise AND result: " + result);

    }

}

Output

Bitwise AND result: 2

While beginners may not use bitwise operators often, understanding them becomes valuable when working on performance optimization or systems programming.


7. Ternary Operator

The ternary operator provides a shorthand way of writing simple if-else conditions in a single line. It is the only operator in Java that works with three operands.

Syntax

condition ? valueIfTrue : valueIfFalse

Example

public class TernaryExample {

    public static void main(String[] args) {

        String channel = "CS Engineering Gyan";

        int subscribers = 95000;

        String status = (subscribers >= 100000) ? "Milestone Reached" : "Growing Steadily";

        System.out.println(channel + " status: " + status);

    }

}

Output

CS Engineering Gyan status: Growing Steadily

The ternary operator is especially useful for simple conditions where writing a full if-else block would make the code longer than necessary.


Operator Precedence in Java

When an expression contains multiple operators, Java follows a specific order, known as operator precedence, to decide which operation is performed first. Operators with higher precedence are evaluated before those with lower precedence.

Example

public class PrecedenceExample {

    public static void main(String[] args) {

        int result = 10 + 5 * 2;

        System.out.println(result);

    }

}

Output

20

In this example, multiplication is performed before addition because it has higher precedence, resulting in 10 + 10, which equals 20. Parentheses can always be used to control the order of evaluation explicitly.


Best Practices While Using Operators


Common Mistakes Beginners Make

Mistake Correct Practice
Confusing the assignment operator (=) with the equality operator (==). Use == only for comparison, and = only for assigning values.
Ignoring operator precedence in complex expressions. Use parentheses to clearly define the intended order of operations.
Using integer division when a decimal result is expected. Ensure at least one operand is a floating-point type when a decimal result is needed.
Overusing the ternary operator for complex logic. Use a full if-else statement when the logic becomes too complex for a single line.

Frequently Asked Interview Questions

  1. What is the difference between the = and == operators in Java?
  2. What is the purpose of relational operators?
  3. How do logical AND and logical OR operators differ in behavior?
  4. What is the difference between pre-increment and post-increment operators?
  5. How does the ternary operator work in Java?
  6. What is operator precedence, and why is it important?
  7. What are bitwise operators used for in Java?
  8. How do compound assignment operators simplify code?

Summary

Operators are essential tools that allow Java programs to perform calculations, comparisons, and logical decisions. From basic arithmetic operations to more advanced bitwise manipulations, each category of operator plays a specific role in building functional programs.

By understanding how arithmetic, relational, logical, assignment, unary, bitwise, and ternary operators work, you gain the ability to write expressions that control the behavior of your programs precisely. With this knowledge in place, you are now ready to explore how Java handles input and output, allowing your programs to interact with users directly.


← Previous: Variables & Data Types Next: Input & Output →

Home Visit Our YouTube Channel