Learn Java Programming

Java is a powerful, versatile, and platform-independent programming language widely used for building robust applications β€” from mobile apps to enterprise software.

Start Learning

πŸ“˜ Introduction to Java

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It was developed by James Gosling at Sun Microsystems and released in 1995.

Java is widely used in building web applications, desktop apps, Android apps, enterprise solutions, and more. It is known for its philosophy: "Write Once, Run Anywhere" β€” meaning compiled Java code can run on all platforms that support Java without recompilation.

πŸ’‘ Key Features of Java:
  • Object-Oriented: Everything in Java is an object that models real-world entities.
  • Platform Independent: Java programs run on any device with a JVM (Java Virtual Machine).
  • Simple and Familiar: Easy to learn for those with prior programming experience in C or C++.
  • Secure: Java provides features for secure app development and sandboxed execution.
  • Robust: Java handles errors efficiently with strong memory management and exception handling.
  • Multithreaded: Java can handle multiple tasks simultaneously through multithreading.
  • Rich API & Community Support: A vast set of libraries, tools, and global developer community.
πŸ“¦ Common Uses of Java:
  • Android App Development
  • Web Applications (via frameworks like Spring)
  • Enterprise Solutions (Banking, E-Commerce)
  • Game Development (with libraries like LibGDX)
  • Big Data and Distributed Systems (e.g., Apache Hadoop)
  • Scientific Computing and Machine Learning (limited use, but possible)
βš™οΈ Tools You'll Need to Get Started:
  • JDK (Java Development Kit): Contains tools to compile, run, and debug Java programs.
  • IDE: Use IDEs like IntelliJ IDEA, Eclipse, or VS Code with Java extensions.
  • Text Editor: Alternatively, use simple editors like Notepad++ or Sublime for quick scripting.
πŸ”§ Tip: Start by writing small programs like printing messages or performing calculations. Understanding the syntax and structure is the first step toward mastery.

πŸ”€ Basic Syntax in Java

Understanding the basic syntax of Java is the foundation for writing your first program. Java has a structured and consistent syntax that is case-sensitive, requires semicolons at the end of statements, and follows specific naming conventions.

βœ… Java Program Structure:
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, world!");
  }
}
  • Class: Every Java program must have at least one class. In this case, it's HelloWorld.
  • main Method: This is the entry point. The JVM looks for this method to run your code.
  • System.out.println(): Used to print output to the console.
πŸ“Œ Important Syntax Rules:
  • Java is case-sensitive: Main and main are different.
  • Statements end with a semicolon (;).
  • Blocks of code are enclosed in curly braces { }.
  • File name must match the public class name (e.g., HelloWorld.java).
πŸ“¦ Java Identifiers:
  • Can include letters, digits, underscores (_) and dollar signs ($).
  • Must start with a letter, underscore, or dollar sign (not a digit).
  • Should not use Java reserved keywords (like int, class, public).
πŸ›‘ Java Comments:
  • // Single-line comment
  • /* Multi-line comment */
  • /** Documentation comment */ (used for JavaDoc)
πŸ’‘ Naming Conventions:
  • Classes: PascalCase (e.g., StudentInfo)
  • Methods/Variables: camelCase (e.g., calculateTotal)
  • Constants: ALL_UPPERCASE (e.g., PI_VALUE)
πŸ’‘ Tip: Practice writing simple Java programs to reinforce the syntax β€” like printing your name, adding two numbers, or displaying patterns.

πŸ”’ Data Types in Java

Java is a strongly typed language, meaning each variable must be declared with a data type. Data types specify the kind of value a variable can hold and how much memory it uses.

πŸ“¦ Two Main Categories:
  • Primitive Data Types: Basic built-in types.
  • Non-Primitive (Reference) Data Types: Objects and arrays.

πŸ“˜ Primitive Data Types

Type Description Size Example
byte Stores whole numbers from -128 to 127 1 byte byte age = 25;
short Stores whole numbers from -32,768 to 32,767 2 bytes short temp = 1000;
int Stores whole numbers from -2B to 2B 4 bytes int salary = 50000;
long Larger whole numbers 8 bytes long distance = 123456789L;
float Single-precision decimal 4 bytes float price = 99.99f;
double Double-precision decimal 8 bytes double gpa = 8.56;
char Single character 2 bytes char grade = 'A';
boolean True or false 1 bit boolean isJavaFun = true;

