Back To Home
Code Newb

Learn Java!

Lesson 1: Java Basics

1.1 Introduction to Java

Java is a powerful, object-oriented programming language widely used in web development, mobile applications (Android), and enterprise systems. It is known for its platform independence and robustness.

1.2 Why Learn Java?

  • Platform Independence: Java programs can run on any device with the Java Virtual Machine (JVM).
  • Object-Oriented: Java is built around objects and classes, making it modular and reusable.
  • Large Community: Extensive libraries and frameworks are available.
  • High Demand: Java is widely used in enterprise applications and Android development.

Writing Your First Java Program

Create a file named HelloWorld.java and write the following code:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compile and run the program:

javac HelloWorld.java
java HelloWorld

This prints Hello, World! to the screen.

1.4 Understanding Variables and Data Types

Variables: A variable stores a value that can change.

String name = "Alice";
int age = 25;
System.out.println(name + " is " + age + " years old.");

Data Types:

  • int: Whole numbers (e.g., 10, -5).
  • double: Decimal numbers (e.g., 3.14, -0.5).
  • String: Text (e.g., "Hello").
  • boolean: true or false.

1.5 Basic Operations

Java supports basic mathematical operations:

int x = 10;
int y = 5;
System.out.println(x + y);  // Addition
System.out.println(x - y);  // Subtraction
System.out.println(x * y);  // Multiplication
System.out.println(x / y);  // Division

1.6 Coding Challenge: Simple Math Calculator

Task: Write a Java program that asks the user for two numbers and prints their sum, difference, product, and quotient.

Example Output:

Enter first number: 8
Enter second number: 2
Sum: 10
Difference: 6
Product: 16
Quotient: 4.0

Use Scanner to get user input:

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        double num1 = scanner.nextDouble();
        System.out.print("Enter second number: ");
        double num2 = scanner.nextDouble();

        System.out.println("Sum: " + (num1 + num2));
        System.out.println("Difference: " + (num1 - num2));
        System.out.println("Product: " + (num1 * num2));
        System.out.println("Quotient: " + (num1 / num2));
    }
}

Lesson 2: Control Flow – Making Decisions in Java

2.1 Conditional Statements (if, else if, else)

Java’s if-else if-else structure allows your program to make decisions based on conditions.

int age = 20;

if (age < 18) {
    System.out.println("You are a minor.");
} else if (age == 18) {
    System.out.println("You just became an adult!");
} else {
    System.out.println("You are an adult.");
}

2.2 Logical Operators

You can combine multiple conditions using && (and), || (or), ! (not).

int x = 5;

if (x > 0 && x < 10) {
    System.out.println("x is between 0 and 10.");
}

2.3 Loops – Repeating Actions

The for Loop

for (int i = 1; i <= 5; i++) {
    System.out.println("Iteration: " + i);
}

The while Loop

int x = 0;
while (x < 5) {
    System.out.println("Value of x: " + x);
    x++;
}

2.4 Loop Control Statements

break: Stops the loop completely.

continue: Skips the current iteration but continues looping.

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println(i);
}

2.5 Coding Challenge: FizzBuzz

Write a program that prints numbers from 1 to 20 but:

Expected Output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...

Mini-Project: Simple Number Guessing Game

Concepts used: if-else, while, break

Steps

  1. Generate a random number.
  2. Prompt the user to guess the number.
  3. Give hints (e.g., "Too high" or "Too low").
  4. Keep looping until they guess correctly.

Lesson 3: Functions & Modular Code

3.1 Defining Functions

Functions help break down a large program into smaller, manageable parts.

Syntax:

public static returnType functionName(parameters) {
    // Code block
    return value;  // (Optional)
}

Example: Simple Greeting Function

public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {
    greet("Alice");  // Output: Hello, Alice!
}

3.2 Parameters & Return Values

Example: Add Two Numbers

public static int addNumbers(int a, int b) {
    return a + b;
}

