Lesson 12 of 140
Written lesson · 15 min

Operators and Expressions

Write arithmetic, comparison and logical expressions, and understand compound assignment, increment, precedence and short-circuit evaluation.

Preview

You are viewing a free preview lesson.

Lesson Overview

Programs do not only store data. They also calculate with it, compare it and combine conditions: a total from price and quantity, whether a learner is 18 or older, whether both email and password are valid, a counter that goes up by one. In Java, we use operators to perform these operations:

java
int total = 10 + 20;
boolean isAdult = age >= 18;

Here, + is an operator, and >= is a comparison operator. Most operators look like school maths, but a few behave in ways that surprise beginners (integer division, = versus ==, the order of evaluation), and those are where bugs come from.

Learning Objectives

After completing this lesson, you will be able to:

  • Identify operators, operands, and expressions
  • Perform arithmetic calculations
  • Use assignment and compound assignment
  • Compare values
  • Combine multiple boolean conditions
  • Use increment and decrement
  • Understand operator precedence
  • Control evaluation order using parentheses
  • Understand the basic behavior of short-circuit evaluation
  • Distinguish between String concatenation and numeric addition

Operators, Operands, and Expressions

An operator is a symbol that performs an operation on one or more values. A value or variable that an operator works on is called an operand, and a combination of values, variables, and operators that evaluates to a result is called an expression. In this statement:

java
int total = 10 + 20;
  • 10 — operand
  • 20 — operand
  • + — operator
  • 10 + 20 — expression

In the same way, the two operands of firstNumber + secondNumber are firstNumber and secondNumber. The expression 10 + 20 evaluates to 30, and the expression age >= 18 produces a boolean result: true or false.

An expression produces a value, while a statement is a complete instruction. In int total = 10 + 20;, 10 + 20 is an expression, while the complete line is a statement.

Arithmetic Operators

Java has five basic arithmetic operators:

OperatorPurpose
+Addition
-Subtraction
*Multiplication
/Division
%Remainder

This snippet uses each of them once:

java
int firstNumber = 10;
int secondNumber = 20;
int totalAmount = 1000;
int spentAmount = 350;
int productPrice = 500;
int quantity = 3;

System.out.println(firstNumber + secondNumber);
System.out.println(totalAmount - spentAmount);
System.out.println(productPrice * quantity);
System.out.println(20 / 4);
System.out.println(10 % 3);

Output:

text
30
650
1500
5
1

% returns the remainder of a division, so 10 % 3 is 1. A common use of the remainder is checking whether a number is even:

java
int number = 10;
boolean isEven = number % 2 == 0;
System.out.println(isEven);

Output:

text
true

Integer Division

When two integers are divided, the fractional part is discarded. To get a decimal result, at least one operand must be floating-point:

java
int result = 5 / 2;
double decimalResult = 5.0 / 2;
System.out.println(result);
System.out.println(decimalResult);

Output:

text
2
2.5

This causes a common bug when calculating an average:

java
int totalMarks = 250;
int subjectCount = 3;
double average = totalMarks / subjectCount;

Here, the division is performed using integer arithmetic first. Dividing by 3.0 produces a decimal result:

java
double average = totalMarks / 3.0;

Assignment and Compound Assignment

In int age = 30;, the assignment operator = stores the value on its right side in the variable on its left side. Assigning to the same variable again replaces its value:

java
int score = 80;
score = 90;
System.out.println(score);

Output:

text
90

Compound assignment is a shorter form for updating an existing variable:

OperatorEquivalent
+=value = value + ...
-=value = value - ...
*=value = value * ...
/=value = value / ...
%=value = value % ...
java
int score = 10;
score += 5;
System.out.println(score);

Output:

text
15

Here, score += 5; is equivalent to score = score + 5;. The other compound assignment operators work the same way, and they help make code more concise:

java
int value = 20;
value -= 5;
value *= 2;
value /= 3;

Comparison Operators

Comparison operators compare two values and produce a boolean result:

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
java
int age = 20;
int score = 80;
boolean exactAge = age == 18;
boolean notPerfect = score != 100;
boolean isAdult = age >= 18;
boolean isChild = age < 18;

System.out.println(exactAge);
System.out.println(notPerfect);
System.out.println(isAdult);
System.out.println(isChild);

Output:

text
false
true
true
false

A comparison expression always returns true or false. Be careful with equality: assignment is written age = 18;, while equality comparison is written age == 18. A single = and double == serve different purposes.

Logical Operators

Logical operators are used to combine multiple boolean conditions:

OperatorMeaning
&&AND
||OR
!NOT

With &&, the result is true only when both conditions are true; if either condition is false, the result is false. With ||, the result is true when at least one condition is true. ! reverses a boolean value.

java
boolean emailValid = true;
boolean passwordValid = true;
boolean isInstructor = false;
boolean isTeamMember = true;
boolean accountBlocked = false;

boolean canLogin = emailValid && passwordValid;
boolean hasAccess = isInstructor || isTeamMember;
boolean accountAllowed = !accountBlocked;

System.out.println(canLogin);
System.out.println(hasAccess);
System.out.println(accountAllowed);

Output:

text
true
true
true

Logical operators are often combined with comparisons. Suppose a valid mark must be between 0 and 100. Two comparisons are combined using logical AND:

java
int mark = 85;
boolean validMark = mark >= 0 && mark <= 100;

You can combine more than two conditions in the same way:

java
int age = 20;
boolean emailVerified = true;
boolean accountBlocked = false;
boolean canEnroll = age >= 18 && emailVerified && !accountBlocked;
System.out.println(canEnroll);

Output:

text
true

Short-Circuit Evaluation

&& and || use short-circuit evaluation. This means that when Java can already determine the result of an expression, it does not evaluate the remaining part.

java
String value = null;
boolean valid = value != null && !value.isBlank();

If value != null is false, Java will not call value.isBlank(). This can prevent a NullPointerException, but only when the conditions are in the right order. Wrong:

java
boolean valid = !value.isBlank() && value != null;

If value is null, the first expression already causes an error. Correct:

java
boolean valid = value != null && !value.isBlank();

Increment and Decrement

++ increases a variable's value by 1, and -- decreases it by 1:

java
int count = 10;
count++;
System.out.println(count);
count--;
System.out.println(count);

Output:

text
11
10

Here, count++; is equivalent to count = count + 1; or count += 1;.

Prefix and Postfix

Increment can be written in two ways: ++count and count++. As standalone statements, count++; and ++count; both increase count by 1. The difference matters when increment is used inside an expression. With prefix:

java
int count = 10;
int result = ++count;

Final values:

text
count = 11
result = 11

With postfix:

java
int count = 10;
int result = count++;

Final values:

text
count = 11
result = 10

Keep it simple and avoid expressions like:

java
int result = count++ + ++count;

This may be technically valid, but it is difficult to read and reason about. Prefer count++; where the increment is standalone and clear.

Operator Precedence

When an expression contains multiple operators, precedence determines which operation is performed first.

java
int result = 10 + 5 * 2;

Multiplication happens first, so the result is 20:

text
5 * 2 = 10
10 + 10 = 20

Parentheses control the order. Here, the expression inside the parentheses is evaluated first, so the result is 30:

java
int result = (10 + 5) * 2;
text
10 + 5 = 15
15 * 2 = 30

As a beginner, remember this order:

  1. Parentheses
  2. Unary operators
  3. *, /, %
  4. +, -
  5. <, <=, >, >=
  6. ==, !=
  7. &&
  8. ||
  9. Assignment

Multiplication and division have the same precedence level. When operators have the same precedence, evaluation happens from left to right, so the result here is 8:

java
int result = 20 / 5 * 2;
text
20 / 5 = 4
4 * 2 = 8

Parentheses Improve Readability

Less clear:

java
boolean allowed = isAdmin || isInstructor && isActive;

Clearer:

java
boolean allowed = isAdmin || (isInstructor && isActive);

The compiler can understand the expression without parentheses, but parentheses make the intent clearer for the reader.

String Concatenation

+ is used for both numeric addition and String concatenation:

java
int sum = 10 + 20;
String title = "Java" + " Foundation";
System.out.println(sum);
System.out.println(title);

Output:

text
30
Java Foundation

When a String and numbers are mixed, the order of evaluation decides the result, and parentheses force the calculation to happen first:

java
System.out.println("Total: " + 10 + 20);
System.out.println("Total: " + (10 + 20));

Output:

text
Total: 1020
Total: 30

Complete Examples

Student Result

java
public class Main {

    public static void main(String[] args) {
        int mathematicsMark = 80;
        int englishMark = 90;
        int scienceMark = 85;

        int totalMarks = mathematicsMark + englishMark + scienceMark;
        double averageMark = totalMarks / 3.0;
        boolean passed =
                mathematicsMark >= 40 && englishMark >= 40 && scienceMark >= 40;

        System.out.println("Total: " + totalMarks);
        System.out.println("Average: " + averageMark);
        System.out.println("Passed: " + passed);
    }
}

Output:

text
Total: 255
Average: 85.0
Passed: true

Enrollment Eligibility

java
public class Main {

    public static void main(String[] args) {
        int learnerAge = 20;
        boolean emailVerified = true;
        boolean accountBlocked = false;
        boolean enrollmentOpen = true;

        boolean canEnroll =
                learnerAge >= 18
                && emailVerified && !accountBlocked && enrollmentOpen;

        System.out.println("Can enroll: " + canEnroll);
    }
}

Output:

text
Can enroll: true

Predict the Result

Question 1

java
System.out.println(10 + 5 * 2);
System.out.println((10 + 5) * 2);
System.out.println(20 / 5 * 2);

What does this print?

Answer

text
20
30
8

* runs before +, and parentheses change that order. / and * have the same precedence, so they run from left to right: 20 / 5 is 4, then 4 * 2 is 8.

Question 2

java
System.out.println(7 / 2 * 2.0);
System.out.println(7 % 3);
System.out.println(7.0 / 2);

What does this print?

Answer

text
6.0
1
3.5

7 / 2 uses two int values, so it is integer division and gives 3; only then is it multiplied by 2.0. 7 % 3 is the remainder 1. With 7.0, the division keeps the decimal part.

Question 3

java
int firstValue = 5;
int firstResult = ++firstValue;

int secondValue = 5;
int secondResult = secondValue++;

System.out.println(firstValue + " " + firstResult);
System.out.println(secondValue + " " + secondResult);

What does this print?

Answer

text
6 6
6 5

Both variables end up as 6. Prefix ++firstValue increases first and then gives the new value; postfix secondValue++ gives the old value 5 and then increases.

Question 4

java
System.out.println(1 + 2 + "3" + 4 * 5);

What does this print?

Answer

3320. 4 * 5 runs first because of precedence, giving 20. Then + works from left to right: 1 + 2 is 3, 3 + "3" is the text "33", and "33" + 20 is "3320".

Question 5

java
int count = 0;
boolean result = count != 0 && 10 / count > 1;
System.out.println(result);

What does this print?

Answer

false. count != 0 is false, so && short-circuits and never evaluates 10 / count. Without the first check, dividing by zero would stop the program with an error.

Common Mistakes

Integer Division

Storing the result in a double does not help, because the division has already happened with integers:

java
double average = 5 / 2;

The result is 2.0. Correct:

java
double average = 5.0 / 2;

Wrong Logical Operator

Requirement:

Both email and password must be valid.

Wrong:

java
boolean canLogin = emailValid || passwordValid;

Correct:

java
boolean canLogin = emailValid && passwordValid;

Wrong Range Logic

With ||, every number passes, because any number is either at least 0 or at most 100. Wrong:

java
boolean valid = mark >= 0 || mark <= 100;

Correct:

java
boolean valid = mark >= 0 && mark <= 100;

