Index

Basic Syntax and Structure

Java for Beginners

2.1 Variables and Data Types

In Java, variables are containers for storing data values. Every variable in Java has a data type, which determines the kind of data it can hold. Java is a statically-typed language, meaning you must declare the type of a variable before using it.

Java data types are categorized into two main types:

Primitive Types

Java has eight primitive data types, which are not objects and represent simple values.

Type Description Example
int Integer values int age = 25;
double Decimal numbers (floating-point) double pi = 3.14;
boolean True or false values boolean isOpen = true;
char A single Unicode character char grade = 'A';
byte Small integers (-128 to 127) byte b = 100;
short Larger than byte short s = 32000;
long Very large integers long population = 8000000000L;
float Less precise decimals than double float temp = 36.6f;

Note: float and long literals require a suffix (f or L).

Reference Types

Reference types store references (addresses) to objects rather than the actual data. Common examples include:

Other reference types include objects created from classes.

Declaring and Initializing Variables

You declare a variable by specifying the type followed by the variable name. You can also assign an initial value at the time of declaration.

int age = 30;
double price = 9.99;
boolean isAvailable = true;
char initial = 'J';
String greeting = "Hello, world!";

You can also declare multiple variables of the same type in one line:

int a = 5, b = 10, c = 15;

Runnable Example 1: Declaring Multiple Variables

public class DeclareMultiple {
    public static void main(String[] args) {
        int x = 10, y = 20, sum;
        sum = x + y;
        System.out.println("Sum: " + sum);
    }
}

Runnable Example 2: Performing Arithmetic

public class ArithmeticExample {
    public static void main(String[] args) {
        double price = 19.99;
        int quantity = 3;
        double total = price * quantity;
        System.out.println("Total cost: $" + total);
    }
}

Runnable Example 3: Using Booleans in Conditions

public class BooleanExample {
    public static void main(String[] args) {
        int age = 18;
        boolean isAdult = age >= 18;

        if (isAdult) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are not an adult.");
        }
    }
}

Type Safety in Java

Java is type-safe, meaning that each variable must be declared with a specific type, and the compiler checks for type mismatches. This helps catch errors early during compilation rather than at runtime.

For example:

int x = 10;
String s = "Hello";
// x = s; // ❌ Compile-time error: incompatible types

Type Conversion

Java supports two types of type conversion:

  1. Implicit (Widening) Conversion – safe conversion from a smaller type to a larger type:

    int a = 10;
    double b = a;  // int to double (safe)
  2. Explicit (Narrowing) Conversion – converting from a larger type to a smaller type, which may lead to data loss:

    double d = 9.78;
    int i = (int) d;  // Explicit cast: double to int
    System.out.println(i);  // Outputs 9
Index

2.2 Operators and Expressions

In Java, operators are special symbols that perform operations on variables and values. Understanding how to use them is key to writing functional, logical programs.

Java provides several types of operators:

Arithmetic Operators

These are used to perform basic mathematical operations.

Operator Description Example (a = 10, b = 3)
+ Addition a + b → 13
- Subtraction a - b → 7
* Multiplication a * b → 30
/ Division a / b → 3
% Modulus (remainder) a % b → 1

Example:

int a = 10, b = 3;
System.out.println("Sum: " + (a + b));
System.out.println("Remainder: " + (a % b));

Comparison Operators

These return true or false depending on the comparison result.

Operator Description Example
== Equal to a == b → false
!= Not equal to a != b → true
> Greater than a > b → true
< Less than a < b → false
>= Greater or equal a >= b → true
<= Less or equal a <= b → false

Example:

int age = 18;
System.out.println(age >= 18); // true

Logical Operators

Used to combine multiple boolean expressions.

Operator Description Example
&& Logical AND true && false → false
|| Logical OR true || false → true
! Logical NOT !true → false

Example:

int age = 20;
boolean hasID = true;

if (age >= 18 && hasID) {
    System.out.println("Entry allowed.");
} else {
    System.out.println("Entry denied.");
}

