Skip to content
thesarfo

Concept

Operators

Arithmetic, relational, logical, and ternary operators in Java.

views 0

Arithmetic operators

There are 5 arithmetic operators in Java: add, subtract, divide, multiply, and modulus.

class Main {
public static void main(String[] args) {
int number1 = 13;
int number2 = 6;
// addition
System.out.println(number1 + number2);
// subtraction
System.out.println(number1 - number2);
// multiplication
System.out.println(number1 * number2);
// division
System.out.println(number1 / number2);
// modulus
System.out.println(number1 % number2);
}
}

With the division operator, when you divide an int by an int the result will always be an int. So even though sometimes dividing an int by another int might have some remainder, it will still print out a single whole number. To get around that, you have to divide an int by a double, or an int by a float, in order to get remainders behind the decimal point.

Relational operators

They check the relations among multiple operands and return a boolean value as the result.

class Main {
public static void main(String[] args) {
int number1 = 13;
int number2 = 6;
System.out.println(number1 == number2); // is equal to
System.out.println(number1 != number2); // is not equal to
System.out.println(number1 > number2); // is greater than
System.out.println(number1 < number2); // is less than
System.out.println(number1 >= number2); // is greater than or equal to
System.out.println(number1 <= number2); // is less than or equal to
}
}

Logical operators

  • && (and) — both comparisons have to be true for it to be true
  • || (or) — either comparison has to be true for it to be true; false only when both are false
  • ! (not) — reverses a boolean value
  • += or ++ (increment) — adds a value to a variable
  • -= or -- (decrement) — subtracts a value from a variable

You can add the increment or decrement operators before or after the variable.

Ternary operator (?)

In the example below, the ? is the ternary operator. If income is greater than 100,000, we assign the string "First" to className, else we assign "Economy".

public class Practice {
public static void main(String[] args) {
int income = 120_000;
String className = income > 100_000 ? "First" : "Economy";
System.out.println(className);
}
}