Java Tutorial menu

Java Operators

Operators are symbols that do work on values, like adding numbers or comparing them.

Arithmetic Operators

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division7 / 32
%Remainder (modulus)7 % 31
++Incrementx++adds 1
--Decrementx--subtracts 1

Example

java
public class Main {
  public static void main(String[] args) {
    int total = 1250;
    int people = 4;

    System.out.println(total / people);
    System.out.println(total % people);
    System.out.println(total / 4.0);
  }
}
Output
312
2
312.5

When both numbers are int, Java does integer division and drops the decimal part. Make one of them a double (like 4.0) to get the exact answer.

Assignment Operators

OperatorSame as
x = 5put 5 in x
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3

Example

java
public class Main {
  public static void main(String[] args) {
    int balance = 1000;
    balance += 500;   // salary arrives
    balance -= 200;   // mobile load
    balance++;        // one rupee bonus
    System.out.println(balance);
  }
}
Output
1301

Comparison Operators

Comparison operators give a boolean answer: true or false.

OperatorMeaning
==equal to
!=not equal to
>greater than
<less than
>=greater than or equal to
<=less than or equal to

Logical Operators

Logical operators combine conditions:

  • && (and): true only if both sides are true
  • || (or): true if at least one side is true
  • ! (not): flips true to false and false to true

Example

java
public class Main {
  public static void main(String[] args) {
    int age = 20;
    boolean hasCnic = true;

    System.out.println(age >= 18);
    System.out.println(age >= 18 && hasCnic);
    System.out.println(age < 18 || !hasCnic);
  }
}
Output
true
true
false

Order of Operations

Java follows normal maths rules: *, / and % happen before + and -. Use brackets to make the order clear:

Example

java
int a = 2 + 3 * 4;     // 14
int b = (2 + 3) * 4;   // 20

Exercise

Exercise

What is the value of 17 % 5 in Java?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp