Virtual assistance

Operators in Java

Operators are special symbols that perform operations on variables and values. Understanding operators is essential for writing effective Java programs.

Java Operators Tutorial

What are Operators?

Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java provides a rich set of operators that can be categorized into different types based on their functionality.

Types of Operators in Java

Java supports several categories of operators:

  • Arithmetic Operators: Perform mathematical operations
  • Relational Operators: Compare two values
  • Logical Operators: Perform logical operations
  • Bitwise Operators: Perform bit-level operations
  • Assignment Operators: Assign values to variables
  • Unary Operators: Operate on single operands
  • Ternary Operator: Conditional operator

Arithmetic Operators

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

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 3 1 (integer division)
% Modulus (Remainder) 5 % 3 2

Arithmetic Operators Example

public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 10, b = 3;

        System.out.println("a = " + a + ", b = " + b);
        System.out.println("a + b = " + (a + b)); // Addition
        System.out.println("a - b = " + (a - b)); // Subtraction
        System.out.println("a * b = " + (a * b)); // Multiplication
        System.out.println("a / b = " + (a / b)); // Division (integer)
        System.out.println("a % b = " + (a % b)); // Modulus

        // Floating-point division
        double x = 10.0, y = 3.0;
        System.out.println("x / y = " + (x / y)); // Division (floating-point)
    }
}

Relational Operators

Relational operators are used to compare two values. They return a boolean result (true or false).

Operator Description Example Result
== Equal to 5 == 3 false
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 3 true
<= Less than or equal to 5 <= 3 false

Relational Operators Example

public class RelationalOperators {
    public static void main(String[] args) {
        int a = 10, b = 5, c = 10;

        System.out.println("a = " + a + ", b = " + b + ", c = " + c);
        System.out.println("a == b: " + (a == b)); // false
        System.out.println("a != b: " + (a != b)); // true
        System.out.println("a > b: " + (a > b));   // true
        System.out.println("a < b: " + (a < b));   // false
        System.out.println("a >= c: " + (a >= c)); // true
        System.out.println("a <= b: " + (a <= b)); // false

        // String comparison
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");

        System.out.println("str1 == str2: " + (str1 == str2));     // true (same reference)
        System.out.println("str1 == str3: " + (str1 == str3));     // false (different references)
        System.out.println("str1.equals(str3): " + str1.equals(str3)); // true (same content)
    }
}

Logical Operators

Logical operators are used to combine multiple boolean expressions. They are commonly used in conditional statements and loops.

Operator Description Example Result
&& Logical AND true && false false
|| Logical OR true || false true
! Logical NOT !true false

Logical Operators Example

public class LogicalOperators {
    public static void main(String[] args) {
        boolean a = true, b = false;

        System.out.println("a = " + a + ", b = " + b);
        System.out.println("a && b: " + (a && b)); // false (AND)
        System.out.println("a || b: " + (a || b)); // true (OR)
        System.out.println("!a: " + (!a));         // false (NOT)
        System.out.println("!b: " + (!b));         // true (NOT)

        // Short-circuit evaluation
        int x = 5, y = 10;
        boolean result1 = (x < 10) && (y++ > 5); // y++ is not executed
        System.out.println("y after &&: " + y);   // y is still 10

        boolean result2 = (x > 10) || (y++ > 5); // y++ is executed
        System.out.println("y after ||: " + y);   // y is now 11
    }
}

Bitwise Operators

Bitwise operators perform operations on individual bits of integer values. They are useful for low-level programming and performance-critical applications.

Operator Description Example Result
& Bitwise AND 5 & 3 1
| Bitwise OR 5 | 3 7
^ Bitwise XOR 5 ^ 3 6
~ Bitwise NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2
>>> Unsigned right shift -5 >>> 1 2147483645

Bitwise Operators Example

public class BitwiseOperators {
    public static void main(String[] args) {
        int a = 5;  // Binary: 101
        int b = 3;  // Binary: 011

        System.out.println("a = " + a + " (binary: " + Integer.toBinaryString(a) + ")");
        System.out.println("b = " + b + " (binary: " + Integer.toBinaryString(b) + ")");

        System.out.println("a & b = " + (a & b) + " (binary: " + Integer.toBinaryString(a & b) + ")");   // AND
        System.out.println("a | b = " + (a | b) + " (binary: " + Integer.toBinaryString(a | b) + ")");   // OR
        System.out.println("a ^ b = " + (a ^ b) + " (binary: " + Integer.toBinaryString(a ^ b) + ")");   // XOR
        System.out.println("~a = " + (~a) + " (binary: " + Integer.toBinaryString(~a) + ")");           // NOT

        System.out.println("a << 1 = " + (a << 1) + " (binary: " + Integer.toBinaryString(a << 1) + ")"); // Left shift
        System.out.println("a >> 1 = " + (a >> 1) + " (binary: " + Integer.toBinaryString(a >> 1) + ")"); // Right shift
    }
}

Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is '=', but there are compound assignment operators that combine assignment with other operations.