Assignment Operators

Used to assign values to variables.

Operator Description Example
= Assign x = 5
+= Add and assign x += 2x = x + 2
-= Subtract and assign x -= 3
*= Multiply and assign x *= 4
/= Divide and assign x /= 2
%= Modulus and assign x %= 3

Example:

int score = 50;
score += 10;  // score is now 60
System.out.println(score);

Operator Precedence

Java evaluates expressions using precedence rules, similar to math:

  1. Parentheses () have the highest precedence.
  2. Then come arithmetic operators: *, /, % before +, -.
  3. Comparison operators come after arithmetic.
  4. Then logical operators: && before ||.
  5. Assignment (=, +=, etc.) has the lowest precedence.

Tip: Use parentheses to clarify complex expressions and ensure the correct order of evaluation.

Example 1: Simple Calculator

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double num1 = input.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        char op = input.next().charAt(0);

        System.out.print("Enter second number: ");
        double num2 = input.nextDouble();

        double result;
        if (op == '+') result = num1 + num2;
        else if (op == '-') result = num1 - num2;
        else if (op == '*') result = num1 * num2;
        else if (op == '/') result = num1 / num2;
        else {
            System.out.println("Invalid operator!");
            return;
        }

        System.out.println("Result: " + result);
    }
}

Example 2: Condition Checker

public class ConditionChecker {
    public static void main(String[] args) {
        int score = 85;
        boolean passed = score >= 60;
        boolean hasPerfectAttendance = true;

        if (passed && hasPerfectAttendance) {
            System.out.println("Eligible for reward!");
        } else {
            System.out.println("Not eligible.");
        }
    }
}

Example 3: Combining Expressions

public class ExpressionDemo {
    public static void main(String[] args) {
        int a = 5, b = 10;
        int result = (a + b) * 2; // Parentheses used for precedence
        System.out.println("Result: " + result);
    }
}
Index

2.3 Control Flow: if, else, switch

In Java, conditional statements let your program make decisions and execute specific code depending on whether a condition is true or false. The two main conditional control structures are:

The if Statement

The simplest form checks a condition and runs code if it’s true.

if (condition) {
    // Code runs if condition is true
}

Example: Check if a number is positive

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

        if (num > 0) {
            System.out.println("The number is positive.");
        }
    }
}

if / else Statement

The else block runs if the condition is false.

if (condition) {
    // Runs if true
} else {
    // Runs if false
}

Example: Positive or negative number

public class SignChecker {
    public static void main(String[] args) {
        int num = -3;

        if (num >= 0) {
            System.out.println("The number is non-negative.");
        } else {
            System.out.println("The number is negative.");
        }
    }
}

if, else if, and else

You can chain multiple conditions using else if.

if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if none are true
}

Example: Grade evaluator

public class GradeEvaluator {
    public static void main(String[] args) {
        int score = 76;

        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else if (score >= 60) {
            System.out.println("Grade: D");
        } else {
            System.out.println("Grade: F");
        }
    }
}

This is useful when there are ranges or non-exact values to compare.

Nested if Statements

You can place one if inside another for more specific checks.

int age = 20;
boolean hasID = true;

if (age >= 18) {
    if (hasID) {
        System.out.println("Access granted.");
    } else {
        System.out.println("ID required.");
    }
} else {
    System.out.println("Access denied. Must be 18+.");
}

Nested if is good when one condition depends on another.

The switch Statement

switch is cleaner than multiple if statements when you're checking a variable against specific constant values.

switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
}

Each case is matched against the value. break exits the switch after a match. Without it, execution "falls through" to the next case.

Example: Simple menu system

import java.util.Scanner;

public class MenuSystem {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Menu:");
        System.out.println("1. Say Hello");
        System.out.println("2. Add Numbers");
        System.out.println("3. Exit");
        System.out.print("Choose an option: ");
        int choice = input.nextInt();

