2026-03-07
Interactive Course

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 ProgrammingWith Programming
Computer is just hardware — a box of circuitsComputer becomes a powerful tool
Cannot perform any useful taskCan calculate, store data, communicate, automate
No applications, no games, no websitesApps, games, websites, AI — everything exists
Cannot process informationProcesses 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

StepInstruction
1Take input: marks of each subject
2Add all marks together
3Store the result as total
4Display the total to the user

When these steps are written in Java (or any programming language), it becomes a program.

The Complete Programming Process

PhaseWhat HappensSkills Required
1. Problem UnderstandingClearly define what needs to be solvedAnalytical thinking
2. Logic BuildingDesign the step-by-step solution (algorithm)Logical reasoning
3. Writing CodeTranslate the algorithm into a programming languageSyntax knowledge
4. Compilation/InterpretationConvert code into machine-executable formTool knowledge
5. TestingCheck if the program works correctly for all inputsTesting skills
6. DebuggingFind and fix errors (bugs) in the codePatience, attention to detail
7. MaintenanceUpdate and improve the program over timeDocumentation, code organization
Note

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.

Algorithm Properties Mindmap

Five Essential Properties of an Algorithm

PropertyMeaningExample
InputMust accept zero or more inputsAccepting two numbers
OutputMust produce at least one outputDisplaying the sum
FinitenessMust terminate after a finite number of stepsStops after calculating
DefinitenessEach step must be clear, precise, and unambiguous"Add A and B" not "do something"
EffectivenessEach step must be feasible and executableNo impossible operations

Algorithm Example: Calculate Area of a Rectangle

StepInstruction
1START
2Input length (L)
3Input breadth (B)
4Calculate Area = L x B
5Display Area
6STOP

Algorithm Example: Find Largest of Three Numbers

StepInstruction
1START
2Input three numbers: A, B, C
3IF A > B AND A > C, THEN Largest = A
4ELSE IF B > A AND B > C, THEN Largest = B
5ELSE Largest = C
6Display Largest
7STOP

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

SymbolShapePurposeExample
TerminalStart / End of the programSTART, STOP
Input/OutputRead input or display outputRead A, Print Sum
ProcessCalculation or assignmentSum = A + B
DecisionCondition check (Yes/No)Is A > B?
Flow LineShows direction of flow→ ↓
ConnectorConnects parts of flowchartMulti-page flowcharts

Why Use Flowcharts?

BenefitExplanation
Visual clarityEasier to understand than textual algorithms
CommunicationTeam members can discuss logic visually
DebuggingLogical errors are easier to spot in diagrams
DocumentationServes as permanent record of program logic
PlanningHelps plan before writing code
Note

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

AspectDetail
ProcessEntire source code is translated into machine code at once
OutputProduces an executable file (.exe on Windows)
Error detectionAll errors detected before execution (compile-time errors)
Execution speedVery fast — already in machine code
ExamplesC, C++, Rust, Go
Tool calledCompiler

Interpretation

AspectDetail
ProcessSource code is executed line by line
OutputNo separate executable file created
Error detectionErrors detected during execution (runtime errors)
Execution speedSlower — each line is translated every time
ExamplesPython (mostly), JavaScript, Ruby
Tool calledInterpreter

Java's Hybrid Approach — The Best of Both Worlds

Java uses both compilation and interpretation, making it unique:

