๐ŸŽ“ A1Learner
๐Ÿ”

Java Operators

Operators are symbols that perform an operation on values. Arithmetic operators work on numbers, and logical operators work on boolean values.

Division and remainder

Division gives the whole part of the answer. The % operator gives the part the division leaves behind.

public class Main {
  public static void main(String[] args) {
    System.out.println(10 / 3);
    System.out.println(10 % 3);
  }
}

Move a counter by one

The ++ operator adds one to the counter. The -- operator takes one away again.

public class Main {
  public static void main(String[] args) {
    int count = 5;
    count++;
    System.out.println(count);
    count--;
    System.out.println(count);
  }
}

Add in place

The += operator adds 5 to the variable in one step. The total rises from 10 to 15.

public class Main {
  public static void main(String[] args) {
    int total = 10;
    total += 5;
    System.out.println(total);
  }
}

Logical operators print verdicts

The && operator needs both sides true, and the || operator needs one side true. The ! operator reverses the value after it.

public class Main {
  public static void main(String[] args) {
    System.out.println(true && false);
    System.out.println(true || false);
    System.out.println(!true);
  }
}

Example

public class Main {
  public static void main(String[] args) {
    int points = 8;
    points += 2;
    points++;
    System.out.println(points);
    System.out.println(points % 4);
    boolean passed = points > 10 && points < 20;
    System.out.println(passed);
  }
}

Key points

  • The + operator adds two values together.
  • The % operator gives the remainder after a division.
  • The ++ operator adds 1 to a variable.
  • The -- operator subtracts 1 from a variable.
  • The += operator adds a value to a variable in place.
  • The && operator gives true only when both sides are true.
  • The || operator gives true when at least one side is true.
  • The ! operator reverses a boolean value.

In this example, points starts at 8. The += line adds 2, and the ++ line adds 1 more, so the variable holds 11. The remainder line prints 3, and the logical test prints true.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

What does 10 % 3 print?