🧱 Non-Primitive Data Types

  • String: Sequence of characters β€” String name = "Java";
  • Arrays: Used to store multiple values of the same type β€” int[] numbers = {1, 2, 3};
  • Objects: Instances of classes β€” Car myCar = new Car();
πŸ”„ Type Conversion:
  • Widening (Automatic): e.g., int β†’ long β†’ float β†’ double
  • Narrowing (Manual): Requires casting β€” double β†’ float β†’ int β†’ byte
int a = 10;
double b = a; // Widening

double x = 9.8;
int y = (int)x; // Narrowing (cast required)
πŸ’‘ Tip: Always choose the most appropriate data type for efficiency and clarity.

Variables & Operators

πŸ”Ή What is a Variable?

A variable is a name given to a memory location where data can be stored and modified during program execution. In Java, variables must be declared with a specific data type.

Example:

int age = 25;
String name = "John";
double price = 19.99;

πŸ“Œ Types of Variables in Java:

  • Local Variable – Declared inside methods or blocks.
  • Instance Variable – Non-static variable declared inside a class but outside methods.
  • Static Variable – Declared with static keyword; shared across all objects.

πŸ”Ή What are Operators?

Operators are special symbols that perform operations on variables and values.

1. Arithmetic Operators
+   Addition
-   Subtraction
*   Multiplication
/   Division
%   Modulus (Remainder)

Example: int sum = 5 + 3; β†’ sum is 8

2. Assignment Operators
=   Assign
+=  Add and assign
-=  Subtract and assign
*=  Multiply and assign
/=  Divide and assign
%=  Modulus and assign

Example: count += 5; β†’ count = count + 5

3. Relational (Comparison) Operators
==  Equal to
!=  Not equal to
>   Greater than
<   Less than
>=  Greater than or equal to
<=  Less than or equal to
4. Logical Operators
&&  Logical AND
||  Logical OR
!   Logical NOT

Used in decision making (e.g., if conditions).

5. Unary Operators
+   Unary plus (positive value)
-   Unary minus (negative value)
++  Increment
--  Decrement
!   Logical complement
6. Ternary Operator

condition ? value_if_true : value_if_false

Example: int result = (a > b) ? a : b;


βœ… Practice Task:

Write a Java program that takes two numbers, performs all arithmetic operations, and prints the results.

πŸ› οΈ Recommended Tools:

Methods in Java

πŸ”Ή What is a Method?

A method in Java is a block of code that performs a specific task. It helps make your code reusable, organized, and easier to debug.

Syntax:

returnType methodName(parameters) {
    // Code block
}

Example:

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

πŸ”§ Why Use Methods?
  • Reuse code multiple times
  • Make programs easier to read
  • Divide complex problems into smaller parts
  • Improve debugging and testing
πŸ“š Types of Methods

1. Predefined (Built-in) Methods

Provided by Java (e.g., System.out.println(), Math.max())

2. User-Defined Methods

Created by the programmer to perform custom tasks

πŸ“Œ Method Components:
  • Method Name: Identifies the method (e.g., addNumbers)
  • Return Type: What the method returns (e.g., int, void)
  • Parameters: Inputs (optional)
  • Method Body: Code to be executed
πŸ“Œ The main() Method:

This is the entry point of every Java application.

public static void main(String[] args) {
  // Code here runs first
}
πŸ“Œ Calling a Method

Once defined, a method can be called like this:

int result = add(10, 20);
πŸ§ͺ Example:
public class Calculator {

  // User-defined method
  static int multiply(int a, int b) {
    return a * b;
  }

  public static void main(String[] args) {
    int result = multiply(4, 5);
    System.out.println("Result: " + result);
  }
}
βœ… Practice Task:

Create methods to:

  • Calculate the square of a number
  • Convert temperature from Celsius to Fahrenheit
  • Check if a number is even or odd

Control Flow

Control flow statements allow you to dictate the order in which your program’s code executes based on conditions and repetition. These are essential for making decisions and performing tasks multiple times.

  • Conditional Statements: Used to execute code blocks based on specified conditions.
    • if – executes code if a condition is true.
    • else if – checks another condition if the previous if was false.
    • else – executes code if all previous conditions are false.
  • Loops: Used to repeat code while a condition is true.
    • for loop – repeats code a specific number of times.
    • while loop – repeats code while a condition remains true.
    • do-while loop – similar to while but executes the code block at least once before checking the condition.

Example of a for loop that prints numbers from 0 to 4:

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

Explanation:

  • int i = 0; initializes the loop variable i to 0.
  • i < 5; is the loop continuation condition (loop runs while true).
  • i++ increments i by 1 after each iteration.
  • System.out.println(i); outputs the current value of i to the console.

Loops in Java

πŸ” What is a Loop?

Loops are used to execute a block of code repeatedly until a specific condition is met. They help you avoid repeating code manually.


πŸ“Œ Types of Loops in Java

1️⃣ for Loop

Used when you know how many times to run the loop.

for (int i = 1; i <= 5; i++) {
  System.out.println("Count: " + i);
}
2️⃣ while Loop

Executes as long as the condition is true. Ideal for unknown number of iterations.

int i = 1;
while (i <= 5) {
  System.out.println("Count: " + i);
  i++;
}
3️⃣ do-while Loop

Runs at least once before checking the condition.

int i = 1;
do {
  System.out.println("Count: " + i);
  i++;
} while (i <= 5);
4️⃣ for-each Loop (Enhanced for Loop)

Best for iterating over arrays or collections.

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

🚨 Loop Control Statements

  • break – Exit the loop early
  • continue – Skip the current iteration
// Example using break
for (int i = 1; i <= 10; i++) {
  if (i == 5) break;
  System.out.println(i);
}

// Example using continue
for (int i = 1; i <= 5; i++) {
  if (i == 3) continue;
  System.out.println(i);
}

βœ… Practice Tasks:

  • Print numbers from 1 to 100
  • Display even numbers between 1 and 50
  • Calculate the sum of numbers from 1 to 10
  • Use a for-each loop to display elements of an array

Object-Oriented Programming (OOP)

Java is an object-oriented programming language, meaning everything in Java is associated with objects and classes. OOP allows for cleaner, reusable, and modular code.

🌟 Key OOP Principles in Java:

  • 1. Classes and Objects: Classes are blueprints; objects are instances of those classes.
  • 2. Encapsulation: Wrapping data (variables) and code (methods) together as a single unit and hiding internal details from outside access.
  • 3. Inheritance: One class can inherit fields and methods from another (parent-child relationship).
  • 4. Polymorphism: The ability of one function or method to behave differently based on the object that calls it.
  • 5. Abstraction: Hiding complex implementation details and showing only the essential features of the object.

πŸš— Example:

public class Car {
  private String brand;  // Encapsulation

  // Constructor
  public Car(String brand) {
    this.brand = brand;
  }

  // Method
  public void drive() {
    System.out.println(brand + " is driving.");
  }
}
public class ElectricCar extends Car {  // Inheritance
  public ElectricCar(String brand) {
    super(brand);
  }

  @Override
  public void drive() {  // Polymorphism (method overriding)
    System.out.println("Electric " + getBrand() + " is silently driving.");
  }
}

🧠 Explanation:

  • Car is a class with a private field and a method.
  • ElectricCar extends Car, inheriting and overriding the drive() method.
  • We use constructor chaining with super().

πŸ’‘ Real-Life Analogy:

Think of a class as a "blueprint" of a house. You can build many houses (objects) using that one blueprint (class). Each house can have its own wall colors, doors, and furniture, but they’re all based on the same design.

πŸ§ͺ Practice Tasks:

  • Create a Person class with name and age. Add a method to display the info.
  • Extend it to a Student class with additional fields like roll number and grade.
  • Override a method to display student-specific info using polymorphism.

Classes & Objects in Java

πŸ—οΈ What is a Class?

A class is a blueprint for creating objects. It defines properties (variables) and behaviors (methods).

πŸ“¦ What is an Object?

An object is an instance of a class. It represents a specific entity with actual values assigned to class properties.


πŸ“Œ Declaring a Class

public class Car {
  // Properties (Attributes)
  String brand;
  int year;

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

πŸš— Creating an Object

public class Main {
  public static void main(String[] args) {
    Car myCar = new Car(); // Create object
    myCar.brand = "Toyota";
    myCar.year = 2023;

    System.out.println(myCar.brand + " " + myCar.year);
    myCar.honk(); // Call method
  }
}

πŸ› οΈ Constructors

A constructor is a special method used to initialize objects.

public class Car {
  String brand;
  int year;

  // Constructor
  Car(String b, int y) {
    brand = b;
    year = y;
  }

