Java:Java Operators: Arithmetic, Logical, and Bitwise
Java•Operators

Java Operators: Arithmetic, Logical, and Bitwise

Understand precedence, integer division truncation, and short-circuit evaluation in Java expressions.

Syntax

int total = a + b; boolean isValid = (x > 0) && (y < 10);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&&, ||Logical OperatorsShort-circuit AND and OR evaluation.
%Modulo OperatorCalculates remainder after division.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    public static void main(String[] args) {
        int a = 23;
        int b = 4;

        System.out.println("Addition:       " + (a + b));
        System.out.println("Integer Div:    " + (a / b));
        System.out.println("Floating Div:   " + ((double) a / b));
        System.out.println("Modulo (Rem):   " + (a % b));

        // Short-circuit logical evaluation
        boolean authorized = true;
        boolean tokenExpired = false;
        boolean canProceed = authorized && !tokenExpired;
        System.out.println("Can Proceed:    " + canProceed);
    }
}
Expected Output:
Addition:       27
Integer Div:    5
Floating Div:   5.75
Modulo (Rem):   3
Can Proceed:    true

How It Works: Step-by-Step

  • Lines 7-9: Shows integer division truncation and explicit double casting.
  • Lines 13-15: Evaluates logical AND with boolean negation !.

Key Concepts

  • Integer division in Java truncates any decimal part.
  • Explicitly cast one operand to (double) to perform floating-point division.
  • && and || short-circuit, skipping evaluation of the right operand if the left determines the result.

Common Mistake: Integer overflow when computing large products

Multiplying large integers can overflow beyond Integer.MAX_VALUE without throwing an exception. Use long.

❌ Incorrect
int large = 2000000000 * 2; // Overflows to negative number!
✅ Correct
long large = 2000000000L * 2L; // Correctly uses 64-bit integer

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler