Programming & Java
Imagine you want your younger sibling to make tea. They have never made tea before, so you write them a note: "Boil water โ Add tea bag โ Pour into cup โ Add sugar โ Stir." You just wrote a program โ a precise, step-by-step set of instructions for someone to follow.
Programming is exactly that, but for a computer. The only critical difference: your sibling can think, guess, and adapt. A computer is completely literal. It does exactly what you write โ nothing more, nothing less. This is why programming must be precise.
A program is an ordered set of instructions written in a programming language, designed to perform a specific task or solve a problem. The act of writing these instructions is called programming (also called coding or software development).
Why Do We Need Programming?
Computers are incredibly fast and powerful machines, but they are completely brainless โ they cannot think independently. Every app on your phone, every website you visit, every ATM transaction โ all of it exists because a programmer told the computer exactly what to do, step by step.
- Without programming, your phone is just an expensive brick
- Without programming, hospitals cannot manage patient records
- Without programming, banks cannot process transactions
- Without programming, no games, no internet services, nothing digital works
What is a Programming Language?
Computers understand only one language: machine language โ sequences of 0s and 1s (binary). But humans find it nearly impossible to write millions of zeros and ones. So, programming languages were created as human-readable layers that get automatically translated to machine language.
Before writing Java code, understand the journey from your fingers to the screen. This is called the program execution model.
.java extension. Example: HelloWorld.javajavac) reads your source code and translates it into bytecode โ an intermediate, platform-neutral language. This produces a .class file..class bytecode and translates it into the actual machine language for your specific CPU and OS.Both are programs that translate code to machine language โ but they work in completely different ways. This is one of the most frequently asked concepts in university exams.
You have a French book to read but don't understand French.
Compiler = A translator who translates the entire book first, gives you the complete English copy, then you read it at full speed. Slow start, fast to read afterward.
Interpreter = A translator who sits next to you and translates sentence by sentence as you read. Starts immediately, but always slower because they translate in real time.
- Translates entire program at once
- Creates a separate output file
- All errors reported together
- Faster execution (translation already done)
- Examples: javac (Java), gcc (C/C++)
- Must recompile after code changes
- Translates and runs line by line
- No separate output file created
- Stops at first error found
- Slower execution (translating while running)
- Examples: Python, Ruby, PHP
- No recompile needed โ just run again
Java's Special Hybrid Approach
Step 1: javac compiles .java โ .class (bytecode) โ Compilation phase
Step 2: JVM interprets/executes the bytecode at runtime โ Interpretation phase
Step 3: Modern JVMs use JIT (Just-In-Time) compilation to convert hot bytecode directly to native machine code for near-native speed.
This hybrid gives Java the portability of interpreters and the speed of compiled languages.
| Feature | Compiler | Interpreter | Java (Hybrid) |
|---|---|---|---|
| Translation | All at once | Line by line | Compiled to bytecode โ JVM runs it |
| Speed | โก Fast execution | ๐ข Slower | ๐ Fast (with JIT) |
| Error reporting | All at compile time | Stops at first error | All at compile time |
| Output file | Yes (.exe/.out) | No | Yes (.class bytecode) |
| Portability | Platform-specific | Needs interpreter per OS | Platform-independent (via JVM) |
| Examples | C, C++, Go | Python, Ruby | Java, Kotlin, Scala |
You'll hear these three terms constantly. Most beginners confuse them. Let's fix that once and for all.
JVM (Java Virtual Machine) = The oven โ the machine that actually bakes (runs) the pizza (program).
JRE (Java Runtime Environment) = The restaurant โ everything needed to eat pizza (run Java programs). Includes the oven, tables, and staff.
JDK (Java Development Kit) = The restaurant + cooking school โ everything in JRE, PLUS all the tools to create new pizzas (write and compile Java programs). If you're a developer (chef), you need JDK.
JVM โ The Heart of Java
The Java Virtual Machine is a program that runs on your computer and acts as a virtual CPU. It reads bytecode and converts it to instructions your real CPU understands. The key insight: different operating systems have different JVMs, but they all understand the same bytecode.
| JDK Tool | Command | Purpose |
|---|---|---|
| javac | javac HelloWorld.java | Compiler โ converts .java โ .class |
| java | java HelloWorld | Launcher โ runs .class file via JVM |
| javadoc | javadoc HelloWorld.java | Generates HTML documentation |
| jar | jar -cf app.jar *.class | Packages .class files into archive |
| jdb | jdb HelloWorld | Debugger โ find bugs in programs |
Java's most famous feature โ officially called WORA (Write Once, Run Anywhere). Here's why it exists and exactly how it works.
The Problem Before Java
C++ compiles directly to machine code. Windows machine code โ Mac machine code โ Linux machine code. If you wrote a C++ program on Windows and wanted it to run on Mac, you had to recompile separately for every platform. For large projects, this was a nightmare.
Many students say "Yes!" โ but the precise answer is: Java programs (bytecode) are platform-independent. The JVM itself is platform-dependent (different JVM for Windows, Mac, Linux). The JVM is the bridge that makes Java programs appear platform-independent.
โ Model Answer: "Java source code and bytecode are platform-independent. The JVM is platform-specific, but since JVMs are provided for all major operating systems, Java programs can run anywhere without modification."
This is every Java developer's first program. Don't just type it โ understand every single character before moving on.
// File: HelloWorld.java // This is your very first Java program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Hello, World!
Line-by-Line Breakdown
publicโ Access modifier. This class is visible to everyone, including the JVM.classโ Keyword declaring this is a class. Every Java program needs at least one class. A class is a container for your code.HelloWorldโ The class name. Must EXACTLY match the filename (HelloWorld.java). Java is case-sensitive โhelloworldโHelloWorld.{ }โ Curly braces. Everything between them is the class body.
This is the entry point of every Java program. The JVM searches for this exact signature when it starts running your program. If it's not there, the program won't run.
publicโ The JVM (which is outside your class) needs to call this. Must be public.staticโ The JVM calls main without creating an object of your class first. static allows this.voidโ This method returns nothing to the caller.mainโ The exact name the JVM looks for. Cannot be changed or misspelled.String[] argsโ An array that holds command-line arguments. Can be empty โ you don't have to use it.
Systemโ A built-in Java class representing the computer system.outโ A static field inside System representing the standard output (your screen).printlnโ A method that prints text AND moves to a new line (print + line).("Hello, World!")โ The String argument โ text in double quotes.;โ Semicolon terminates every statement. Missing this is the #1 beginner mistake.
How to Compile and Run
HelloWorld.java. Filename must match class name exactly. Check capitalization carefully.cd path/to/folderjavac HelloWorld.java and press Enter. If no errors, a HelloWorld.class file appears in the folder.java HelloWorld (no .class extension!) and press Enter. You should see Hello, World! printed.- Filename doesn't match class name โ Saving as
hello.javabut writingpublic class HelloWorld. Error: "class HelloWorld is public, should be declared in a file named HelloWorld.java" - Missing semicolon โ
System.out.println("Hi")without;. Most common compile error. - Wrong capitalisation โ
system.out.printlnwon't work. Java is case-sensitive. Must beSystem.out.println. - Running with .class extension โ Typing
java HelloWorld.classinstead ofjava HelloWorld. - Misspelling main โ Writing
MainorMAINinstead ofmain. JVM won't find the entry point. - Missing curly braces โ Every
{needs a matching}. Count your braces. - Code outside a class โ In Java, ALL code must live inside a class. Nothing can be written at the "top level" outside a class.
| Step | Action | By | Result |
|---|---|---|---|
| 1 | User types javac HelloWorld.java | Terminal | Compiler starts reading source file |
| 2 | Compiler checks for syntax errors | javac | No errors found |
| 3 | Compiler translates source to bytecode | javac | HelloWorld.class created on disk |
| 4 | User types java HelloWorld | Terminal | JVM starts up |
| 5 | JVM loads HelloWorld.class | JVM | Bytecode loaded into memory |
| 6 | JVM searches for public static void main(String[] args) | JVM | Found in HelloWorld class |
| 7 | JVM executes System.out.println("Hello, World!") | JVM | Hello, World! printed to screen |
| 8 | main() body ends, no more statements | JVM | Program terminates normally |
- JDK / JRE / JVM: "D is for Developers, R is for Running, V is the Virtual machine inside" โ JDK (develop), JRE (run), JVM (virtual engine)
- WORA: Think of bytecode as a universal power adapter โ same plug (bytecode) works in any country's socket (OS via JVM).
- public static void main: "Please Stop Visiting My house" โ Public Static Void Main
- Compiler vs Interpreter: Compiler = full book translator (translate all, then read). Interpreter = live translator (sentence by sentence, right now).
- Semicolons: Every Java statement ends with
;โ treat it like the full stop (period) at the end of an English sentence. - Java file naming: Class name = filename. Always. PascalCase. No exceptions.
Theory Questions with Model Answers
Q: What is a program? Why is it needed?
Answer: A program is an ordered set of instructions written in a programming language that directs a computer to perform a specific task. Programs are needed because computers have no intelligence of their own โ they require precise, step-by-step instructions for every operation. Without programs, a computer is an inert machine incapable of any useful function.
Q: Distinguish between a compiler and an interpreter with examples.
Answer: A compiler translates the entire source code into machine code or an intermediate form at once, before execution begins. It detects all syntax errors at compile time and produces a separate executable file. Examples: javac (Java), gcc (C/C++). An interpreter translates and executes the source code line-by-line at runtime. It stops at the first error encountered and produces no separate file. Examples: Python interpreter, Ruby. Java uniquely combines both: javac compiles source to bytecode (.class), then the JVM interprets and executes that bytecode at runtime.
Q: Explain the role of JVM in making Java platform-independent. Differentiate between JVM, JRE, and JDK.
Answer: Java achieves platform independence through a two-step process. First, the Java compiler (javac) compiles source code (.java) into bytecode (.class files) โ a platform-neutral intermediate format not tied to any specific OS. Second, the JVM installed on each target OS reads bytecode and converts it to platform-specific machine code at runtime. Since every major OS has its own JVM implementation, the same bytecode runs unchanged on all platforms โ this is "Write Once, Run Anywhere."
JVM (Java Virtual Machine): The runtime engine that executes bytecode. Platform-specific โ a different JVM exists for Windows, Mac, and Linux.
JRE (Java Runtime Environment): Contains the JVM plus the Java standard class libraries. Used to RUN Java programs.
JDK (Java Development Kit): Contains the JRE plus development tools (compiler javac, debugger jdb, etc.). Used to DEVELOP and compile Java programs.
Viva Questions
- What is the difference between source code and bytecode?
- If only JRE is installed on a machine, can you compile Java programs? Why?
- Why must the Java filename exactly match the public class name?
- What would happen if you removed the
statickeyword from the main method? - Can a single .java file have multiple classes? What restriction applies?
- What does JIT compilation mean? How does it improve Java performance?
- Is Java purely object-oriented? Why or why not?
MCQ Bank
public static void main(String[] args). Every keyword matters. Missing 'public' or 'static' causes a runtime error: "Main method not found in class."java HelloWorld.class?java command takes a class name, not a filename. java HelloWorld.class looks for a class literally named "HelloWorld.class" (with a dot), which doesn't exist. The correct command is java HelloWorld (no extension).Output Prediction Exercises
Code 1:
System.out.println("Line 1"); System.out.print("Line 2"); System.out.println("Line 3");
Line 2Line 3
Why: println("Line 1") prints and moves to next line. print("Line 2") prints WITHOUT moving to next line. println("Line 3") prints on the same line as "Line 2", then moves to next line.
Code 2:
System.out.println("Hello\nWorld"); System.out.println("A\tB\tC");
World
A B C
Why: \n is the newline escape sequence โ moves to next line mid-string. \t is the tab escape sequence โ adds horizontal spacing.
Debugging Exercises
Public Class myProgram { public static Void Main(String[] args) { system.out.println("Hello") } }
Public โ must be public (lowercase p)Bug 2:
Class โ must be class (lowercase c)Bug 3:
Void โ must be void (lowercase v)Bug 4:
Main โ must be main (lowercase m โ JVM looks for "main")Bug 5:
system โ must be System (capital S)Bug 6: Missing semicolon after println("Hello")
javac compiles to platform-neutral bytecode โ JVM on each OS executes it. WORA.public class ClassName โ class name must exactly match filename (case-sensitive).public static void main(String[] args) โ exact JVM entry point. Every word matters. Trick: Please Stop Visiting My house.System.out.println() prints + newline. System.out.print() prints, no newline. System.out.printf() formatted.; โ missing it is the most common error.javac FileName.java. Run: java ClassName (no .class extension).Easy Problems
println() calls.print() and println(). Expected: Hello World!println(), print three lines of text using \n inside the string. Then add tabs using \t.***** / * * / * * / *****\".C:\Users\Student\Desktop\Java. You need \\ for each backslash. Tricky!public Class Test { public static void main(String args) { System.out.println("Hi") } }Public class test { Public Static Void Main(String[] Args) { system.out.Println("ok") }}javac, run with java in the terminal. What files are created? What happens if you skip compilation?Medium Problems
\t to print a table with three columns (Name, Age, City) and three rows of data. Columns should be aligned.System.out.println(1 + 2 + "3"); and System.out.println("1" + 2 + 3);. Explain why they differ, then verify.java ClassA vs java ClassB. What do you observe?printf to print: "Name: Ahmed, Score: 95.50, Grade: A" using format specifiers %s, %.2f, %c.System.out.println("\u0048\u0065\u006C\u006C\u006F"); โ what prints? Research what Unicode is and write a 3-sentence explanation in a comment block./** */ style. Practice professional documentation habits from day one.Hard Problems
args[0]: running java Greeter Alice prints "Hello, Alice!". Handle the case where no argument is provided (use args.length check).System.out.print() and escape sequences, produce this exact output on three lines: (1) a quoted sentence, (2) a Windows file path, (3) a tab-aligned table row.If you can answer all of these without notes, you truly own Chapter 1.
- Write the complete HelloWorld program from memory โ every keyword, every punctuation mark, correct capitalisation.
- Explain to a friend (out loud): the entire Java execution pipeline from source code to screen output.
- Answer without looking: What is the difference between JDK, JRE, and JVM? Which do you install as a developer and why?
- Predict and explain:
System.out.println("A" + "B" + 1 + 2);vsSystem.out.println(1 + 2 + "A" + "B");