Operator Description Example Equivalent to
= Simple assignment x = 5 x = 5
+= Add and assign x += 5 x = x + 5
-= Subtract and assign x -= 5 x = x - 5
*= Multiply and assign x *= 5 x = x * 5
/= Divide and assign x /= 5 x = x / 5
%= Modulus and assign x %= 5 x = x % 5
&= Bitwise AND and assign x &= 5 x = x & 5
|= Bitwise OR and assign x |= 5 x = x | 5
^= Bitwise XOR and assign x ^= 5 x = x ^ 5
<<= Left shift and assign x <<= 2 x = x << 2
>>= Right shift and assign x >>= 2 x = x >> 2
>>>= Unsigned right shift and assign x >>>= 2 x = x >>> 2

Assignment Operators Example

public class AssignmentOperators {
    public static void main(String[] args) {
        int x = 10;

        System.out.println("Initial value of x: " + x);

        x += 5;  // x = x + 5
        System.out.println("After x += 5: " + x);

        x -= 3;  // x = x - 3
        System.out.println("After x -= 3: " + x);

        x *= 2;  // x = x * 2
        System.out.println("After x *= 2: " + x);

        x /= 4;  // x = x / 4
        System.out.println("After x /= 4: " + x);

        x %= 3;  // x = x % 3
        System.out.println("After x %= 3: " + x);

        // Bitwise assignment
        x = 12;  // Reset x
        x &= 10; // x = x & 10
        System.out.println("After x &= 10: " + x);

        x = 5;   // Reset x
        x <<= 1; // x = x << 1
        System.out.println("After x <<= 1: " + x);
    }
}

Unary Operators

Unary operators operate on a single operand. Java supports several unary operators:

Operator Description Example Result
+ Unary plus +5 5
- Unary minus -5 -5
++ Increment x++ or ++x Increases value by 1
-- Decrement x-- or --x Decreases value by 1
! Logical NOT !true false
~ Bitwise NOT ~5 -6

Unary Operators Example

public class UnaryOperators {
    public static void main(String[] args) {
        int x = 5, y = 10;

        System.out.println("x = " + x + ", y = " + y);

        // Increment operators
        System.out.println("x++ = " + (x++)); // Post-increment: prints 5, then x becomes 6
        System.out.println("x = " + x);

        System.out.println("++x = " + (++x)); // Pre-increment: x becomes 7, then prints 7

        // Decrement operators
        System.out.println("y-- = " + (y--)); // Post-decrement: prints 10, then y becomes 9
        System.out.println("y = " + y);

        System.out.println("--y = " + (--y)); // Pre-decrement: y becomes 8, then prints 8

        // Unary minus and plus
        int positive = 5;
        int negative = -positive;
        int stillPositive = +positive;

        System.out.println("positive = " + positive);
        System.out.println("negative = " + negative);
        System.out.println("stillPositive = " + stillPositive);

        // Logical NOT
        boolean flag = true;
        System.out.println("!flag = " + (!flag));

        // Bitwise NOT
        int num = 5;
        System.out.println("~num = " + (~num));
    }
}

Ternary Operator

The ternary operator is the only conditional operator in Java that takes three operands. It's a shorthand for if-else statements.

Syntax

condition ? expression1 : expression2

If the condition is true, expression1 is evaluated; otherwise, expression2 is evaluated.

Ternary Operator Example

public class TernaryOperator {
    public static void main(String[] args) {
        int a = 10, b = 20;

        // Find the maximum of two numbers
        int max = (a > b) ? a : b;
        System.out.println("Maximum of " + a + " and " + b + " is: " + max);

        // Check if a number is even or odd
        int number = 15;
        String result = (number % 2 == 0) ? "even" : "odd";
        System.out.println(number + " is " + result);

        // Nested ternary operators
        int x = 5, y = 10, z = 15;
        int largest = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
        System.out.println("Largest among " + x + ", " + y + ", " + z + " is: " + largest);

        // Using ternary with method calls
        String message = (isPositive(number)) ? "Number is positive" : "Number is not positive";
        System.out.println(message);
    }

    public static boolean isPositive(int num) {
        return num > 0;
    }
}