The other classic mistakes in this lesson, = instead of ==, the null check placed after isBlank(), and "Total: " + 10 + 20, are shown with their fixes in their own sections above.

Practice Exercise 1: Operator and Operand

Solutions: lesson 1.24.

In the expression price * quantity, identify:

  1. Operator
  2. First operand
  3. Second operand

Practice Exercise 2: Arithmetic

java
int firstNumber = 20;
int secondNumber = 6;

Calculate:

  • Addition
  • Subtraction
  • Multiplication
  • Integer division
  • Remainder

Practice Exercise 3: Compound Assignment

Rewrite using the short form:

java
score = score + 10;
balance = balance - 500;
price = price * 2;

Practice Exercise 4: Comparison

java
int firstValue = 10;
int secondValue = 20;

Predict:

java
firstValue == secondValue
firstValue != secondValue
firstValue < secondValue
firstValue >= 10

Practice Exercise 5: Range Check

A mark is valid if it is between 0 and 100. Write the Java boolean expression.

Practice Exercise 6: Login Validation

java
boolean emailValid = true;
boolean passwordValid = false;

Requirement:

Login is allowed only if both are valid.

Write the canLogin expression.

Practice Exercise 7: Enrollment

Requirements:

  • Age at least 18
  • Email verified
  • Account is not blocked
  • Enrollment is open

Write a canEnroll boolean expression.

Knowledge Check

Question 1

What is an operator?

Question 2

What is an operand?

Question 3

What is an expression?

Question 4

What are the basic arithmetic operators?

Question 5

What does % return?

Question 6

What is the result of 5 / 2?

Question 7

What is required to get a decimal division result?

Question 8

What are the assignment and equality operators?

Question 9

What does a comparison operator return?

Question 10

Which operator is logical AND?

Question 11

Which operator is logical OR?

Question 12

Which operator is logical NOT?

Question 13

When does && return true?

Question 14

When does || return true?

Question 15

What is short-circuit evaluation?

Question 16

What does ++ do?

Question 17

What is the difference between prefix and postfix increment?

Question 18

What is the result of 10 + 5 * 2?

Question 19

What is the result of (10 + 5) * 2?

Question 20

What is the output of "Total: " + 10 + 20?

Knowledge Check Answers

Answer 1

An operator is a symbol that performs an operation on one or more values.

Answer 2

An operand is the value or variable that an operator works on.

Answer 3

An expression is a combination of values, variables, and operators that evaluates to a result.

Answer 4

+, -, *, / and %.

Answer 5

The remainder of a division.

Answer 6

2, because it uses integer division.

Answer 7

At least one operand must be floating-point, for example 5.0 / 2.

Answer 8

Assignment is =, and equality is ==.

Answer 9

A boolean.

Answer 10

&&

Answer 11

||

Answer 12

!

Answer 13

When both conditions are true.

Answer 14

When at least one condition is true.

Answer 15

Short-circuit evaluation means Java skips evaluating the remaining part of an expression when the result is already known.

Answer 16

It increases a variable's value by 1.

Answer 17

Prefix updates the value first and then uses the updated value. Postfix uses the current value first and then updates it.

Answer 18

20

Answer 19

30

Answer 20

Total: 1020

Lesson Summary

  • An expression combines operands and operators and evaluates to a result; a statement is a complete instruction.
  • Arithmetic operators are +, -, *, / and %, and dividing two integers discards the fractional part.
  • = assigns a value, == compares values, and compound assignment such as score += 5; updates an existing variable.
  • Comparison operators produce a boolean, and &&, || and ! combine or reverse boolean conditions.
  • && and || short-circuit, so write value != null && !value.isBlank() with the null check first.
  • Prefix ++count updates before the value is used, postfix count++ uses the value first; keep increments standalone for clarity.
  • Precedence decides which operator runs first, and parentheses make the order explicit, including "Total: " + (10 + 20).

Think first

Coming soon

Checkpoint questions that ask you to commit to an answer before the lesson shows it.