Skip to main content

Command Palette

Search for a command to run...

Java Operators Program

Published
3 min readView as Markdown
Java Operators Program

1️⃣ Arithmetic Operators

Q1. Write a program to perform all arithmetic operations.

class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 10, b = 3;
        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: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1

2️⃣ Relational Operators

Q2. Check whether one number is greater than another.

class RelationalDemo {
    public static void main(String[] args) {
        int x = 15, y = 20;
        System.out.println(x > y);
        System.out.println(x < y);
        System.out.println(x == y);
    }
}

Output

false
true
false

3️⃣ Logical Operators

Q3. Use logical AND and OR operators.

class LogicalDemo {
    public static void main(String[] args) {
        int a = 10, b = 5;
        System.out.println(a > b && b > 0);
        System.out.println(a < b || b > 0);
    }
}

Output

true
true

4️⃣ Assignment Operators

Q4. Demonstrate assignment operators.

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

Output

30

5️⃣ Unary Operators

Q5. Difference between pre-increment and post-increment.

class UnaryDemo {
    public static void main(String[] args) {
        int a = 5;
        System.out.println(++a); // pre
        System.out.println(a++); // post
        System.out.println(a);
    }
}

Output

6
6
7

6️⃣ Bitwise Operators

Q6. Use bitwise AND and OR.

class BitwiseDemo {
    public static void main(String[] args) {
        int a = 5, b = 3;
        System.out.println(a & b);
        System.out.println(a | b);
    }
}

Output

1
7

7️⃣ Ternary Operator

Q7. Find the maximum of two numbers.

class TernaryDemo {
    public static void main(String[] args) {
        int a = 10, b = 20;
        int max = (a > b) ? a : b;
        System.out.println("Max: " + max);
    }
}

Output

Max: 20

8️⃣ Operator Precedence (Tricky)

Q8. Predict the output.

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

Output

20

👉 multiplication first, then addition.


9️⃣ Real-time Logic Question

Q9. Check if a number is even or odd using operators.

class EvenOdd {
    public static void main(String[] args) {
        int n = 7;
        System.out.println(n % 2 == 0 ? "Even" : "Odd");
    }
}

Output

Odd