        switch (choice) {
            case 1:
                System.out.println("Hello!");
                break;
            case 2:
                System.out.println("5 + 3 = " + (5 + 3));
                break;
            case 3:
                System.out.println("Goodbye!");
                break;
            default:
                System.out.println("Invalid choice.");
        }
    }
}

Choosing Between if and switch

Use if when: Use switch when:
Conditions involve ranges (score >= 90) You're checking one variable for matches
Logic depends on multiple variables Comparing exact values (like menu options)
You need more complex boolean expressions Values are constants (int, char, etc.)

4th Example: Number Sign Checker with else if

public class SignClassifier {
    public static void main(String[] args) {
        int num = 0;

        if (num > 0) {
            System.out.println("Positive");
        } else if (num < 0) {
            System.out.println("Negative");
        } else {
            System.out.println("Zero");
        }
    }
}

Logic Flow Summary

Index

2.4 Looping Constructs: for, while, do-while

In Java, loops allow you to repeat a block of code multiple times based on a condition. This is especially useful when processing collections, validating input, or performing repetitive tasks like displaying menus or calculating values.

Java has three main types of loops:

Let’s explore each with practical examples and learn when to use which.

for Loop

The for loop is used when you know in advance how many times you want to repeat a block.

Syntax:

for (initialization; condition; update) {
    // code to repeat
}

Example: Counting from 1 to 5

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
    }
}

Example: Print a multiplication table

public class MultiplicationTable {
    public static void main(String[] args) {
        int number = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.println(number + " x " + i + " = " + (number * i));
        }
    }
}

Use case: Best for count-controlled loops, like generating tables, repeating steps a fixed number of times, or iterating through arrays.

while Loop

The while loop runs as long as a condition is true. It’s ideal when you don’t know how many times you'll loop, but the condition controls when to stop.

Syntax:

while (condition) {
    // code to repeat
}

Example: Input validation

import java.util.Scanner;

public class InputValidator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int age;

        System.out.print("Enter your age (0–120): ");
        age = input.nextInt();

        while (age < 0 || age > 120) {
            System.out.print("Invalid. Please enter a valid age: ");
            age = input.nextInt();
        }

        System.out.println("Age entered: " + age);
    }
}

Use case: Ideal for condition-controlled loops, like checking for valid input or reading data until a stop condition is met.

do-while Loop

The do-while loop is similar to while, but the block always runs at least once, regardless of the condition.

Syntax:

do {
    // code to repeat
} while (condition);

Example: Menu-driven program

import java.util.Scanner;

public class MenuLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\nMenu:");
            System.out.println("1. Greet");
            System.out.println("2. Show Time");
            System.out.println("3. Exit");
            System.out.print("Choose an option: ");
            choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    System.out.println("Hello!");
                    break;
                case 2:
                    System.out.println("It's Java time!");
                    break;
                case 3:
                    System.out.println("Goodbye!");
                    break;
                default:
                    System.out.println("Invalid option.");
            }

        } while (choice != 3);
    }
}

Use case: Best when you need the loop to run at least once, such as showing menus or retry prompts.

Breaking and Continuing Loops

break Exits the loop immediately:

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    System.out.println(i);
}
// Output: 1 2 3 4

continue Skips the current iteration:

for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}
// Output: 1 2 4 5
Click to view full runnable Code

public class Test {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) break;
            System.out.println(i);
        }
        
        for (int i = 1; i <= 5; i++) {
            if (i == 3) continue;
            System.out.println(i);
        }
    }
}

Visual Output Example: Printing a Triangle Pattern

public class PatternPrinter {
    public static void main(String[] args) {
        int rows = 5;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println(); // Move to the next line
        }
    }
}

Output:

* 
* * 
* * * 
* * * * 
* * * * *

Choosing the Right Loop

Loop Type Best Used When…
for You know how many times to repeat (e.g., count 1–100)
while Repeat until a condition becomes false (e.g., input check)
do-while Run at least once before checking condition (e.g., menu)
Index