  void display() {
    System.out.println(brand + " " + year);
  }
}
public class Main {
  public static void main(String[] args) {
    Car c1 = new Car("Honda", 2022);
    c1.display();
  }
}

🧠 Practice Tasks:

  • Create a class called Student with name, age, and roll number. Create objects and display data.
  • Build a class Calculator with methods: add(), subtract(), multiply(), divide().
  • Write a Book class and create multiple book objects with different titles and authors.

Inheritance & Interfaces

🧬 What is Inheritance?

Inheritance is a core concept in Object-Oriented Programming. It allows a class (child or subclass) to inherit fields and methods from another class (parent or superclass). This promotes reusability and reduces code duplication.

πŸ“˜ Example:

class Animal {
  void makeSound() {
    System.out.println("Some sound...");
  }
}

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

public class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.makeSound(); // Inherited method
    d.bark();      // Dog-specific method
  }
}
πŸ‘¨β€πŸ‘§β€πŸ‘¦ Types of Inheritance in Java:
  • Single Inheritance (one parent, one child)
  • Multilevel Inheritance (inheritance of inherited class)
  • Hierarchical Inheritance (multiple classes inherit from one)

Note: Java does not support multiple inheritance through classes to avoid ambiguity.


πŸ”Œ What is an Interface?

An interface is a collection of abstract methods. It defines a contract that other classes must follow. A class implements an interface and provides method definitions.

πŸ“˜ Interface Example:

interface Animal {
  void makeSound();  // Abstract method
}

class Cat implements Animal {
  public void makeSound() {
    System.out.println("Meow!");
  }
}

public class Main {
  public static void main(String[] args) {
    Cat c = new Cat();
    c.makeSound(); // Output: Meow!
  }
}
πŸ“ Interface Key Points:
  • Interfaces contain only method signatures (no body)
  • All methods are implicitly public and abstract
  • A class can implement multiple interfaces
  • Used to achieve multiple inheritance

πŸ’‘ Practice Tasks:

  • Create a Vehicle class and let Car and Bike inherit from it.
  • Create an interface called Drawable with a draw() method, and implement it in Circle and Rectangle classes.
  • Use multilevel inheritance by creating a Person β†’ Employee β†’ Manager hierarchy.

Arrays & Strings

🧩 Arrays in Java

An array is a collection of elements stored in a single variable, accessible by index. All elements in an array must be of the same data type.

πŸ“˜ Array Example:

int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < numbers.length; i++) {
  System.out.println(numbers[i]);
}
πŸ”‘ Key Points:
  • Fixed size once declared
  • Index starts from 0
  • Can store primitive or object references
πŸ› οΈ Declaring Arrays:
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
πŸ‘©β€πŸ’» Enhanced For Loop:
for (int num : numbers) {
  System.out.println(num);
}

πŸ”€ Strings in Java

Strings in Java are objects that represent sequences of characters. They are immutable (cannot be changed once created).

πŸ“˜ String Example:

String greeting = "Hello, World!";
System.out.println(greeting.length());
System.out.println(greeting.toUpperCase());
✨ Common String Methods:
  • length() – Get string length
  • toUpperCase() / toLowerCase() – Change case
  • charAt(index) – Get character at a position
  • substring(start, end) – Extract part of a string
  • equals() – Compare two strings for equality
  • contains() – Check if string contains another string
  • replace() – Replace characters or substrings
  • trim() – Remove leading/trailing spaces

πŸ’‘ Practice Tasks:

  • Store 5 student scores in an array and find the average.
  • Reverse a string manually using a loop.
  • Check if a word is a palindrome using string methods.
  • Count vowels in a string entered by the user.

Exception Handling

In Java, exceptions are events that occur during the execution of a program that disrupt its normal flow. Exception handling is a powerful mechanism to handle runtime errors so that the program can continue execution.

⚠️ What Is an Exception?

An exception is an object that represents an error or unexpected behavior. For example, trying to divide a number by zero or accessing an invalid array index.

int x = 5 / 0; // This throws ArithmeticException

πŸ“¦ Types of Exceptions

  • Checked Exceptions: Must be handled at compile time (e.g., FileNotFoundException).
  • Unchecked Exceptions: Occur at runtime (e.g., NullPointerException, ArithmeticException).

πŸ› οΈ Try-Catch Block

You use a try block to write risky code and catch block to handle the exception.

try {
  int result = 10 / 0;
  System.out.println(result);
} catch (ArithmeticException e) {
  System.out.println("Error: Division by zero is not allowed.");
}

