BhauAutomation

Operators in Java

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

📘 Topic: Core Java / Basics
Read time: 8 min
📊 Level: Beginner
Focus: Operator Types
📖 Overview

What are Operators in Java?

Operators are special symbols that perform specific operations on one, two, or three operands and then return a result. They make programming more efficient and logical.

Example:
int a = 10, b = 5;
int sum = a + b; // '+' is an arithmetic operator
System.out.println(sum); // Output: 15
🔧 Operator Types

Types of Operators in Java

➕ Arithmetic Operators

Perform mathematical operations like addition, subtraction, multiplication, division, and modulus.

int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1
⚖️ Relational Operators

Compare two values and return a boolean result (true/false).

int a = 10, b = 5;
System.out.println(a > b);  // true
System.out.println(a == b); // false
🔀 Logical Operators

Perform logical operations such as AND, OR, and NOT.

int x = 10, y = 20;
System.out.println(x > 0 && y > 0); // true
System.out.println(!(x > y));       // true
📝 Assignment Operators

Used to assign values to variables.

int num = 10;
num += 5; // same as num = num + 5
System.out.println(num); // Output: 15
🔄 Unary Operators

Operate on a single operand and perform increment/decrement or negation operations.

int a = 10;
System.out.println(++a); // 11
System.out.println(-a);  // -11
💻 Bitwise Operators

Perform operations on bits, mostly used in low-level programming or optimization.

int a = 5, b = 3;
System.out.println(a & b); // 1 (AND)
System.out.println(a | b); // 7 (OR)
❓ Ternary Operator

A shorthand version of if-else.

int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max); // 20
✅ Advantages

Advantages of Using Operators

Operators simplify program logic, make expressions concise, and enhance code readability. They also enable complex decision-making and data manipulation effectively.

⚠️ Important Points

Important Points

Operators follow a strict precedence and associativity order. Division by zero using '/' operator throws an ArithmeticException. Increment and decrement operators work only on numeric data types.

💻 Example Program

Example Program

public class OperatorsDemo { public static void main(String[] args) { int a = 10, b = 5; 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 > 0) && (b > 0)); System.out.println("++a = " + (++a)); } }
🏆 Best Practices

Best Practices

Always use parentheses to make expressions clear and avoid confusion

Test for division by zero before performing division

Write meaningful and simple operator expressions for better readability