Java Day 3: Operators and Expressions

Goal of this Day

Today you will learn:

By the end, you will be able to perform calculations and make decisions in Java.

Step 1: Arithmetic Operators

Arithmetic operators are used to perform calculations.

Example:


int a = 10;
int b = 3;

System.out.println("Sum: " + (a + b));
System.out.println("Remainder: " + (a % b));

Step 2: Assignment Operators

Assignment operators are used to assign values to variables.

Example:


int x = 5;
x += 3;  // x is now 8

Step 3: Comparison Operators

These operators compare values.

Example:


int age = 18;

if (age >= 18) {
    System.out.println("You are an adult");
}

Step 4: Logical Operators

Logical operators combine conditions.

&& (AND)

Both conditions must be true.


if (age >= 18 && age < 65) {
    System.out.println("Working age");
}

|| (OR)

At least one condition must be true.


if (age < 18 || age > 65) {
    System.out.println("Not typical working age");
}

! (NOT)

Reverses a condition.


boolean isStudent = false;

if (!isStudent) {
    System.out.println("Not a student");
}

Practice


int a = 10;
int b = 3;

System.out.println("Sum: " + (a + b));
System.out.println("Remainder: " + (a % b));

Exercise

Write a program that checks if a number is even or odd.

Steps:

Example:


public class EvenOdd {
    public static void main(String[] args) {
        int number = 7;

        if (number % 2 == 0) {
            System.out.println("The number is even");
        } else {
            System.out.println("The number is odd");
        }
    }
}