πŸ” Finally Block

The finally block always executes, whether an exception is thrown or not. It is used to clean up resources (like closing files or connections).

try {
  int[] arr = {1, 2, 3};
  System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println("Invalid array index!");
} finally {
  System.out.println("Always executed.");
}

🚨 Throwing Exceptions

You can manually throw exceptions using the throw keyword.

public void checkAge(int age) {
  if (age < 18) {
    throw new IllegalArgumentException("You must be 18+");
  }
}

πŸ“ Throws Keyword

If a method may throw a checked exception, you must declare it using throws.

public void readFile(String file) throws IOException {
  // file reading logic
}

πŸ’‘ Best Practices

  • Catch specific exceptions, not generic Exception.
  • Use finally for resource cleanup.
  • Log exceptions instead of just printing them.
  • Do not suppress exceptions silently.

βœ… Practice Tasks

  • Handle division by zero using try-catch.
  • Write a program that throws an exception if a user enters a negative number for age.
  • Create a method that reads a file and uses throws to handle exceptions.

πŸ“ File Handling in Java

File handling in Java allows programs to read, write, update, and delete files stored on the computer. The java.io and java.nio.file packages provide built-in classes for working with files.

✍️ Common Tasks:

  • Creating a new file
  • Writing to a file
  • Reading from a file
  • Deleting a file

πŸ“„ Example: Create and Write to a File

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

public class WriteFile {
  public static void main(String[] args) {
    try {
      FileWriter writer = new FileWriter("example.txt");
      writer.write("Hello, this is a file write example!");
      writer.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

πŸ“– Example: Read from a File

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
  public static void main(String[] args) {
    try {
      File file = new File("example.txt");
      Scanner reader = new Scanner(file);
      while (reader.hasNextLine()) {
        String line = reader.nextLine();
        System.out.println(line);
      }
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("File not found.");
      e.printStackTrace();
    }
  }
}

πŸ—‘οΈ Example: Delete a File

import java.io.File;

public class DeleteFile {
  public static void main(String[] args) {
    File file = new File("example.txt");
    if (file.delete()) {
      System.out.println("Deleted: " + file.getName());
    } else {
      System.out.println("Failed to delete the file.");
    }
  }
}

🧠 Tips:

  • Always close your file after reading or writing to avoid memory leaks.
  • Use try-catch to handle exceptions safely.
  • Use BufferedReader or Files.readAllLines() for large files or more efficient reading.

πŸ§ͺ Practice:

  • Create a text file and write user input into it.
  • Read the file content line by line and display it.
  • Delete the file after reading, with confirmation.

πŸ“š Java Collections Framework

The Collections Framework in Java provides a set of classes and interfaces to store and manipulate groups of data efficiently. These data structures include lists, sets, queues, and maps.

πŸ”‘ Key Interfaces:

  • List – Ordered collection (e.g., ArrayList, LinkedList)
  • Set – No duplicate elements (e.g., HashSet, TreeSet)
  • Queue – FIFO data structure (e.g., LinkedList, PriorityQueue)
  • Map – Key-value pairs (e.g., HashMap, TreeMap)

πŸ“˜ Example: Using ArrayList

import java.util.ArrayList;

public class Example {
  public static void main(String[] args) {
    ArrayList fruits = new ArrayList<>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");

    for (String fruit : fruits) {
      System.out.println(fruit);
    }
  }
}

πŸ“˜ Example: Using HashMap

import java.util.HashMap;

public class HashMapExample {
  public static void main(String[] args) {
    HashMap scores = new HashMap<>();
    scores.put("Alice", 90);
    scores.put("Bob", 85);

    System.out.println("Alice's score: " + scores.get("Alice"));
  }
}

🧠 Common Implementations:

Interface Implementation Features
List ArrayList Resizable array, fast random access
List LinkedList Fast insertion/deletion, slower access
Set HashSet No duplicates, unordered
Map HashMap Key-value pairs, fast access
Queue PriorityQueue Elements sorted by priority

πŸ› οΈ Utility Methods:

  • Collections.sort(list) – Sort a list
  • Collections.reverse(list) – Reverse a list
  • Collections.shuffle(list) – Shuffle elements
  • Collections.max()/min() – Find max or min

πŸ§ͺ Practice Ideas:

  • Store student names and grades in a HashMap
  • Sort a list of numbers in descending order
  • Create a to-do list using ArrayList
  • Track unique email addresses using HashSet

πŸ“¦ Packages & Access Modifiers

Java organizes classes into packages to avoid name conflicts and to control access. Packages also help manage large codebases by grouping related classes together.

πŸ“¦ What is a Package?

  • A package is a namespace for classes and interfaces.
  • Java provides built-in packages like java.util, java.io, etc.
  • You can also create your own custom packages.
Creating a Package:
// File: MyClass.java
package mypackage;

public class MyClass {
  public void greet() {
    System.out.println("Hello from mypackage!");
  }
}
Using a Package:
import mypackage.MyClass;

public class Main {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    obj.greet();
  }
}

πŸ” Access Modifiers

Access modifiers define the scope of visibility for classes, variables, methods, and constructors.

Modifier Class Package Subclass World
public βœ… βœ… βœ… βœ…
protected βœ… βœ… βœ… ❌
default (no modifier) βœ… βœ… ❌ ❌
private βœ… ❌ ❌ ❌
Quick Notes:
  • public: Accessible from anywhere.
  • private: Accessible only within the declared class.
  • protected: Accessible within the same package and subclasses.
  • default: Accessible within the same package only.
πŸ” Best Practices:
  • Group related classes in the same package.
  • Use private for internal fields and methods to enforce encapsulation.
  • Use public APIs thoughtfully and keep internal logic hidden.
πŸ§ͺ Practice Idea:

Create a package shapes and define multiple shape classes inside it like Circle, Rectangle, and test their usage from another class.

🧡 Multithreading Basics

Multithreading in Java is a feature that allows concurrent execution of two or more threads. A thread is a lightweight subprocess, and Java supports multithreading by default to enable better CPU utilization and faster program execution.

🧠 Why Use Multithreading?

