Programming and Java Fundamentals

Operators and Expressions

ReadingPreview

You are viewing a free preview lesson.

Lesson Overview

Programs do not only store data. They also perform calculations, comparisons, and logical operations on stored data.

For example:

  • Adding two numbers
  • Calculating a total from product price and quantity
  • Checking whether age is 18 or above
  • Determining whether both email and password are valid
  • Increasing a counter value
  • Updating an existing variable

In Java, we use operators to perform these operations.

int total = 10 + 20;

Here, + is an operator.

Another example:

boolean isAdult = age >= 18;

Here, >= is a comparison operator.

In this lesson, we will learn:

  • Operator, operand, and expression
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Increment and decrement
  • Operator precedence
  • Parentheses
  • Short-circuit evaluation
  • String concatenation

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

What Is an Operator?

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

int total = 10 + 20;

Here:

  • 10 — operand
  • 20 — operand
  • + — operator
  • 10 + 20 — expression

What Is an Operand?

A value or variable that an operator works on is called an operand.

firstNumber + secondNumber

Here:

firstNumber
secondNumber

are the two operands.

What Is an Expression?

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

10 + 20

Result:

30

Another expression:

age >= 18

This produces a boolean result:

true

or:

false

Expression and Statement

Expression:

10 + 20

produces a value.

Statement:

int total = 10 + 20;

is a complete instruction.

Here, 10 + 20 is an expression, while the complete line is a statement.

Arithmetic Operators

Basic arithmetic operators:

OperatorPurpose
+Addition
-Subtraction
*Multiplication
/Division
%Remainder

Addition +

int firstNumber = 10;
int secondNumber = 20;

int total = firstNumber + secondNumber;

System.out.println(total);

Output:

30

Subtraction -

int totalAmount = 1000;
int spentAmount = 350;

int remainingAmount =
        totalAmount - spentAmount;

System.out.println(remainingAmount);

Output:

650

Multiplication *

int productPrice = 500;
int quantity = 3;

int totalPrice =
        productPrice * quantity;

System.out.println(totalPrice);

Output:

1500

Division /

int total = 20;
int count = 4;

int result = total / count;

System.out.println(result);

Output:

5

Integer Division

When two integers are divided, the fractional part is discarded.

int result = 5 / 2;

System.out.println(result);

Output:

2

To get a decimal result, at least one operand must be floating-point:

double result = 5.0 / 2;

System.out.println(result);

Output:

2.5

Common Average Bug

int totalMarks = 250;
int subjectCount = 3;

double average =
        totalMarks / subjectCount;

Here, the division is performed using integer arithmetic first.

Better:

double average =
        totalMarks / 3.0;

Now a decimal result is produced.

Remainder %

% returns the remainder of a division.

int remainder = 10 % 3;

System.out.println(remainder);

Output:

1

Even Number Check

int number = 10;

boolean isEven =
        number % 2 == 0;

System.out.println(isEven);

Output:

true

Assignment Operator =

To assign a value to a variable:

int age = 30;

Here:

=

is the assignment operator.

The value on the right side is stored in the variable on the left side.

Reassignment

int score = 80;

score = 90;

System.out.println(score);

Output:

90

Compound Assignment

A shorter form for updating an existing variable:

OperatorEquivalent
+=value = value + ...
-=value = value - ...
*=value = value * ...
/=value = value / ...
%=value = value % ...

+=

int score = 10;

score += 5;

System.out.println(score);

Output:

15

Equivalent:

score = score + 5;

Other Compound Assignment Operators

int value = 20;

value -= 5;
value *= 2;
value /= 3;

Compound assignment helps make code more concise.

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

Equality ==

int age = 18;

boolean exactAge =
        age == 18;

System.out.println(exactAge);

Output:

true

Assignment and Equality

Assignment:

age = 18;

Equality comparison:

age == 18

A single = and double == serve different purposes.

Not Equal !=

int score = 80;

boolean notPerfect =
        score != 100;

System.out.println(notPerfect);

Output:

true

Greater and Less Comparison

int age = 20;

boolean isAdult = age >= 18;
boolean isChild = age < 18;

A comparison expression always returns:

true

or:

false

Range Check

Suppose a valid mark must be between 0 and 100.

int mark = 85;

boolean validMark =
        mark >= 0
        && mark <= 100;

Here, two comparisons are combined using logical AND.

Logical Operators

Logical operators are used to combine multiple boolean conditions.

OperatorMeaning
&&AND
``OR
!NOT

Logical AND &&

The result is true only when both conditions are true.

boolean emailValid = true;
boolean passwordValid = true;

boolean canLogin =
        emailValid && passwordValid;

System.out.println(canLogin);

Output:

true

If either condition is false, the result is:

false

Range Check with &&

int age = 25;

boolean withinRange =
        age >= 18
        && age <= 60;

Both conditions must be true.

Logical OR ||

The result is true when at least one condition is true.

boolean isInstructor = false;
boolean isTeamMember = true;

boolean hasAccess =
        isInstructor || isTeamMember;

System.out.println(hasAccess);

Output:

true

Logical NOT !

Reverses a boolean value.

boolean accountBlocked = false;

boolean accountAllowed =
        !accountBlocked;

System.out.println(accountAllowed);

Output:

true

Combining Multiple Conditions

int age = 20;
boolean emailVerified = true;
boolean accountBlocked = false;

boolean canEnroll =
        age >= 18
        && emailVerified
        && !accountBlocked;

System.out.println(canEnroll);

Output:

true

Short-Circuit Evaluation

