Operators

Operators are used to perform operations on variables and values. This lesson covers the various operators in Java.

Arithmetic Operators

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
++ Increment i++ i increases by 1
-- Decrement i-- i decreases by 1

Example: Arithmetic Operations

JAVA
public class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 10, b = 3;
        
        System.out.println("a + b = " + (a + b));  // 13
        System.out.println("a - b = " + (a - b));  // 7
        System.out.println("a * b = " + (a * b));  // 30
        System.out.println("a / b = " + (a / b));  // 3 (integer division, decimals truncated)
        System.out.println("a % b = " + (a % b));  // 1
        
        // Floating-point division
        double c = 10.0, d = 3.0;
        System.out.println("c / d = " + (c / d));  // 3.3333...
    }
}
▶ Try it Yourself
⚠️ Integer division: When two integers are divided, the result is also an integer, and the decimal part is truncated. To get a decimal result, at least one operand must be a floating-point number.

Increment and Decrement

JAVA
int i = 5;

// Post-increment: use first, then increase
int a = i++;  // a = 5, i = 6

// Pre-increment: increase first, then use
int b = ++i;  // b = 7, i = 7

Assignment Operators

Operator Description Example Equivalent To
= Assignment a = 5
+= Add and assign a += 3 a = a + 3
-= Subtract and assign a -= 3 a = a - 3
*= Multiply and assign a *= 3 a = a * 3
/= Divide and assign a /= 3 a = a / 3
%= Modulus and assign a %= 3 a = a % 3

Example: Assignment Operations

JAVA
public class AssignmentDemo {
    public static void main(String[] args) {
        int a = 10;
        System.out.println("Initial value: " + a);  // 10
        
        a += 5;
        System.out.println("a += 5: " + a);  // 15
        
        a -= 3;
        System.out.println("a -= 3: " + a);  // 12
        
        a *= 2;
        System.out.println("a *= 2: " + a);  // 24
        
        a /= 4;
        System.out.println("a /= 4: " + a);  // 6
        
        a %= 4;
        System.out.println("a %= 4: " + a);  // 2
    }
}
▶ Try it Yourself

Comparison Operators

Comparison operators return a boolean value (true or false).

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

Example: Comparison Operations

JAVA
public class ComparisonDemo {
    public static void main(String[] args) {
        int a = 10, b = 20;
        
        System.out.println("a == b: " + (a == b));  // false
        System.out.println("a != b: " + (a != b));  // true
        System.out.println("a > b: " + (a > b));    // false
        System.out.println("a < b: " + (a < b));    // true
        System.out.println("a >= 10: " + (a >= 10)); // true
        System.out.println("a <= 5: " + (a <= 5));   // false
    }
}
▶ Try it Yourself

Logical Operators

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

Logical Operators Truth Table

A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true

Example: Logical Operations

JAVA
public class LogicDemo {
    public static void main(String[] args) {
        int age = 25;
        boolean hasID = true;
        
        // Age >= 18 and has ID
        boolean canEnter = (age >= 18) && hasID;
        System.out.println("Can enter: " + canEnter);  // true
        
        // Age < 12 or > 60
        boolean isSpecial = (age < 12) || (age > 60);
        System.out.println("Special category: " + isSpecial);  // false
        
        // Logical NOT
        boolean isAdult = age >= 18;
        System.out.println("Is adult: " + isAdult);    // true
        System.out.println("Not adult: " + !isAdult);  // false
    }
}
▶ Try it Yourself
💡 Short-circuit evaluation: && stops if the left side is false; || stops if the left side is true. The right side is not evaluated in these cases.

Ternary Operator

The ternary operator is a shorthand for if-else.

JAVA
// Syntax: condition ? value1 : value2
int max = (a > b) ? a : b;

Example: Ternary Operator

JAVA
public class TernaryDemo {
    public static void main(String[] args) {
        int a = 10, b = 20;
        
        // Find maximum
        int max = (a > b) ? a : b;
        System.out.println("Maximum: " + max);  // 20
        
        // Check odd or even
        int num = 7;
        String result = (num % 2 == 0) ? "even" : "odd";
        System.out.println(num + " is " + result);  // 7 is odd
        
        // Absolute value
        int x = -5;
        int abs = (x >= 0) ? x : -x;
        System.out.println("Absolute value: " + abs);  // 5
    }
}
▶ Try it Yourself

Operator Precedence

Operators with higher precedence are evaluated first. Use parentheses to change precedence.

Precedence Operator Description
1 () Parentheses
2 ! ++ -- Unary operators
3 * / % Multiplication, division, modulus
4 + - Addition, subtraction
5 < <= > >= Comparison
6 == != Equality
7 && Logical AND
8 || Logical OR
9 ?: Ternary operator
10 = += -= etc. Assignment

Example: Precedence

JAVA
public class PrecedenceDemo {
    public static void main(String[] args) {
        // Multiplication has higher precedence than addition
        int result1 = 2 + 3 * 4;
        System.out.println("2 + 3 * 4 = " + result1);  // 14, not 20
        
        // Use parentheses to change precedence
        int result2 = (2 + 3) * 4;
        System.out.println("(2 + 3) * 4 = " + result2);  // 20
    }
}
▶ Try it Yourself
💡 Tip: Use parentheses in complex expressions to improve readability and avoid precedence errors.

Type Promotion

When values of different types are mixed in an operation, the smaller type is automatically promoted to the larger type.

JAVA
public class TypePromotion {
    public static void main(String[] args) {
        // int + long → long
        int a = 10;
        long b = 20;
        long c = a + b;
        
        // int + double → double
        int d = 10;
        double e = 3.14;
        double f = d + e;
        
        // byte + byte → int
        byte g = 10;
        byte h = 20;
        // byte i = g + h;  // Error! Result is int type
        int i = g + h;      // Correct
    }
}

❓ Frequently Asked Questions

Q What's the difference between == and equals?
A == compares values for primitives and addresses for references. equals compares object content. Use equals for string comparison.
Q What's the difference between i++ and ++i?
A i++ uses the value first then increments; ++i increments first then uses. When used alone, the effect is the same. The difference only matters in expressions.
Q Why is 0.1 + 0.2 != 0.3?
A Floating-point numbers have precision issues. 0.1 and 0.2 cannot be represented exactly in binary. Use range comparison for floating-point values.

📖 Summary

📝 Exercises

  1. Arithmetic practice: Input a number of seconds and convert it to "X hours X minutes X seconds" format
  2. Comparison practice: Determine if a year is a leap year (divisible by 4 but not by 100, or divisible by 400)
  3. Ternary practice: Input three numbers and find the maximum using the ternary operator

Next Lesson

In the next lesson, we'll learn about Conditional Statements — making decisions in your programs.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