Navigation

Java Full Course: Mastering the Language
A complete guide to Java programming from basics to advanced concepts.
Java Full Course: Mastering the Language Programming Fundamentals & Java Architecture
Programming Fundamentals & Java Architecture
(Complete Notes | Beginner to Advanced | Professional & Exam-Oriented | SEO-Optimized)
This module is designed for:
- Students searching what is programming and introduction to Java
- Learners looking for Java architecture explained and JDK vs JRE vs JVM
- Users searching Java compilation process and what is bytecode in Java
- Candidates preparing for competitive computer science exams (BCA, MCA, GATE, UGC NET)
- Beginners starting their first Java programming course
1. Introduction to Programming
1.1 What is Programming?
Programming is the process of designing and writing a precise sequence of instructions that a computer can understand and execute to perform a specific task or solve a problem.
A computer is an incredibly fast but fundamentally unintelligent machine — it cannot think, reason, or make decisions on its own. It only follows the instructions given to it, exactly as written, step by step. These instructions are written in a programming language — a formal language with strict syntax and rules that both humans can write and computers can process.
Why Do We Need Programming?
| Without Programming | With Programming |
|---|---|
| Computer is just hardware — a box of circuits | Computer becomes a powerful tool |
| Cannot perform any useful task | Can calculate, store data, communicate, automate |
| No applications, no games, no websites | Apps, games, websites, AI — everything exists |
| Cannot process information | Processes billions of operations per second |
Everything digital — from the calculator app on your phone to Google Search to self-driving cars — exists because someone wrote a program.
What Does a Program Look Like?
A program is a collection of instructions written in a specific syntax that solves a defined problem.
Real-world analogy: Think of a recipe for cooking. The recipe has:
- A list of ingredients (input)
- Step-by-step instructions (process)
- The final dish (output)
Similarly, a program takes input, processes it using instructions, and produces output.
Example: Calculate total marks of a student
| Step | Instruction |
|---|---|
| 1 | Take input: marks of each subject |
| 2 | Add all marks together |
| 3 | Store the result as total |
| 4 | Display the total to the user |
When these steps are written in Java (or any programming language), it becomes a program.
The Complete Programming Process
| Phase | What Happens | Skills Required |
|---|---|---|
| 1. Problem Understanding | Clearly define what needs to be solved | Analytical thinking |
| 2. Logic Building | Design the step-by-step solution (algorithm) | Logical reasoning |
| 3. Writing Code | Translate the algorithm into a programming language | Syntax knowledge |
| 4. Compilation/Interpretation | Convert code into machine-executable form | Tool knowledge |
| 5. Testing | Check if the program works correctly for all inputs | Testing skills |
| 6. Debugging | Find and fix errors (bugs) in the code | Patience, attention to detail |
| 7. Maintenance | Update and improve the program over time | Documentation, code organization |
Important: Programming is NOT just coding. It is logical problem solving. The code is just the final expression of a well-thought-out solution.
1.2 Algorithm & Flowchart
What is an Algorithm?
An algorithm is a finite, well-defined sequence of step-by-step instructions designed to solve a specific problem or accomplish a particular task.
Think of an algorithm as a recipe for solving a problem — it tells you exactly what to do, in what order, and when to stop.
Five Essential Properties of an Algorithm
| Property | Meaning | Example |
|---|---|---|
| Input | Must accept zero or more inputs | Accepting two numbers |
| Output | Must produce at least one output | Displaying the sum |
| Finiteness | Must terminate after a finite number of steps | Stops after calculating |
| Definiteness | Each step must be clear, precise, and unambiguous | "Add A and B" not "do something" |
| Effectiveness | Each step must be feasible and executable | No impossible operations |
Algorithm Example: Calculate Area of a Rectangle
| Step | Instruction |
|---|---|
| 1 | START |
| 2 | Input length (L) |
| 3 | Input breadth (B) |
| 4 | Calculate Area = L x B |
| 5 | Display Area |
| 6 | STOP |
Algorithm Example: Find Largest of Three Numbers
| Step | Instruction |
|---|---|
| 1 | START |
| 2 | Input three numbers: A, B, C |
| 3 | IF A > B AND A > C, THEN Largest = A |
| 4 | ELSE IF B > A AND B > C, THEN Largest = B |
| 5 | ELSE Largest = C |
| 6 | Display Largest |
| 7 | STOP |
Key Point: Algorithms are language-independent — the same algorithm can be implemented in Java, Python, C++, or any other language.
What is a Flowchart?
A flowchart is a graphical/diagrammatic representation of an algorithm using standardized symbols connected by arrows (flow lines) that show the sequence and flow of operations.
Standard Flowchart Symbols
| Symbol | Shape | Purpose | Example |
|---|---|---|---|
| Terminal | Start / End of the program | START, STOP | |
| Input/Output | Read input or display output | Read A, Print Sum | |
| Process | Calculation or assignment | Sum = A + B | |
| Decision | Condition check (Yes/No) | Is A > B? | |
| Flow Line | Shows direction of flow | → ↓ | |
| Connector | Connects parts of flowchart | Multi-page flowcharts |
Why Use Flowcharts?
| Benefit | Explanation |
|---|---|
| Visual clarity | Easier to understand than textual algorithms |
| Communication | Team members can discuss logic visually |
| Debugging | Logical errors are easier to spot in diagrams |
| Documentation | Serves as permanent record of program logic |
| Planning | Helps plan before writing code |
Best practice: Always design your algorithm/flowchart BEFORE writing code. This prevents logical errors and saves time.
1.3 Compilation vs Interpretation
When you write code in a high-level language, the computer cannot understand it directly. It must be translated into machine code (binary: 0s and 1s). There are two main approaches:
Compilation
| Aspect | Detail |
|---|---|
| Process | Entire source code is translated into machine code at once |
| Output | Produces an executable file (.exe on Windows) |
| Error detection | All errors detected before execution (compile-time errors) |
| Execution speed | Very fast — already in machine code |
| Examples | C, C++, Rust, Go |
| Tool called | Compiler |
Interpretation
| Aspect | Detail |
|---|---|
| Process | Source code is executed line by line |
| Output | No separate executable file created |
| Error detection | Errors detected during execution (runtime errors) |
| Execution speed | Slower — each line is translated every time |
| Examples | Python (mostly), JavaScript, Ruby |
| Tool called | Interpreter |
Java's Hybrid Approach — The Best of Both Worlds
Java uses both compilation and interpretation, making it unique:
| Stage | What Happens | Tool |
|---|---|---|
| Step 1: Compilation | Java source code (.java) is compiled into bytecode (.class) | javac (Java Compiler) |
| Step 2: Interpretation | Bytecode is interpreted and executed by the JVM | JVM (Java Virtual Machine) |
| Optimization | Frequently used bytecode is compiled to native machine code | JIT (Just-In-Time Compiler) |
This hybrid approach gives Java:
- Compile-time error checking (catches errors early)
- Platform independence (bytecode runs on any JVM)
- Good performance (JIT optimizes hot code paths)
1.4 Low-Level vs High-Level Languages
| Feature | Low-Level Language | High-Level Language |
|---|---|---|
| Closeness to hardware | Very close to machine | Far from machine, close to human |
| Readability | Very difficult for humans | Easy to read and write |
| Portability | Platform-specific | Platform-independent (mostly) |
| Execution speed | Very fast | Slower (due to translation) |
| Memory control | Direct memory manipulation | Abstracted memory management |
| Examples | Machine Code (binary), Assembly | Java, Python, C++, JavaScript |
| Use cases | Device drivers, OS kernels, embedded systems | Applications, web apps, mobile apps |
Language Hierarchy
| Level | Language Type | Example | Who Uses |
|---|---|---|---|
| Level 1 | Machine Language | Binary (0s and 1s) | CPU directly |
| Level 2 | Assembly Language | MOV, ADD, SUB instructions | System programmers |
| Level 3 | High-Level Language | Java, Python, C++ | Application developers |
| Level 4 | Very High-Level / 4GL | SQL, MATLAB, R | Specialized domains |
Java is a high-level language — it uses English-like keywords (class, public, void, if, while) making it readable and maintainable.
1.5 Structured vs Object-Oriented Programming
| Feature | Structured Programming | Object-Oriented Programming (OOP) |
|---|---|---|
| Approach | Top-down approach | Bottom-up approach |
| Focus | Focus on procedures/functions | Focus on objects (data + behavior) |
| Data and Functions | Separate — functions operate on data | Combined — objects contain both |
| Code reuse | Limited — through function calls | Extensive — through inheritance, polymorphism |
| Data security | Less secure — data is accessible globally | More secure — data is encapsulated within objects |
| Scalability | Difficult for large programs | Designed for large, complex applications |
| Maintenance | Harder to maintain as program grows | Easier to maintain and extend |
| Examples | C, Pascal, FORTRAN | Java, C++, Python, C# |
Four Pillars of OOP (Preview — Detailed in Module 3)
| Pillar | Meaning | Real-World Analogy |
|---|---|---|
| Encapsulation | Wrapping data and methods into a single unit (class) | A capsule containing medicine |
| Inheritance | One class acquiring properties of another | Child inherits traits from parent |
| Polymorphism | One interface, multiple implementations | A person is a student, son, and friend |
| Abstraction | Hiding complexity, showing only essential details | Car dashboard hides engine internals |
Java is primarily an Object-Oriented language — everything in Java revolves around classes and objects.
2. Introduction to Java
2.1 History of Java
| Year | Event |
|---|---|
| 1991 | James Gosling and team at Sun Microsystems start the "Green Project" |
| 1991 | Language initially named Oak (after an oak tree outside Gosling's office) |
| 1994 | Oak renamed to Green, then to Java (inspired by Java coffee from Indonesia) |
| 1995 | Java 1.0 officially released — the era of "Write Once, Run Anywhere" begins |
| 1996 | JDK 1.0 released publicly |
| 2004 | Java 5 (Tiger) — introduced Generics, Enhanced for-loop, Autoboxing |
| 2006 | Java became open-source under GPL |
| 2010 | Oracle acquires Sun Microsystems — becomes the owner of Java |
| 2014 | Java 8 — Lambda expressions, Streams API, functional programming features |
| 2017 | Java 9 — Module system (Project Jigsaw) |
| 2018+ | Six-month release cycle begins (Java 10, 11, 12... every 6 months) |
| 2021 | Java 17 (LTS) — Long-Term Support release |
| 2023 | Java 21 (LTS) — Virtual Threads, Pattern Matching |
Key Facts for Exams:
- Creator: James Gosling (Father of Java)
- Company: Sun Microsystems (now Oracle)
- Year: 1995
- Original name: Oak
- Motto: WORA — Write Once, Run Anywhere
2.2 Java Editions
| Edition | Full Name | Purpose | Examples |
|---|---|---|---|
| Java SE | Standard Edition | Core Java — desktop apps, fundamental programming | Console apps, Swing GUIs, basic programs |
| Java EE | Enterprise Edition | Web and enterprise applications | Servlets, JSP, EJB, REST APIs, Spring |
| Java ME | Micro Edition | Embedded and mobile devices | IoT devices, old mobile phones, set-top boxes |
| JavaFX | JavaFX | Rich GUI applications | Desktop apps with modern UI |
For beginners and most competitive exams, Java SE (Core Java) is the focus.
2.3 Features of Java — Complete List
| Feature | Explanation |
|---|---|
| Simple | Clean syntax similar to C/C++ but removes complexity (no pointers, no operator overloading) |
| Object-Oriented | Everything is based on classes and objects — promotes code organization and reuse |
| Platform Independent | Bytecode runs on any system with JVM — Write Once, Run Anywhere (WORA) |
| Secure | No pointer arithmetic, bytecode verification, Security Manager, sandboxed execution |
| Robust | Strong memory management, automatic garbage collection, exception handling |
| Multithreaded | Built-in support for concurrent programming — multiple threads can run simultaneously |
| Architecture Neutral | Bytecode is independent of CPU architecture (32-bit, 64-bit, ARM, x86) |
| Portable | No implementation-dependent features — data types have fixed sizes across platforms |
| High Performance | JIT compiler optimizes frequently executed code into native machine code |
| Distributed | Built-in networking support (java.net, RMI) for creating distributed applications |
| Dynamic | Supports dynamic class loading, reflection, and runtime type information |
| Interpreted | Bytecode is interpreted by JVM (with JIT optimization) |
Memory Trick for Features
S-O-P-S-R-M-A-P-H-D-D-I → Simple, Object-Oriented, Platform Independent, Secure, Robust, Multithreaded, Architecture Neutral, Portable, High Performance, Distributed, Dynamic, Interpreted
3. Java Architecture — The Most Important Section
Understanding Java architecture is critical for exams and interviews. This section explains how Java programs are compiled, loaded, verified, and executed.
3.1 JDK (Java Development Kit)
The JDK (Java Development Kit) is a comprehensive software development environment used to develop Java applications and applets. It is a physical bundle of software that includes everything you need to write, compile, and debug Java code.
1. Core Components of JDK
The JDK essentially consists of two main parts:
- JRE (Java Runtime Environment): Used to run Java programs.
- Development Tools: Used to build Java programs.
2. Essential Development Tools
The JDK includes several command-line tools that every Java developer must know:
| Tool | Full Name | Purpose |
|---|---|---|
javac | Java Compiler | Converts human-readable source code (.java) into bytecode (.class). |
java | Java Launcher | Starts the JVM, loads the class, and executes the program. |
jar | Java Archiver | Packages multiple class files and resources into a single .jar file for distribution. |
javadoc | Java Doc Generator | Automatically generates HTML documentation from comments in your code. |
jdb | Java Debugger | Helps find and fix bugs by allowing you to step through code line-by-line. |
javap | Java Disassembler | Used to see the actual bytecode inside a .class file. |
3. Why do we need the JDK?
Imagine you are a chef (the Developer).
- The JRE is like the Kitchen (the environment where the food is cooked and served).
- The JDK is the Kitchen + Chef's Toolkit (knives, pans, recipe books).
To run a restaurant (run an app), you just need a kitchen (JRE). But to be a chef and create new dishes (develop apps), you must have the full toolkit (JDK).
[!TIP] Who needs what?
- JDK: If you want to write and compile code (Developers).
- JRE: If you only want to run Java applications on your computer (End-users).
4. The Hierarchy
Mathematically, the relationship is often summarized as: JDK = JRE + Development Tools (And as we'll see in the next section, JRE = JVM + Class Libraries)
3.2 JRE (Java Runtime Environment)
The JRE (Java Runtime Environment) is a part of the Java Development Kit (JDK) that contains everything required to run a Java application. It is the implementation of the Java Virtual Machine (JVM) that actually exists on your computer.
1. What is inside the JRE?
The JRE is composed of three primary components:
- JVM (Java Virtual Machine): The engine that executes the bytecode.
- Class Libraries: A collection of pre-written code (like
java.lang,java.util) that your program needs to function. - Supporting Files: Configuration and property files used by the JVM.
2. Component Functions
| Component | Detailed Purpose |
|---|---|
| Java Virtual Machine (JVM) | Acts as a software-based "computer" that runs Java Bytecode. It handles memory management and security. |
| Standard Class Libraries | These are the "building blocks" of Java. For example, when you use System.out.println(), that code comes from the Class Libraries. |
| Java Launcher | A tool that finds the main method in your class and starts the JVM to run it. |
| Other Files | Includes fonts, setup files, and security certificates required for the program to look and behave correctly. |
3. How JRE Works (The Bridge)
Think of the JRE as a Language Translator Experience.
- The Bytecode is a book written in a foreign language.
- The JRE is the Reading Room that provides the Translator (JVM) and the Dictionary (Class Libraries).
- Without the JRE, your computer would see the
.classfile but wouldn't have the tools or the environment to understand or play it.
[!IMPORTANT] JRE is for REading/Running:
- If a user just wants to play a game written in Java or use a Java-based desktop app, they only need the JRE.
- The JRE does not contain the Java Compiler (
javac). Therefore, you cannot create new Java programs using only the JRE.
4. The Hierarchy
As mentioned before: JRE = JVM + Class Libraries + Supporting Files
3.3 JVM (Java Virtual Machine)
The JVM (Java Virtual Machine) is the heart of the Java technology. It is an abstract computer that runs on your real computer. It provides a runtime environment in which Java bytecode can be executed.
JVM Architecture — The Internal Subsystems
To understand how Java runs, you must understand the three main subsystems of the JVM:
1. Class Loader Subsystem
This subsystem is responsible for loading, linking, and initializing the class files.
- Loading: Reads the
.classfile and stores binary data in the Method Area. - Linking: Performs Verification (checks if bytecode is valid), Preparation (allocates memory for static variables), and Resolution (replaces symbolic references with actual memory references).
- Initialization: Assigns actual values to static variables and executes static blocks.
2. Runtime Data Areas (Memory Management)
JVM divides its memory into five main areas to manage data efficiently:
| Memory Area | Description & Ownership | What It Stores |
|---|---|---|
| Method Area | One per JVM (Shared) | Class-level data, static variables, and runtime constant pool. |
| Heap Area | One per JVM (Shared) | All Objects and their instance variables. This is where Garbage Collection happens. |
| Stack Area | One per Thread | Method calls, local variables, and return values. A "Stack Frame" is created for every method call. |
| PC Register | One per Thread | Contains the address of the current JVM instruction being executed. |
| Native Stack | One per Thread | Stores information about native methods (methods written in C/C++). |
3. Execution Engine
This is where the actual work happens. It "talks" to the hardware.
- Interpreter: Reads bytecode and executes it line-by-line. It is fast to start but slow for repeated code.
- JIT (Just-In-Time) Compiler: Identifies "hot spots" (code that runs repeatedly) and compiles them into Native Machine Code for high performance.
- Garbage Collector (GC): Automatically identifies objects that are no longer in use and deletes them to free up memory.
4. Native Method Interface (JNI)
The JNI is a bridge that allows Java code to interact with libraries written in other languages like C or C++. This is useful for high-performance graphics or interacting directly with hardware.
[!IMPORTANT]
Why is the JVM "platform-dependent"?
Even though the Bytecode (.class) is identical for all systems, the JVM itself must know how to talk to the specific OS (Windows, Mac, or Linux). Therefore, you download a different JVM for Windows than you do for Mac, but they both run the same Java programs.
Summary: The Software CPU
The JVM is essentially a software-based CPU that translates your generic Bytecode into the specific "language" of your computer's hardware.
3.4 The JDK-JRE-JVM Hierarchy
The relationship is:
| Container | Contains |
|---|---|
| JDK | JRE + Development Tools (javac, jdb, javadoc, jar) |
| JRE | JVM + Class Libraries + Supporting Files |
| JVM | Class Loader + Bytecode Verifier + Execution Engine + Memory + GC |
Visual hierarchy: JDK contains JRE, and JRE contains JVM.
3.5 Bytecode — Java's Secret to Portability
Java's most famous motto is "Write Once, Run Anywhere" (WORA). The "secret" that makes this possible is Bytecode.
1. What is Java Bytecode?
Bytecode is a highly optimized set of instructions designed to be executed by the Java Virtual Machine (JVM) rather than the physical CPU.
- When you compile a C or C++ program, it is converted directly into Machine Code (specific to Windows, Linux, or Mac).
- When you compile a Java program, the
javaccompiler converts it into Bytecode (a.classfile).
2. The Compilation & Execution Process
To understand portability, let's look at the lifecycle of a Java program:
| Step | Action | Tool / Component | Output |
|---|---|---|---|
| 1. Writing | Programmer writes the code. | Text Editor / IDE | Main.java (Source Code) |
| 2. Compiling | Code is checked for syntax errors. | javac (Compiler) | Main.class (Bytecode) |
| 3. Loading | Bytecode is brought into memory. | Class Loader | Loaded Bytecode |
| 4. Verifying | Ensures code is safe and not corrupted. | Bytecode Verifier | Verified Bytecode |
| 5. Executing | Bytecode is converted to Machine Code. | JVM (Interpreter + JIT) | Program Output |
3. Why is Bytecode the "Secret" to Portability?
Imagine you are writing a book and want people in China, India, and France to read it.
- The C++ Way: You write three different books in three different languages.
- The Java Way: You write the book in a special "Universal Language" (Bytecode). You then give everyone a "Translator" (the JVM). Whether the reader is in China or France, as long as they have the JVM translator, they can read your book perfectly.
[!IMPORTANT]
Key Concept: The Java compiler (javac) is Platform Independent (it always produces the same bytecode), but the Java Virtual Machine (JVM) is Platform Dependent (Windows has a Windows-JVM, Mac has a Mac-JVM).
4. Comparison: Machine Code vs. Bytecode
| Feature | Machine Code (C/C++) | Bytecode (Java) |
|---|---|---|
| Target | Physical CPU (Intel, ARM, etc.) | Virtual Machine (JVM) |
| File Extension | .exe, .out, .bin | .class |
| Portability | Low (Specific to one OS/Hardware) | High (Platform Independent) |
| Security | Hard to verify (direct hardware access) | High (Verified by JVM before running) |
| Execution | Runs directly on Hardware | Needs JVM to execute |
3.6 JIT (Just-In-Time) Compiler
The JIT (Just-In-Time) Compiler is the secret weapon of the JVM that makes Java programs run at lightning speed. It is a part of the Execution Engine that drastically improves the performance of Java applications at runtime.
1. Why do we need JIT?
Computers have two main ways to run high-level code:
- Interpreter: Starts quickly but runs slowly because it translates every line of code as it runs, even if that line runs 1,000 times (like in a loop).
- Compiler (C++/Rust): Slow to start (needs time to compile everything) but runs very fast because it produces machine code once.
Java uses a Hybrid Approach: It uses the Interpreter to start the program instantly and the JIT Compiler to speed it up as it runs.
2. The "Hotspot" Concept
The JVM monitors your code while it's running. It identifies "Hotspots"—sections of code that are executed frequently (like a loop that runs 50,000 times).
When a hotspot is detected, the JIT Compiler steps in and:
- Translates that specific bytecode into Native Machine Code (the CPU's native language).
- Stores that native code in a special cache.
- The next time that code is needed, the CPU runs the native code directly without any translation.
3. Comparison: Interpreter vs. JIT Compiler
| Feature | Interpreter | JIT Compiler |
|---|---|---|
| Speed | Fast to start, slow to execute. | Slow to start, incredibly fast to execute. |
| Method | Translates line-by-line. | Translates entire "Hot" segments at once. |
| Efficiency | Same line is translated every time. | Translates once, reuses the native code. |
| Role | Handles code that runs once or twice. | Handles code that runs repeatedly. |
4. Adaptive Optimization
The JIT doesn't just compile; it optimizes. It analyzes the running program and makes "guesses" on how to make the code faster (like inlining small methods or removing redundant checks). If the guess is wrong, it can even "de-optimize" and go back to the interpreter to maintain safety.
[!TIP] Performance Fact: In long-running applications (like servers), Java can often reach or even exceed the speed of C++ because the JIT compiler can optimize the code based on how it's actually being used, which a static compiler cannot do.
Summary
The JIT Compiler ensures that Java achieves the best of both worlds: the Portability of an interpreted language and the Performance of a compiled language.
3.7 Class Loader — Loading Classes into Memory
The Class Loader is a crucial subsystem of the JVM that is used to load class files dynamically at runtime. It is the first component that touches your .class files and brings them into the JVM's memory.
1. Why do we need it?
In many languages (like C), all code is loaded at once when the program starts. Java is different—it loads classes on-demand (only when they are needed for the first time). This makes Java more memory-efficient and flexible.
2. The Three Built-in Class Loaders
Java uses a hierarchy of three loaders to ensure security and organization:
| Class Loader | Responsibility | Source Location |
|---|---|---|
| Bootstrap Class Loader | Loads core Java API classes (like String, System). | rt.jar (RunTime jar) or lib folder. |
| Extension Class Loader | Loads classes from the extension directories. | jre/lib/ext or specified by java.ext.dirs. |
| Application (System) Class Loader | Loads your project's code and external libraries. | Environment variable CLASSPATH. |
3. Delegation Hierarchy Model
When a class needs to be loaded, Java follows a unique "Ask-the-Parent-First" rule:
- Request: You call a class.
- Delegation: The Application Loader asks the Extension Loader. The Extension Loader asks the Bootstrap Loader.
- Search: If the Bootstrap Loader finds it, it loads it. If not, the request comes back down to the Extension, then finally to the Application loader.
[!NOTE]
Why this model? It prevents security risks. For example, a malicious user cannot write their own version of the String class and force Java to load it, because the Bootstrap Loader will always find the official version first.
4. The Three Principles
- Delegation: Passes the loading request to the parent.
- Visibility: A child loader can see classes loaded by parent loaders, but a parent cannot see classes loaded by a child.
- Uniqueness: A class loaded by a parent should not be re-loaded by a child.
3.8 Garbage Collection — Automatic Memory Management
One of Java's biggest advantages is that you never have to "clean up" the memory yourself. The Garbage Collector (GC) is a background process that automatically manages memory for you.
1. What is Garbage Collection?
In older languages like C or C++, if you create a variable, you must manually delete it when you're done. If you forget, your computer runs out of memory (a Memory Leak). In Java, the GC automatically identifies objects that are no longer being used and deletes them to free up space.
2. How does it work? (The "Mark and Sweep" Concept)
The GC follows a simple but powerful process:
- Mark: It traces all objects starting from the "roots" (active variables). Objects that are still reachable are "marked" as alive.
- Sweep: Any object that was not marked is considered "garbage" and is "swept" away (deleted).
3. When is an Object eligible for GC?
An object becomes "garbage" when it can no longer be reached by your code. This happens if:
- The variable is set to
null(e.g.,student = null;). - The variable goes out of scope (e.g., a variable inside a method after the method finishes).
- The object is "orphaned" (no one points to it anymore).
4. Comparison: Java vs. C++ Memory Management
| Feature | C / C++ | Java |
|---|---|---|
| Allocation | Manual (malloc, new) | Automatic (new keyword) |
| Deallocation | Manual (free, delete) | Automatic (Garbage Collector) |
| Risk | High (Memory Leaks, Dangling Pointers) | Minimal (JVM manages everything) |
| Complexity | High (Programmer must track memory) | Low (Programmer focuses on logic) |
5. Can we control the GC?
No. While you can "request" the GC to run using System.gc(), the JVM usually ignores this request and runs it only when it feels necessary.
[!TIP] Best Practice: Don't try to force the GC. Focus on writing clean code, and let the JVM handle the memory. It is much better at it than humans!
4. Java Program Structure
4.1 Basic Structure of a Java Program
Every Java program follows this structure:
4.2 Understanding Each Component
| Component | Meaning | Why It Is Required |
|---|---|---|
| class | Keyword that defines a class | Java is OOP — everything must be inside a class |
| ClassName | Name of the class (must match filename) | Identifies the class; follows PascalCase convention |
| public | Access modifier — accessible from everywhere | JVM needs to access main() from outside the class |
| static | Belongs to the class, not an object instance | JVM calls main() without creating an object |
| void | Return type — returns nothing | main() does not return any value to JVM |
| main | The method name — recognized by JVM as entry point | JVM looks specifically for "main" to start execution |
| String[] args | Parameter — array of strings for command-line arguments | Allows passing values when running the program |
| System.out.println() | Prints text to the console followed by a new line | Standard output method in Java |
4.3 The Complete Compilation and Execution Process
| Step | Command | What Happens |
|---|---|---|
| 1. Write | Use any text editor or IDE | Create a file named HelloWorld.java |
| 2. Compile | javac HelloWorld.java | javac compiler checks for errors, generates HelloWorld.class (bytecode) |
| 3. Run | java HelloWorld | JVM loads bytecode, verifies it, and executes the program |
| 4. Output | (Console) | "Hello, World!" is displayed |
4.4 Important Rules
| Rule | Explanation |
|---|---|
| File name must match class name | If class is HelloWorld, file must be HelloWorld.java |
| Java is case-sensitive | Main is not same as main, String is not same as string |
| Every statement ends with semicolon | Semicolons are mandatory statement terminators |
| Code blocks use curly braces | Curly braces define scope of classes, methods, loops |
| Comments | // single line, /* multi line /, and /* documentation */ |
5. Setting Up Java Development Environment
5.1 Installing JDK
| Step | Action |
|---|---|
| 1 | Download JDK from oracle.com or use OpenJDK |
| 2 | Run the installer |
| 3 | Set JAVA_HOME environment variable to JDK installation directory |
| 4 | Add JAVA_HOME/bin to the PATH variable |
| 5 | Verify: Open command prompt and type java -version and javac -version |
5.2 Popular Java IDEs
| IDE | Developer | Best For |
|---|---|---|
| IntelliJ IDEA | JetBrains | Professional Java development (most popular) |
| Eclipse | Eclipse Foundation | Enterprise Java (free, open-source) |
| VS Code | Microsoft | Lightweight editing with Java extensions |
| NetBeans | Apache | Beginner-friendly, built-in tools |
| Notepad++ | Don Ho | Basic code editing (no IDE features) |
Practice Lab
Interactive Java Compiler
Write, compile, and run code in your browser