public static void main(String[] args) {
    int result = addNumbers(5, 10);
    System.out.println(result);  // Output: 15
}

3.3 Function Scope & Variables

Example: Scope Difference

int x = 10;  // Global variable

public static void changeX() {
    int x = 5;  // Local variable
    System.out.println("Inside function: " + x);
}

public static void main(String[] args) {
    changeX();
    System.out.println("Outside function: " + x);  // Output: 10 (global x is unchanged)
}

3.4 Recursion

Example: Factorial Calculation

public static int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

public static void main(String[] args) {
    System.out.println(factorial(5));  // Output: 120
}

3.5 Lambda Functions (Java 8+)

Example: Multiply by 2

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function doubleValue = x -> x * 2;
        System.out.println(doubleValue.apply(5));  // Output: 10
    }
}

3.6 Coding Challenge: Even or Odd Checker

Write a function that:

Expected Output

System.out.println(checkNumber(7));  // Output: Odd
System.out.println(checkNumber(10)); // Output: Even

Mini-Project: Simple Calculator

Concepts used: Functions, loops, user input.

Objective: Create a program where the user can input two numbers and choose an operation (+, -, *, /).

Steps

Lesson 4: Data Structures (Arrays, Lists, Sets, Maps)

4.1 Arrays

An array is a fixed-size collection of elements of the same type.

Creating an Array

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]);  // Output: 1

4.2 Lists (ArrayList)

A List is a dynamic collection that can grow or shrink in size.

Creating a List

import java.util.ArrayList;

ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits.get(0));  // Output: Apple

4.3 Sets (HashSet)

A Set is a collection of unique elements.

Creating a Set

import java.util.HashSet;

HashSet uniqueNumbers = new HashSet<>();
uniqueNumbers.add(1);
uniqueNumbers.add(2);
uniqueNumbers.add(1);  // Duplicate, won't be added
System.out.println(uniqueNumbers);  // Output: [1, 2]

4.4 Maps (HashMap)

A Map stores key-value pairs.

Creating a Map

import java.util.HashMap;

HashMap studentGrades = new HashMap<>();
studentGrades.put("Alice", 90);
studentGrades.put("Bob", 85);
System.out.println(studentGrades.get("Alice"));  // Output: 90

4.5 Coding Challenge: Find Unique Words in a Sentence

Write a function that:

System.out.println(uniqueWords("Hello world hello"));  // Output: [hello, world]

Mini-Project: Student Database (Using Maps)

Concepts used: Lists, maps, user input.

Objective: Create a program to store and retrieve student information.

Steps

  1. Use a Map where each student's name is the key and their grades are the values.
  2. Allow users to:
    • Add new students.
    • Update student grades.
    • Retrieve student information.
  3. Display all student data in a formatted way.

Lesson 5: Object-Oriented Programming (OOP)

5.1 Introduction to Classes and Objects

In Java, everything is an object. A class is a blueprint for creating objects, and an object is an instance of a class.

class Car {
    String brand;
    String model;
    int year;

    Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    void displayInfo() {
        System.out.println(year + " " + brand + " " + model);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", "Camry", 2022);
        myCar.displayInfo();  // Output: 2022 Toyota Camry
    }
}

5.2 Encapsulation (Data Hiding & Protection)

Encapsulation restricts direct access to data, ensuring better security.

class BankAccount {
    private double balance;

    BankAccount(double balance) {
        this.balance = balance;
    }

    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds");
        }
    }

    double getBalance() {
        return balance;
    }
}

5.3 Inheritance (Reusability & Hierarchies)

Inheritance allows a child class to inherit properties and methods from a parent class.

class Vehicle {
    String brand;

    Vehicle(String brand) {
        this.brand = brand;
    }

    void start() {
        System.out.println(brand + " is starting...");
    }
}

class Car extends Vehicle {
    Car(String brand) {
        super(brand);
    }