  • To perform multiple tasks simultaneously (e.g., downloading & playing media).
  • Improves application performance on multicore systems.
  • Essential for building responsive and real-time applications.

πŸ“Œ Creating Threads in Java

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

public class TestThread {
  public static void main(String[] args) {
    MyThread t1 = new MyThread();
    t1.start(); // Starts the thread
  }
}
2. By Implementing Runnable interface:
class MyRunnable implements Runnable {
  public void run() {
    System.out.println("Runnable thread running...");
  }
}

public class TestRunnable {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable());
    t1.start();
  }
}

βš™οΈ Common Thread Methods

  • start(): Begins thread execution.
  • run(): Defines the code that runs in the thread.
  • sleep(milliseconds): Pauses execution for specified time.
  • join(): Waits for a thread to die.
  • isAlive(): Checks if a thread is still running.

🚦 Thread States

  • New: Thread is created but not started.
  • Runnable: Thread is ready to run but waiting for CPU.
  • Running: Thread is currently executing.
  • Blocked/Waiting: Waiting for resources or signal.
  • Terminated: Thread has completed or been stopped.

πŸ”’ Thread Safety & Synchronization

When multiple threads try to access shared resources, data inconsistency can occur. Java provides:

  • synchronized methods or blocks to prevent race conditions.
  • Atomic classes (e.g., AtomicInteger) from java.util.concurrent.atomic.

πŸ’‘ Best Practices

  • Keep thread tasks small and focused.
  • Avoid unnecessary thread creation; reuse threads when possible.
  • Use thread pools (Executors) for scalable apps.
πŸ§ͺ Practice Task:

Write a program that creates two threads. One thread prints numbers from 1–5, and the other prints letters A–E. Observe how they run concurrently.

βš™οΈ JVM & Compilation Process

Understanding how Java code is compiled and executed is crucial for mastering the language. Java programs go through several steps from writing to execution. Let’s break it down:

🧾 1. Write the Code

Java code is written in .java files using a text editor or IDE.

πŸ” 2. Compilation

Java source code is compiled using the javac compiler, which converts .java files into .class files containing bytecode.

javac HelloWorld.java

Output: HelloWorld.class

πŸš€ 3. Execution (via JVM)

The Java Virtual Machine (JVM) is responsible for running the compiled bytecode. It reads .class files and interprets or compiles them into machine code for the host OS.

java HelloWorld

πŸ“¦ What is the JVM?

  • JVM (Java Virtual Machine) is an engine that provides a runtime environment to run Java applications.
  • It makes Java platform-independent by converting bytecode to machine-specific code.
  • JVM includes components like the class loader, bytecode verifier, garbage collector, and execution engine.