StageWhat HappensTool
Step 1: CompilationJava source code (.java) is compiled into bytecode (.class)javac (Java Compiler)
Step 2: InterpretationBytecode is interpreted and executed by the JVMJVM (Java Virtual Machine)
OptimizationFrequently used bytecode is compiled to native machine codeJIT (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

FeatureLow-Level LanguageHigh-Level Language
Closeness to hardwareVery close to machineFar from machine, close to human
ReadabilityVery difficult for humansEasy to read and write
PortabilityPlatform-specificPlatform-independent (mostly)
Execution speedVery fastSlower (due to translation)
Memory controlDirect memory manipulationAbstracted memory management
ExamplesMachine Code (binary), AssemblyJava, Python, C++, JavaScript
Use casesDevice drivers, OS kernels, embedded systemsApplications, web apps, mobile apps

Language Hierarchy

LevelLanguage TypeExampleWho Uses
Level 1Machine LanguageBinary (0s and 1s)CPU directly
Level 2Assembly LanguageMOV, ADD, SUB instructionsSystem programmers
Level 3High-Level LanguageJava, Python, C++Application developers
Level 4Very High-Level / 4GLSQL, MATLAB, RSpecialized 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

FeatureStructured ProgrammingObject-Oriented Programming (OOP)
ApproachTop-down approachBottom-up approach
FocusFocus on procedures/functionsFocus on objects (data + behavior)
Data and FunctionsSeparate — functions operate on dataCombined — objects contain both
Code reuseLimited — through function callsExtensive — through inheritance, polymorphism
Data securityLess secure — data is accessible globallyMore secure — data is encapsulated within objects
ScalabilityDifficult for large programsDesigned for large, complex applications
MaintenanceHarder to maintain as program growsEasier to maintain and extend
ExamplesC, Pascal, FORTRANJava, C++, Python, C#

Four Pillars of OOP (Preview — Detailed in Module 3)

PillarMeaningReal-World Analogy
EncapsulationWrapping data and methods into a single unit (class)A capsule containing medicine
InheritanceOne class acquiring properties of anotherChild inherits traits from parent
PolymorphismOne interface, multiple implementationsA person is a student, son, and friend
AbstractionHiding complexity, showing only essential detailsCar 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

YearEvent
1991James Gosling and team at Sun Microsystems start the "Green Project"
1991Language initially named Oak (after an oak tree outside Gosling's office)
1994Oak renamed to Green, then to Java (inspired by Java coffee from Indonesia)
1995Java 1.0 officially released — the era of "Write Once, Run Anywhere" begins
1996JDK 1.0 released publicly
2004Java 5 (Tiger) — introduced Generics, Enhanced for-loop, Autoboxing
2006Java became open-source under GPL
2010Oracle acquires Sun Microsystems — becomes the owner of Java
2014Java 8 — Lambda expressions, Streams API, functional programming features
2017Java 9 — Module system (Project Jigsaw)
2018+Six-month release cycle begins (Java 10, 11, 12... every 6 months)
2021Java 17 (LTS) — Long-Term Support release
2023Java 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

EditionFull NamePurposeExamples
Java SEStandard EditionCore Java — desktop apps, fundamental programmingConsole apps, Swing GUIs, basic programs
Java EEEnterprise EditionWeb and enterprise applicationsServlets, JSP, EJB, REST APIs, Spring
Java MEMicro EditionEmbedded and mobile devicesIoT devices, old mobile phones, set-top boxes
JavaFXJavaFXRich GUI applicationsDesktop apps with modern UI

For beginners and most competitive exams, Java SE (Core Java) is the focus.


2.3 Features of Java — Complete List

FeatureExplanation
SimpleClean syntax similar to C/C++ but removes complexity (no pointers, no operator overloading)
Object-OrientedEverything is based on classes and objects — promotes code organization and reuse
Platform IndependentBytecode runs on any system with JVM — Write Once, Run Anywhere (WORA)
SecureNo pointer arithmetic, bytecode verification, Security Manager, sandboxed execution
RobustStrong memory management, automatic garbage collection, exception handling
MultithreadedBuilt-in support for concurrent programming — multiple threads can run simultaneously
Architecture NeutralBytecode is independent of CPU architecture (32-bit, 64-bit, ARM, x86)
PortableNo implementation-dependent features — data types have fixed sizes across platforms
High PerformanceJIT compiler optimizes frequently executed code into native machine code
DistributedBuilt-in networking support (java.net, RMI) for creating distributed applications
DynamicSupports dynamic class loading, reflection, and runtime type information
InterpretedBytecode is interpreted by JVM (with JIT optimization)

Memory Trick for Features

Note

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.

Java Architecture: JDK, JRE, and JVM

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:

  1. JRE (Java Runtime Environment): Used to run Java programs.
  2. Development Tools: Used to build Java programs.

2. Essential Development Tools

The JDK includes several command-line tools that every Java developer must know:

ToolFull NamePurpose
javacJava CompilerConverts human-readable source code (.java) into bytecode (.class).
javaJava LauncherStarts the JVM, loads the class, and executes the program.
jarJava ArchiverPackages multiple class files and resources into a single .jar file for distribution.
javadocJava Doc GeneratorAutomatically generates HTML documentation from comments in your code.
jdbJava DebuggerHelps find and fix bugs by allowing you to step through code line-by-line.
javapJava DisassemblerUsed 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

[!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:

  1. JVM (Java Virtual Machine): The engine that executes the bytecode.
  2. Class Libraries: A collection of pre-written code (like java.lang, java.util) that your program needs to function.
  3. Supporting Files: Configuration and property files used by the JVM.

2. Component Functions

ComponentDetailed Purpose
Java Virtual Machine (JVM)Acts as a software-based "computer" that runs Java Bytecode. It handles memory management and security.
Standard Class LibrariesThese are the "building blocks" of Java. For example, when you use System.out.println(), that code comes from the Class Libraries.
Java LauncherA tool that finds the main method in your class and starts the JVM to run it.
Other FilesIncludes 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 .class file but wouldn't have the tools or the environment to understand or play it.
Crucial

[!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 .class file 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 AreaDescription & OwnershipWhat It Stores
Method AreaOne per JVM (Shared)Class-level data, static variables, and runtime constant pool.
Heap AreaOne per JVM (Shared)All Objects and their instance variables. This is where Garbage Collection happens.
Stack AreaOne per ThreadMethod calls, local variables, and return values. A "Stack Frame" is created for every method call.
PC RegisterOne per ThreadContains the address of the current JVM instruction being executed.
Native StackOne per ThreadStores 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.

Crucial

[!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:

ContainerContains
JDKJRE + Development Tools (javac, jdb, javadoc, jar)
JREJVM + Class Libraries + Supporting Files
JVMClass 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 javac compiler converts it into Bytecode (a .class file).

2. The Compilation & Execution Process

To understand portability, let's look at the lifecycle of a Java program:

StepActionTool / ComponentOutput
1. WritingProgrammer writes the code.Text Editor / IDEMain.java (Source Code)
2. CompilingCode is checked for syntax errors.javac (Compiler)Main.class (Bytecode)
3. LoadingBytecode is brought into memory.Class LoaderLoaded Bytecode
4. VerifyingEnsures code is safe and not corrupted.Bytecode VerifierVerified Bytecode
5. ExecutingBytecode 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.
Crucial

[!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

FeatureMachine Code (C/C++)Bytecode (Java)
TargetPhysical CPU (Intel, ARM, etc.)Virtual Machine (JVM)
File Extension.exe, .out, .bin.class
PortabilityLow (Specific to one OS/Hardware)High (Platform Independent)
SecurityHard to verify (direct hardware access)High (Verified by JVM before running)
ExecutionRuns directly on HardwareNeeds 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:

  1. Translates that specific bytecode into Native Machine Code (the CPU's native language).
  2. Stores that native code in a special cache.
  3. The next time that code is needed, the CPU runs the native code directly without any translation.

3. Comparison: Interpreter vs. JIT Compiler

FeatureInterpreterJIT Compiler
SpeedFast to start, slow to execute.Slow to start, incredibly fast to execute.
MethodTranslates line-by-line.Translates entire "Hot" segments at once.
EfficiencySame line is translated every time.Translates once, reuses the native code.
RoleHandles 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

[!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 LoaderResponsibilitySource Location
Bootstrap Class LoaderLoads core Java API classes (like String, System).rt.jar (RunTime jar) or lib folder.
Extension Class LoaderLoads classes from the extension directories.jre/lib/ext or specified by java.ext.dirs.
Application (System) Class LoaderLoads 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:

  1. Request: You call a class.
  2. Delegation: The Application Loader asks the Extension Loader. The Extension Loader asks the Bootstrap Loader.
  3. 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

[!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:

  1. Mark: It traces all objects starting from the "roots" (active variables). Objects that are still reachable are "marked" as alive.
  2. 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

FeatureC / C++Java
AllocationManual (malloc, new)Automatic (new keyword)
DeallocationManual (free, delete)Automatic (Garbage Collector)
RiskHigh (Memory Leaks, Dangling Pointers)Minimal (JVM manages everything)
ComplexityHigh (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

[!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:

class ClassName { public static void main(String[] args) { // Your code here System.out.println("Hello, World!"); } }

4.2 Understanding Each Component

ComponentMeaningWhy It Is Required
classKeyword that defines a classJava is OOP — everything must be inside a class
ClassNameName of the class (must match filename)Identifies the class; follows PascalCase convention
publicAccess modifier — accessible from everywhereJVM needs to access main() from outside the class
staticBelongs to the class, not an object instanceJVM calls main() without creating an object
voidReturn type — returns nothingmain() does not return any value to JVM
mainThe method name — recognized by JVM as entry pointJVM looks specifically for "main" to start execution
String[] argsParameter — array of strings for command-line argumentsAllows passing values when running the program
System.out.println()Prints text to the console followed by a new lineStandard output method in Java

4.3 The Complete Compilation and Execution Process

StepCommandWhat Happens
1. WriteUse any text editor or IDECreate a file named HelloWorld.java
2. Compilejavac HelloWorld.javajavac compiler checks for errors, generates HelloWorld.class (bytecode)
3. Runjava HelloWorldJVM loads bytecode, verifies it, and executes the program
4. Output(Console)"Hello, World!" is displayed

4.4 Important Rules

RuleExplanation
File name must match class nameIf class is HelloWorld, file must be HelloWorld.java
Java is case-sensitiveMain is not same as main, String is not same as string
Every statement ends with semicolonSemicolons are mandatory statement terminators
Code blocks use curly bracesCurly braces define scope of classes, methods, loops
Comments// single line, /* multi line /, and /* documentation */

5. Setting Up Java Development Environment

5.1 Installing JDK

StepAction
1Download JDK from oracle.com or use OpenJDK
2Run the installer
3Set JAVA_HOME environment variable to JDK installation directory
4Add JAVA_HOME/bin to the PATH variable
5Verify: Open command prompt and type java -version and javac -version
IDEDeveloperBest For
IntelliJ IDEAJetBrainsProfessional Java development (most popular)
EclipseEclipse FoundationEnterprise Java (free, open-source)
VS CodeMicrosoftLightweight editing with Java extensions
NetBeansApacheBeginner-friendly, built-in tools
Notepad++Don HoBasic code editing (no IDE features)

Practice Lab

Interactive Java Compiler

Loading...
Hi! Need help with studies? 👋
AI