    void honk() {
        System.out.println("Beep beep!");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota");
        myCar.start();  // Output: Toyota is starting...
        myCar.honk();   // Output: Beep beep!
    }
}

5.4 Polymorphism (Same Interface, Different Behavior)

Polymorphism allows different classes to have methods with the same name but different implementations.

class Animal {
    void speak() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void speak() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    void speak() {
        System.out.println("Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal[] animals = {new Dog(), new Cat()};
        for (Animal animal : animals) {
            animal.speak();
        }
        // Output:
        // Woof!
        // Meow!
    }
}

5.5 Coding Challenge: Employee Management System

Write a class-based program that:

Expected Output:

Employee employee = new Employee("Alice", 30, 50000);
employee.displayInfo();
// Output: Name: Alice, Age: 30, Salary: $50000

Mini-Project: Library Management System (Using OOP)

Objective: Create a simple Library System that allows users to borrow and return books.

Steps:

  1. Define a Book class with attributes like title and author.
  2. Create a Library class with methods to:
    • Add books to the collection.
    • Display available books.
    • Allow users to borrow and return books.

Lesson 6: File Handling in Java

6.1 Reading from a File

Java provides the FileReader and BufferedReader classes to read from files.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.2 Writing to a File

Java provides the FileWriter and BufferedWriter classes to write to files.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
            bw.write("Hello, this is a new file!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.3 Working with CSV Files

Java does not have built-in CSV support, but you can use libraries like OpenCSV or manually parse CSV files.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("data.csv"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                System.out.println("Name: " + values[0] + ", Age: " + values[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.4 Coding Challenge: Word Counter

Write a program that:

Expected Output

Enter filename: example.txt
Total words: 42

Mini-Project: To-Do List (File-Based Storage)

Objective: Build a simple to-do list that allows users to add tasks, view tasks, and remove tasks, storing them in a file.

Steps

  1. Create a text file (tasks.txt) to store tasks.
  2. Implement functions to:
    • Add a new task.
    • View all tasks.
    • Remove a completed task.
  3. Save changes to the file after every action.

Lesson 7: Exception Handling in Java

7.1 Understanding Errors in Java

Java encounters two main types of errors:

  • Compile-Time Errors – Mistakes in the code structure.
  • System.out.println("Hello)  // SyntaxError: Missing closing quote
  • Runtime Errors (Exceptions) – Errors that occur while the program runs.
  • int x = 10 / 0;  // ArithmeticException

Key Takeaways:

  • Compile-Time Errors prevent the code from running.
  • Exceptions happen during execution and can be handled.

7.2 Handling Exceptions with `try-catch`

The `try-catch` block prevents the program from crashing.

try {
    int num = Integer.parseInt("abc");  // NumberFormatException
    System.out.println("You entered: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid input! Please enter a number.");
}

7.3 Handling Multiple Exceptions

We can catch multiple exceptions to handle different errors.

try {
    int num = Integer.parseInt("10");
    int result = 10 / num;  // Might cause ArithmeticException
    System.out.println("Result: " + result);
} catch (NumberFormatException e) {
    System.out.println("Invalid input! Please enter a number.");
} catch (ArithmeticException e) {
    System.out.println("You can't divide by zero!");
}

7.4 Using `finally` to Run Cleanup Code

The `finally` block always executes, whether an exception occurs or not.

try {
    FileReader file = new FileReader("data.txt");
    // Read file content
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
} finally {
    System.out.println("File closed.");
}

7.5 Throwing Custom Exceptions

We can manually trigger exceptions using `throw`.

public class Main {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("You must be 18 or older!");
        }
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

7.6 Coding Challenge: Safe Division

Write a function `safeDivide(a, b)` that:

Expected Output:

System.out.println(safeDivide(10, 2));  // Output: 5.0
System.out.println(safeDivide(5, 0));   // Output: Cannot divide by zero

Mini-Project: Password Validator

Concepts used: Exception handling, string manipulation, user input.

Objective: Build a password validator that:

Lesson 8: Advanced Java Concepts

8.1 Generics

Generics allow you to write classes, interfaces, and methods that work with any data type.

class Box {
    private T item;

    void setItem(T item) {
        this.item = item;
    }

    T getItem() {
        return item;
    }
}

public class Main {
    public static void main(String[] args) {
        Box stringBox = new Box<>();
        stringBox.setItem("Hello");
        System.out.println(stringBox.getItem());  // Output: Hello
    }
}

8.2 Multithreading

Java supports multithreading, allowing you to run multiple threads concurrently.

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

8.3 Streams and Lambda Expressions

Java 8 introduced streams and lambda expressions for functional programming.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List names = Arrays.asList("Alice", "Bob", "Charlie");
        names.stream()
             .filter(name -> name.startsWith("A"))
             .forEach(System.out::println);  // Output: Alice
    }
}

8.4 Coding Challenge: Find Maximum Number

Write a generic method that:

Expected Output

List numbers = Arrays.asList(1, 5, 3, 9, 2);
System.out.println(findMax(numbers));  // Output: 9

Mini-Project: Multithreaded File Downloader

Objective: Create a program that downloads multiple files concurrently using multithreading.

Steps

  1. Define a DownloadTask class that implements Runnable.
  2. Create multiple threads to download files concurrently.
  3. Display the progress of each download.

Lesson 9: Java Collections Framework

9.1 List Interface

The List interface represents an ordered collection of elements.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        System.out.println(fruits.get(0));  // Output: Apple
    }
}

9.2 Set Interface

The Set interface represents a collection of unique elements.

import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set uniqueNumbers = new HashSet<>();
        uniqueNumbers.add(1);
        uniqueNumbers.add(2);
        uniqueNumbers.add(1);  // Duplicate, won't be added
        System.out.println(uniqueNumbers);  // Output: [1, 2]
    }
}