πŸ“š JVM vs JRE vs JDK

Component Description
JVM Runs Java bytecode (.class files); platform-specific.
JRE (Java Runtime Environment) Includes JVM + libraries required to run Java apps.
JDK (Java Development Kit) Includes JRE + development tools like compiler (javac), debugger, etc.

🧠 Key JVM Features

  • Automatic Garbage Collection: Frees unused memory.
  • Security Manager: Controls access to resources.
  • Class Loader: Loads classes dynamically as needed.
  • Just-In-Time (JIT) Compiler: Converts bytecode to native code for performance.
πŸ§ͺ Practice Task:

Compile and run a simple Java program. Explore the .class file generated and try running it using java command. Observe memory usage with the -Xmx and -Xms options.

πŸ› οΈ Practice Projects

Applying your knowledge through hands-on coding projects is the best way to solidify your Java skills. Here are some beginner to intermediate project ideas to help you practice:

πŸ“˜ Beginner Projects

  • 1. Simple Calculator: Build a CLI calculator that performs addition, subtraction, multiplication, and division using methods.
  • 2. Number Guessing Game: Create a game where the user guesses a number between 1–100. Provide hints like "too high" or "too low."
  • 3. Student Grade System: Input student scores, calculate average and assign grades using if-else and loops.
  • 4. To-Do List App (Console): Add, remove, and list tasks using ArrayList.
  • 5. Banking System: Simulate deposit, withdraw, and balance checking using object-oriented principles.

πŸ“™ Intermediate Projects

  • 6. Library Management System: Create classes for books, users, and manage borrowing/returning features.
  • 7. Tic-Tac-Toe Game: Build a 2-player console-based Tic-Tac-Toe game with input validation and win logic.
  • 8. File-based Contact Book: Allow users to save, read, and delete contacts stored in a file.
  • 9. Quiz App: Show questions, take input, and calculate final scores using arrays or collections.
  • 10. Expense Tracker: Track expenses by date, category, and amount using object-oriented design and array lists.

πŸ§ͺ Bonus Challenge

Build a small Java Address Book GUI app using Swing that allows the user to add, update, and delete contacts. Use file handling or serialization to store the data.

πŸ’‘ Tips:
  • Start with basic console projects before jumping into GUI.
  • Break big problems into small parts (classes & methods).
  • Document your code and keep backups.
  • Try to reuse and refactor your code for better structure.

Ready to build? Pick a project, start coding, and share your progress!

πŸ—ΊοΈ Java Learning Roadmap

Follow this structured roadmap to master Java programming step-by-step. This path is designed for beginners aiming to become confident Java developers, with a smooth transition from fundamentals to real-world application.

🧩 Phase 1: Java Fundamentals

  • Introduction to Java & Installation
  • Basic Syntax and Structure
  • Data Types and Variables
  • Operators and Expressions
  • Control Flow (if-else, switch, loops)
  • Methods (Functions)

βš™οΈ Phase 2: Object-Oriented Programming (OOP)

  • Classes & Objects
  • Constructors
  • Inheritance
  • Polymorphism (Overloading & Overriding)
  • Encapsulation and Abstraction
  • Interfaces

🧠 Phase 3: Intermediate Java Concepts

  • Arrays & ArrayLists
  • Strings and StringBuilder
  • Exception Handling
  • File I/O
  • Packages & Access Modifiers
  • Multithreading Basics
  • JVM, JRE, and Compilation Process

πŸ“¦ Phase 4: Java Collections & Utilities

  • Collections Framework (List, Set, Map)
  • Wrapper Classes & Autoboxing
  • Generics
  • Iterators and Enhanced For Loop

πŸ’» Phase 5: Project Development & Practice

  • Console-based Java Projects
  • File-based Data Storage
  • Mini Projects like Quiz App, ATM, etc.
  • Basic GUI (Java Swing)

πŸš€ Phase 6: What's Next?

  • Learn JavaFX for modern UI
  • Explore JDBC (Database connection)
  • Try Spring Boot for Web APIs
  • Build RESTful web services
  • Explore Android Development or Competitive Programming with Java

This roadmap is flexible β€” adapt it to your goals and pace. The more you build and experiment, the faster you'll grow!

Test Your Java Knowledge

Type a simple Java statement like int x = 5; or public class Main { } to check if the syntax is correct.