Operator Precedence and Associativity

Operator precedence determines the order in which operators are evaluated in an expression. Associativity determines the order in which operators of the same precedence are evaluated.

Operator Precedence (highest to lowest)

  1. Postfix operators: ++, --
  2. Unary operators: +, -, ++, --, !, ~
  3. Multiplicative: *, /, %
  4. Additive: +, -
  5. Shift: <<, >>, >>>
  6. Relational: <, >, <=, >=, instanceof
  7. Equality: ==, !=
  8. Bitwise AND: &
  9. Bitwise XOR: ^
  10. Bitwise OR: |
  11. Logical AND: &&
  12. Logical OR: ||
  13. Ternary: ? :
  14. Assignment: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=

Operator Precedence Example

public class OperatorPrecedence {
    public static void main(String[] args) {
        int a = 5, b = 10, c = 15;

        // Multiplication has higher precedence than addition
        int result1 = a + b * c;  // Equivalent to: a + (b * c)
        System.out.println("a + b * c = " + result1); // 5 + 150 = 155

        // Parentheses can change precedence
        int result2 = (a + b) * c; // Equivalent to: (a + b) * c
        System.out.println("(a + b) * c = " + result2); // 15 * 15 = 225

        // Logical AND has higher precedence than logical OR
        boolean result3 = a > 3 && b < 20 || c == 10; // Equivalent to: (a > 3 && b < 20) || c == 10
        System.out.println("Complex boolean expression: " + result3); // true

        // Assignment has lowest precedence
        int x = 5;
        int y = x = 10; // x = 10 first, then y = x
        System.out.println("x = " + x + ", y = " + y); // x = 10, y = 10
    }
}

Practical Examples

Let's look at some practical examples that demonstrate the use of various operators:

public class OperatorExamples {
    public static void main(String[] args) {
        // Temperature conversion
        double celsius = 25.0;
        double fahrenheit = (celsius * 9 / 5) + 32;
        System.out.println(celsius + "°C = " + fahrenheit + "°F");

        // Checking if a number is within a range
        int number = 15;
        boolean inRange = number >= 10 && number <= 20;
        System.out.println(number + " is in range [10, 20]: " + inRange);

        // Bit manipulation for flags
        int flags = 0;
        final int READ_FLAG = 1;    // 0001
        final int WRITE_FLAG = 2;   // 0010
        final int EXEC_FLAG = 4;    // 0100

        // Set flags
        flags |= READ_FLAG | WRITE_FLAG; // Set read and write permissions
        System.out.println("Flags after setting read and write: " + Integer.toBinaryString(flags));

        // Check flags
        boolean canRead = (flags & READ_FLAG) != 0;
        boolean canWrite = (flags & WRITE_FLAG) != 0;
        boolean canExecute = (flags & EXEC_FLAG) != 0;

        System.out.println("Can read: " + canRead);
        System.out.println("Can write: " + canWrite);
        System.out.println("Can execute: " + canExecute);

        // Clear a flag
        flags &= ~WRITE_FLAG; // Remove write permission
        System.out.println("Flags after clearing write: " + Integer.toBinaryString(flags));

        // Swapping two numbers without temporary variable
        int x = 10, y = 20;
        System.out.println("Before swap: x = " + x + ", y = " + y);

        x = x ^ y;
        y = x ^ y;
        x = x ^ y;
        System.out.println("After swap: x = " + x + ", y = " + y);

        // Calculating compound interest
        double principal = 1000.0;
        double rate = 0.05; // 5%
        int years = 3;

        double amount = principal * Math.pow(1 + rate, years);
        double interest = amount - principal;

        System.out.println("Principal: $" + principal);
        System.out.println("Interest earned: $" + String.format("%.2f", interest));
        System.out.println("Total amount: $" + String.format("%.2f", amount));
    }
}

Best Practices

When working with operators in Java:

  • Use parentheses to make complex expressions clearer and avoid precedence issues
  • Be careful with integer division - it truncates the decimal part
  • Use compound assignment operators for concise code
  • Avoid complex expressions in a single line - break them down for readability
  • Use bitwise operators only when necessary for performance-critical code
  • Remember that logical operators use short-circuit evaluation
  • Use the ternary operator for simple conditional assignments
  • Be aware of the difference between pre-increment (++x) and post-increment (x++)
  • Use meaningful variable names to make expressions self-documenting
  • Test edge cases when using operators, especially with boundary values

Mastering operators is fundamental to writing efficient and correct Java programs. They form the building blocks for all computations and decision-making in your code.