9.3 Map Interface

The Map interface represents a collection of key-value pairs.

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map studentGrades = new HashMap<>();
        studentGrades.put("Alice", 90);
        studentGrades.put("Bob", 85);
        System.out.println(studentGrades.get("Alice"));  // Output: 90
    }
}

9.4 Coding Challenge: Find Duplicates in a List

Write a function that:

Expected Output

List numbers = Arrays.asList(1, 2, 3, 2, 4, 3);
System.out.println(findDuplicates(numbers));  // Output: [2, 3]

Mini-Project: Student Grade Tracker

Objective: Create a program that tracks student grades using the Map interface.

Steps

  1. Use a Map to store student names as keys and their grades as values.
  2. Allow users to:
    • Add new students.
    • Update student grades.
    • Retrieve student information.
  3. Display all student data in a formatted way.

Lesson 10: Java Networking

10.1 Socket Programming

Java provides the Socket and ServerSocket classes for network communication.

Server Example

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(1234);
        System.out.println("Server is listening on port 1234...");

        Socket socket = serverSocket.accept();
        System.out.println("Client connected");

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message = in.readLine();
        System.out.println("Client says: " + message);

        socket.close();
        serverSocket.close();
    }
}

Client Example

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 1234);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hello, Server!");
        socket.close();
    }
}

10.2 HTTP Requests with HttpURLConnection

Java provides the HttpURLConnection class to send HTTP requests.

import java.io.*;
import java.net.*;

public class Main {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();

        System.out.println(content.toString());
    }
}

10.3 Coding Challenge: Simple Chat Application

Write a simple chat application that:

Mini-Project: Weather App (Using HTTP Requests)

Objective: Create a program that fetches weather data from an API and displays it to the user.

Steps

  1. Use HttpURLConnection to send a GET request to a weather API.
  2. Parse the JSON response to extract weather data.
  3. Display the weather information in a user-friendly format.