&& and || use short-circuit evaluation.

This means that when Java can already determine the result of an expression, it may not evaluate the remaining part.

Short-Circuit AND

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.

Order Matters

Wrong:

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

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

Correct:

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

Increment ++

Increases a variable's value by 1.

int count = 10;

count++;

System.out.println(count);

Output:

11

Equivalent:

count = count + 1;

or:

count += 1;

Decrement --

Decreases a variable's value by 1.

int count = 10;

count--;

System.out.println(count);

Output:

9

Prefix and Postfix

Increment can be written in two ways:

++count

and:

count++

As standalone statements:

count++;

or:

++count;

both increase count by 1.

The difference matters when increment is used inside an expression.

Prefix

int count = 10;

int result = ++count;

Final values:

count = 11
result = 11

Postfix

int count = 10;

int result = count++;

Final values:

count = 11
result = 10

Keep It Simple

Avoid expressions like:

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.

int result = 10 + 5 * 2;

Multiplication happens first:

5 * 2 = 10
10 + 10 = 20

Result:

20

Control Order with Parentheses

int result = (10 + 5) * 2;

Now the expression inside the parentheses is evaluated first:

10 + 5 = 15
15 * 2 = 30

Result:

30

Simplified Precedence

As a beginner, remember this order:

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

When Operators Have the Same Precedence

Multiplication and division have the same precedence level.

int result = 20 / 5 * 2;

Evaluation happens from left to right:

20 / 5 = 4
4 * 2 = 8

Result:

8

Parentheses Improve Readability

Less clear:

boolean allowed =
        isAdmin
        || isInstructor && isActive;

Clearer:

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.

Numeric:

int result = 10 + 20;

Result:

30

String:

String result =
        "Java" + " Foundation";

Result:

Java Foundation

Mixing String and Number

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

Output:

Total: 1020

But:

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

Output:

Total: 30

Parentheses force the calculation to happen first.

Complete Example: Student Result

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:

Total: 255
Average: 85.0
Passed: true

Complete Example: Enrollment Eligibility

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:

Can enroll: true

Common Errors

Confusing Assignment and Comparison

Assignment:

age = 18;

Comparison:

age == 18

Keep the difference clear.

Integer Division

double average = 5 / 2;

Result:

2.0

Correct:

double average = 5.0 / 2;

Wrong Logical Operator

Requirement:

Both email and password must be valid.

Wrong:

boolean canLogin =
        emailValid || passwordValid;

Correct:

boolean canLogin =
        emailValid && passwordValid;

Wrong Range Logic

Wrong:

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

Correct:

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

Wrong Null Check Order

Wrong:

boolean valid =
        !name.isBlank()
        && name != null;

Correct:

boolean valid =
        name != null
        && !name.isBlank();

String Concatenation Instead of Addition

Wrong expectation:

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

Output:

Total: 1020

Correct:

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

Important Terms

Operator

A symbol that performs an operation on values.

Operand

A value or variable that an operator works on.

Expression

A combination of values, variables, and operators that produces a result.

Arithmetic Operator

An operator used for numeric calculations.

Assignment Operator

Assigns a value to a variable.

Compound Assignment

Performs an operation and assignment together.

Comparison Operator

Compares two values and produces a boolean result.

Logical Operator

Combines or reverses boolean conditions.

Increment

Increases a value by 1.

Decrement

Decreases a value by 1.

Prefix

Updates the value first, then uses the updated value in the expression.

Postfix

Uses the current value in the expression first, then updates it.

Operator Precedence

Determines the order in which multiple operators are evaluated.

Short-Circuit Evaluation

Skips evaluating the remaining part of an expression when the result is already known.

Practice Exercise 1: Operator and Operand

Expression:

price * quantity

Identify:

  1. Operator
  2. First operand
  3. Second operand

Practice Exercise 2: Arithmetic

int firstNumber = 20;
int secondNumber = 6;

Calculate:

  • Addition
  • Subtraction
  • Multiplication
  • Integer division
  • Remainder

Practice Exercise 3: Predict the Output

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

Practice Exercise 4: Compound Assignment

Rewrite using the short form:

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

Practice Exercise 5: Comparison

int firstValue = 10;
int secondValue = 20;

Predict:

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

Practice Exercise 6: Range Check

A mark is valid if it is between:

0 to 100

Write the Java boolean expression.

Practice Exercise 7: Login Validation

boolean emailValid = true;
boolean passwordValid = false;

Requirement:

Login is allowed only if both are valid.

Write the canLogin expression.

Practice Exercise 8: Prefix vs. Postfix

Predict the values:

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

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

Practice Exercise 9: Concatenation

Predict the output:

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

Practice Exercise 10: 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

+
-
*
/
%

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.

5.0 / 2

Answer 8

Assignment:

=

Equality:

==

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 may skip 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

In this lesson, we learned:

  • Operators perform operations on values
  • Operands are the inputs to operators
  • Expressions evaluate to results
  • +, -, *, /, and % are arithmetic operators
  • Integer division discards the fractional part
  • A floating-point operand is required for a decimal result
  • % returns the remainder
  • = is assignment and == is comparison
  • Compound assignment makes variable updates concise
  • Comparison operators return boolean results
  • &&, ||, and ! are logical operators
  • && and || can short-circuit
  • The order of null checks matters
  • ++ and -- change a value by 1
  • Prefix and postfix behave differently inside expressions
  • Operator precedence determines evaluation order
  • Parentheses make evaluation order and intent clearer
  • + is used for both numeric addition and String concatenation