Programming in Java
Unit 1: Introduction to Java
From "Hello World" to understanding how 3 billion devices run Java — master Java basics, JVM architecture, and start building real programs.
⏱️ 4 hrs theory + 3 hrs lab | 💰 Earning Potential: ₹5,000–₹20,000/month | 📝 30 MCQs (Bloom's Mapped)
💼 Jobs: Java Intern (₹15K–25K/month) | Jr Java Dev (₹4–6 LPA) | Interview: TCS NQT / Infosys SP
Opening Hook — Java Runs Your India
☕ 3 Billion Devices. One Language. YOUR Career.
Open the Ola app to book a cab — Java. Transfer ₹500 via BHIM UPI — Java. Book a Tatkal ticket on IRCTC at 10:00 AM while 25 million others do the same — Java. Check your PhonePe balance — Java. Browse Flipkart's Big Billion Days sale — Java backend.
Java doesn't just run on your phone. It powers 3 billion+ devices worldwide — from Android smartphones to ATM machines, from satellite systems to stock trading platforms. Every major Indian IT company — TCS, Infosys, Wipro, HCL — has more Java developers than any other language.
Could YOU have built any of this? After this unit, you'll understand how Java works from source code to execution. You'll write your first programs, understand why Java is called "Write Once, Run Anywhere," and know exactly what happens when you type javac and java. This is where your Java career begins.
Learning Outcomes — Bloom's Taxonomy Mapped
| Bloom's Level | Learning Outcome |
|---|---|
| 🔵 Remember | 1. List Java's key features and trace its history from Oak (1991) to Java 21 (2023) |
| 🔵 Remember | 2. Define JDK, JRE, and JVM and state their individual roles in Java execution |
| 🔵 Understand | 3. Explain Java's platform independence through the bytecode-JVM mechanism |
| 🔵 Understand | 4. Describe the complete compilation and execution pipeline: .java → javac → .class → JVM |
| 🟢 Apply | 5. Write, compile, and execute a Java HelloWorld program using command-line tools |
| 🟢 Apply | 6. Use command-line arguments to pass data into a Java program and access via args[] |
| 🟢 Analyze | 7. Compare Java with C, C++, and Python across paradigm, memory management, speed, and platform dependence |
| 🟢 Analyze | 8. Differentiate between JDK, JRE, and JVM using real-world Indian analogies |
| 🟠 Evaluate | 9. Assess why Java is preferred for enterprise applications in Indian IT companies (TCS, Infosys, Wipro) |
| 🟠 Evaluate | 10. Justify Java's "Write Once, Run Anywhere" claim with technical evidence from the bytecode-JIT pipeline |
| 🟠 Create | 11. Design a multi-feature Java console program that processes command-line arguments |
| 🟠 Create | 12. Build a Student ID Card Printer that accepts name, roll number, and branch via cmd-line args and prints formatted output |
Concept Explanation — Introduction to Java from Scratch
1. History of Java
In 1991, a small team at Sun Microsystems led by James Gosling started "Project Green" — an initiative to build software for consumer electronic devices like set-top boxes and TVs. They needed a language that was platform-independent (worked on any chip), robust, and secure. C++ wasn't cutting it — too many memory bugs, too platform-dependent.
Gosling created a new language and named it "Oak" after an oak tree he could see from his office window. When they discovered "Oak" was already trademarked by another company, the team brainstormed over coffee (literally — Java coffee from Indonesia) and renamed it "Java".
📅 Java Timeline — From Oak to Java 21
1991 — James Gosling starts Project Green at Sun Microsystems. Creates "Oak" language.
1995 — Oak renamed to Java. Released as Java 1.0 with the motto "Write Once, Run Anywhere".
1998 — Java 2 (J2SE 1.2) — introduced Collections framework, Swing GUI.
2004 — Java 5 (Tiger) — Generics, enhanced for-loop, autoboxing, enums. A landmark release.
2010 — Oracle acquires Sun Microsystems for $7.4 billion. Java now under Oracle.
2014 — Java 8 — Lambda expressions, Stream API, functional programming. Most widely used version in Indian IT today.
2021 — Java 17 (LTS) — Sealed classes, pattern matching. Current enterprise standard.
2023 — Java 21 (LTS) — Virtual threads, record patterns. Latest long-term support release.
2. Features of Java
Java became the world's most popular enterprise language because of these key features:
| Feature | What It Means | Indian Analogy |
|---|---|---|
| Object-Oriented (OOP) | Everything is an object. Programs are built using classes and objects. | Like Aadhaar — each person is an "object" with properties (name, DOB) and methods (verify, update) |
| Platform Independent | Java bytecode runs on any OS with a JVM. "Write Once, Run Anywhere." | Like a UPI payment — works on any bank's app, any phone, any OS |
| Robust | Strong type checking, exception handling, garbage collection. Hard to crash. | Like Indian Railways reservation — handles millions of requests without crashing (most of the time!) |
| Secure | No pointers, bytecode verifier, security manager. Built-in protection. | Like Aadhaar biometric verification — multiple layers of security |
| Multithreaded | Can run multiple tasks simultaneously within one program. | Like a chai stall owner — making tea, taking orders, giving change — all at once |
| High Performance | JIT compiler converts bytecode to native code at runtime for speed. | Like Vande Bharat Express — not the fastest globally, but optimised for Indian conditions |
| Distributed | Built-in support for network programming (RMI, sockets). | Like India Post — can send data across networks seamlessly |
Java vs C vs C++ vs Python — Comparison Table
| Feature | Java | C | C++ | Python |
|---|---|---|---|---|
| Paradigm | OOP (pure) | Procedural | OOP + Procedural | Multi-paradigm |
| Platform Dependence | Independent (JVM) | Dependent | Dependent | Independent (Interpreter) |
| Memory Management | Automatic (Garbage Collector) | Manual (malloc/free) | Manual (new/delete) | Automatic |
| Pointers | No | Yes | Yes | No |
| Speed | Fast (JIT compiled) | Fastest | Very Fast | Slower (interpreted) |
| Syntax Complexity | Moderate | Complex | Complex | Simple |
| Use in India | Enterprise, Android, Banking | Embedded, OS | Gaming, System SW | AI/ML, Scripting |
| Indian IT Jobs | Highest demand | Niche | Moderate | Growing fast |
3. Java Program Structure
Every Java program follows a specific structure. Let's break it down piece by piece:
Java // 1. Package declaration (optional) — organises classes into folders package com.eduartha.demo; // 2. Import statement — brings in pre-built classes import java.util.Scanner; // 3. Class declaration — every Java program must have at least one class public class HelloWorld { // 4. Main method — the entry point where execution begins public static void main(String[] args) { // 5. Statements — actual instructions System.out.println("Hello, India! 🇮🇳"); } }
Keyword-by-Keyword Explanation
| Keyword | Meaning | Why It's There |
|---|---|---|
public | Access modifier — visible to all | JVM needs to access main() from outside the class |
static | Belongs to class, not object | JVM calls main() without creating an object |
void | Returns nothing | main() doesn't return any value to the JVM |
main | Method name — entry point | JVM looks specifically for this method name |
String[] args | Array of strings — command-line arguments | Allows passing data when running the program |
System.out.println() | Prints text to console with newline | System = class, out = output stream, println = method |
main() method.
public static void main(String[] args) must be EXACT. If you write public void main() — it compiles but won't run. If you write static public void main(String args[]) — it works! The order of public and static can swap, and String args[] is also valid. But String[] args is the convention.
4. Writing Your First Java Program
Step 1: Write the Code
Open any text editor (Notepad, VS Code, or Notepad++) and type:
Java — HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); System.out.println("Welcome to Java Programming!"); System.out.println("India's #1 Enterprise Language ☕"); } }
Step 2: Save the File
Save as HelloWorld.java — the file name MUST match the public class name exactly (case-sensitive).
Step 3: Compile
Open Command Prompt / Terminal and navigate to the file's folder:
Terminal
javac HelloWorld.java
This creates HelloWorld.class — the bytecode file that the JVM can execute.
Step 4: Run
Terminal
java HelloWorld
HelloWorld, the file must be HelloWorld.java — NOT helloworld.java, not Helloworld.java, not hello.java. Java is case-sensitive. This is the #1 error every beginner makes on Day 1.
java HelloWorld.class. When running, use java HelloWorld (without .class extension). When compiling, use javac HelloWorld.java (with .java extension). Mixing these up causes "Could not find or load main class" error.
5. Command-Line Arguments
Command-line arguments let you pass data to your program when you run it — without using Scanner or hardcoding values. They arrive in the String[] args array.
Java — NamePrinter.java public class NamePrinter { public static void main(String[] args) { System.out.println("Hello, " + args[0] + " from " + args[1] + "!"); System.out.println("Welcome to Java programming."); } }
Terminal
javac NamePrinter.java
java NamePrinter Rahul Mumbai
How it works: When you type java NamePrinter Rahul Mumbai, Java puts "Rahul" in args[0] and "Mumbai" in args[1]. The program name is NOT stored in args (unlike C).
args[0] is the FIRST argument, NOT the program name. In C/C++, argv[0] is the program name. In Java, args[0] is the first user argument. This difference is tested in TCS NQT and Infosys SP exams. If no arguments are passed and you access args[0], you get ArrayIndexOutOfBoundsException.
args.length before accessing arguments. Use: if (args.length < 2) { System.out.println("Usage: java NamePrinter <name> <city>"); return; } — this prevents runtime crashes and is a professional coding practice.
6. JDK vs JRE vs JVM — The Java Trinity
Understanding the difference between JDK, JRE, and JVM is one of the most asked interview and exam questions. Let's break it down with an Indian analogy:
🏭 The Flipkart Warehouse Analogy
Contains everything: compiler (javac), debugger (jdb), documentation tool (javadoc), AND the JRE. It's what developers install. Like a warehouse worker who has packing machines, label printers, scanners, AND a delivery vehicle.
JRE (Java Runtime Environment) = The Delivery VehicleContains the JVM + standard libraries (java.lang, java.util, etc.). It's what end-users install to run Java programs. Like a delivery vehicle that has an engine + GPS + storage space — everything needed to deliver packages, but no packing equipment.
JVM (Java Virtual Machine) = The Engine Inside the VehicleThe core engine that actually executes bytecode. It's platform-specific (different JVM for Windows, Mac, Linux) but runs the SAME bytecode. Like the engine — different engines for diesel vs petrol, but they all move the vehicle.
| Component | Contains | Purpose | Who Needs It? |
|---|---|---|---|
| JDK | JRE + javac + jdb + javadoc + tools | Develop + Run Java programs | Developers |
| JRE | JVM + Libraries + Runtime classes | Run Java programs only | End users |
| JVM | ClassLoader + Bytecode Verifier + JIT + GC | Execute bytecode on specific OS | Part of JRE (not standalone) |
Relationship: JDK ⊃ JRE ⊃ JVM — JDK contains JRE, JRE contains JVM. Think of it as Russian nesting dolls (matryoshka).
7. Bytecode → ClassLoader → JIT Pipeline
Understanding what happens between typing javac and seeing output is crucial. Here's the complete pipeline:
⚙️ The Java Compilation & Execution Pipeline
You write HelloWorld.java — human-readable Java code.
The javac compiler converts .java to bytecode — a .class file containing platform-independent intermediate code.
When you run java HelloWorld, the ClassLoader loads the .class file into memory. It also loads dependent classes (like System, String).
Checks the bytecode for security violations — illegal memory access, type mismatches, stack overflows. This is why Java is considered secure.
Stage 5: JIT (Just-In-Time) CompilerConverts frequently-used bytecode into native machine code for the specific OS. This is why Java is fast despite being "interpreted" — hot code paths are compiled once and reused.
Stage 6: ExecutionThe JVM executes the native machine code. Output appears on your screen.
Pipeline Summary:
Pipeline
HelloWorld.java → javac → HelloWorld.class (bytecode)
↓
ClassLoader
↓
Bytecode Verifier
↓
JIT Compiler
↓
Native Machine Code
↓
EXECUTION ✅
8. Installing Java — Setup Guide
Windows Installation
- Go to
oracle.com/java/technologies/downloads/ - Download JDK 21 (LTS) for Windows x64 Installer
- Run the installer → Next → Next → Install
- Set Environment Variables:
JAVA_HOME=C:\Program Files\Java\jdk-21- Add
%JAVA_HOME%\bintoPATH
- Verify: Open CMD → type
java -versionandjavac -version
Linux (Ubuntu/Debian) Installation
Terminal
sudo apt update
sudo apt install openjdk-21-jdk
java -version
javac -version
IDE Setup
| IDE | Best For | Cost | Download |
|---|---|---|---|
| IntelliJ IDEA Community | Serious Java projects, debugging | Free | jetbrains.com/idea |
| VS Code + Java Extension Pack | Quick scripts, lightweight editing | Free | code.visualstudio.com |
| Eclipse | Enterprise Java, legacy projects | Free | eclipse.org |
9. Your First 5 Java Programs
Program 1: HelloWorld
Java — HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Terminal
javac HelloWorld.java
java HelloWorld
Program 2: NamePrinter (Command-Line Arguments)
Java — NamePrinter.java public class NamePrinter { public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: java NamePrinter <name> <city>"); return; } System.out.println("Name: " + args[0]); System.out.println("City: " + args[1]); System.out.println("Welcome to Java, " + args[0] + " from " + args[1] + "!"); } }
Terminal
javac NamePrinter.java
java NamePrinter Priya Delhi
Program 3: AdderProgram (Sum of Two Numbers via CMD Args)
Java — AdderProgram.java public class AdderProgram { public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: java AdderProgram <num1> <num2>"); return; } int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int sum = a + b; System.out.println("Number 1: " + a); System.out.println("Number 2: " + b); System.out.println("Sum: " + sum); } }
Terminal
javac AdderProgram.java
java AdderProgram 25 17
Integer.parseInt() for int, Double.parseDouble() for double. If the user passes "abc" instead of a number, you'll get NumberFormatException. In professional code, always wrap parsing in try-catch.
Program 4: TypeChecker (Data Types Demo)
Java — TypeChecker.java public class TypeChecker { public static void main(String[] args) { int age = 21; double cgpa = 8.75; char grade = 'A'; boolean isPlaced = true; String name = "Rahul Sharma"; System.out.println("=== Student Profile ==="); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("CGPA: " + cgpa); System.out.println("Grade: " + grade); System.out.println("Placed: " + isPlaced); } }
Terminal
javac TypeChecker.java
java TypeChecker
Program 5: SimpleCalculator (Multi-operation via CMD Args)
Java — SimpleCalculator.java public class SimpleCalculator { public static void main(String[] args) { if (args.length < 3) { System.out.println("Usage: java SimpleCalculator <num1> <operator> <num2>"); System.out.println("Operators: + - * /"); return; } double num1 = Double.parseDouble(args[0]); String op = args[1]; double num2 = Double.parseDouble(args[2]); double result = 0; if (op.equals("+")) result = num1 + num2; else if (op.equals("-")) result = num1 - num2; else if (op.equals("*")) result = num1 * num2; else if (op.equals("/")) { if (num2 == 0) { System.out.println("Error: Division by zero!"); return; } result = num1 / num2; } else { System.out.println("Invalid operator: " + op); return; } System.out.println(num1 + " " + op + " " + num2 + " = " + result); } }
Terminal
javac SimpleCalculator.java
java SimpleCalculator 100 + 250
java SimpleCalculator 500 / 4
% (modulus) and ^ (power using Math.pow()). Add error handling for non-numeric inputs using try-catch.
Learn by Doing — 3-Tier Lab Structure
🟢 Tier 1 — GUIDED TASK: HelloWorld + Command-Line Arguments
Step 1: Verify Java Installation
Open Command Prompt (Windows) or Terminal (Linux/Mac) and type:
Terminal
java -version
javac -version
If you see version numbers, Java is installed. If not, follow the installation guide in Section C.8.
Step 2: Create Your Working Folder
Terminal
mkdir JavaUnit1
cd JavaUnit1
Step 3: Write HelloWorld.java
Open Notepad (or any text editor). Type this EXACTLY:
Java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); System.out.println("I am learning Java!"); System.out.println("This is my first program."); } }
Save as HelloWorld.java in the JavaUnit1 folder. Important: Make sure the file extension is .java, not .java.txt.
Step 4: Compile
Terminal
javac HelloWorld.java
If no errors appear, a file HelloWorld.class has been created. Check with dir (Windows) or ls (Linux).
Step 5: Run
Terminal
java HelloWorld
Step 6: Now Try Command-Line Arguments
Create a new file Greeter.java:
Java public class Greeter { public static void main(String[] args) { System.out.println("Hello, " + args[0] + "!"); System.out.println("You are from " + args[1]); System.out.println("Total arguments: " + args.length); } }
Terminal
javac Greeter.java
java Greeter Ankit Pune
🎉 Congratulations! You've written, compiled, and run your first Java programs with command-line arguments!
🟡 Tier 2 — SEMI-GUIDED TASK: Arithmetic Calculator via CMD Args
Your Mission:
Build a program ArithmeticCalc.java that accepts 2 numbers via command-line arguments and prints their sum, difference, and product.
Expected Output:
Terminal
java ArithmeticCalc 45 18
Hints:
- Parse arguments: Use
Integer.parseInt(args[0])to convert String to int - Check length: Verify
args.length >= 2before accessing args[0] and args[1] - Calculate: Sum = a + b, Difference = a - b, Product = a * b
- Print formatted: Use
System.out.println()for each line
🔴 Tier 3 — OPEN CHALLENGE: Student ID Card Printer
The Brief:
Build a StudentIDCard.java program that accepts name, roll number, and branch via command-line arguments and prints a beautifully formatted student ID card.
Expected Output:
Terminal
java StudentIDCard "Priya Sharma" BCA-2024-042 "Computer Science"
Requirements:
- Accept 3 cmd-line args: name, roll number, branch
- Print a formatted card with box-drawing characters
- Auto-detect current year for "Year" field
- Handle missing arguments gracefully with a usage message
- Add a "Status: ACTIVE" line
\u2554, \u2551, \u255A Unicode characters or simple +---+ ASCII art. Both are accepted in exams.
Problem Set — 4 Categories
Category 1: Syntax & Tracing (5 Problems)
P1. Predict the Output
Java public class Test1 { public static void main(String[] args) { System.out.println("Java" + 10 + 20); System.out.println(10 + 20 + "Java"); } }
Explanation: In line 1, "Java" + 10 concatenates to "Java10", then + 20 gives "Java1020". In line 2, 10 + 20 = 30 (arithmetic first), then + "Java" gives "30Java".
P2. Find the Compilation Error
Java public class Test2 { public static void main(string[] args) { System.out.println("Hello"); } }
Error: string should be String (capital S). Java is case-sensitive. String is a class name and must be capitalised.
P3. Predict the Output
Java public class Test3 { public static void main(String[] args) { System.out.println(args[0]); } }
Run as: java Test3 (no arguments)
Answer: ArrayIndexOutOfBoundsException at runtime. The program compiles fine but crashes because args[] is empty and we're accessing args[0].
P4. Find the Error
Java public class MyProgram { public static void main(String[] args) { System.out.println("Hello") } }
Error: Missing semicolon ; after println("Hello"). Every statement in Java must end with a semicolon.
P5. Predict the Output
Java public class Test5 { public static void main(String[] args) { System.out.print("Hello "); System.out.println("World"); System.out.print("Java "); System.out.print("Rules"); } }
Explanation: print() doesn't add newline, println() does. So "Hello " and "World" are on the same line (println adds newline after), then "Java " and "Rules" are on the next line.
Category 2: Programming Exercises (8 Problems)
Easy P6. Reverse Name Printer
Write a program that accepts first name and last name as cmd args and prints them in reverse order.
Input: java ReverseName Rahul Sharma
Output: Sharma, Rahul
Easy P7. Age Calculator
Accept birth year as a cmd arg. Print the person's age (assume current year = 2025).
Input: java AgeCalc 2003
Output: Your age is: 22 years
Medium P8. Temperature Converter
Accept a temperature in Celsius as a cmd arg. Print it in Fahrenheit and Kelvin.
Formula: F = (C × 9/5) + 32, K = C + 273.15
Input: java TempConverter 37
Output: 37.0°C = 98.6°F = 310.15K
Medium P9. Percentage Calculator
Accept 5 subject marks as cmd args. Calculate total, percentage, and grade (A/B/C/D/F).
Input: java MarkSheet 85 90 78 92 88
Output: Total: 433, Percentage: 86.6%, Grade: A
Medium P10. Word Counter
Accept a sentence (multiple words) as cmd args. Print the number of words (i.e., args.length).
Input: java WordCounter Java is the best language
Output: Word count: 5
Hard P11. Argument Sorter
Accept N numbers as cmd args. Print them in sorted (ascending) order.
Input: java ArgSort 45 12 78 3 56
Output: Sorted: 3 12 45 56 78
Hard P12. Mini Invoice Generator
Accept item name, quantity, and unit price as cmd args. Print a formatted invoice with total and 18% GST.
Input: java Invoice Laptop 2 55000
Output: Item: Laptop, Qty: 2, Price: ₹55,000, Subtotal: ₹1,10,000, GST (18%): ₹19,800, Total: ₹1,29,800
Hard P13. Pattern Printer
Accept a number N as cmd arg. Print a right-angled triangle pattern of stars with N rows.
Input: java Pattern 5
Category 3: Industry Problems (Indian Context)
P14. IRCTC Ticket Printer
Build a program that accepts passenger name, train number, source, destination, and class (SL/3A/2A/1A) as cmd args. Print a formatted railway ticket. Include PNR (generate a random 10-digit number).
P15. Ola Fare Calculator
Build a program that accepts ride type (Mini/Sedan/SUV) and distance (km) as cmd args. Calculate fare using: Mini = ₹7/km, Sedan = ₹10/km, SUV = ₹14/km. Add a base fare of ₹50.
P16. GST Invoice Generator
Build a program for a small Indian shop. Accept product name, quantity, rate, and GST slab (5/12/18/28) as cmd args. Print a GST-compliant invoice with CGST and SGST split equally.
Category 4: Interview Problems
P17. Reverse a String (Without StringBuilder)
Asked at: TCS NQT, Wipro NLTH
Given a string as cmd arg, reverse it without using StringBuilder or StringBuffer.
Brute: Convert to char array, swap from both ends → O(n) time, O(n) space
Optimised: Build reversed string by iterating from end → O(n) time, O(n) space (same complexity but cleaner)
P18. Check Palindrome
Asked at: Infosys SP, Cognizant GenC
Accept a word as cmd arg. Check if it reads the same forwards and backwards.
Brute: Reverse the string and compare → O(n) time
Optimised: Compare chars from both ends, stop at middle → O(n/2) time
P19. Count Vowels and Consonants
Asked at: Capgemini, Accenture
Accept a sentence as cmd args. Count total vowels (a,e,i,o,u) and consonants.
Brute: Check each char against all 5 vowels → O(n×5)
Optimised: Use a Set/String of vowels for O(1) lookup → O(n) time
MCQ Assessment Bank — 30 Questions (Bloom's Mapped)
Remember / Identify (Q1–Q5)
Who is known as the "Father of Java"?
- Dennis Ritchie
- James Gosling
- Bjarne Stroustrup
- Guido van Rossum
What was Java originally called before it was renamed?
- Coffee
- Mocha
- Oak
- Green
JVM stands for:
- Java Variable Machine
- Java Virtual Machine
- Java Verified Module
- Java Visual Manager
Which company currently owns Java?
- Sun Microsystems
- Microsoft
- Oracle
The extension of a compiled Java file (bytecode) is:
- .java
- .exe
- .class
- .obj
Understand / Explain (Q6–Q10)
Why is Java called "platform-independent"?
- Because it doesn't need an operating system
- Because Java bytecode can run on any platform that has a JVM
- Because Java programs don't need compilation
- Because Java works only on Windows
What is the role of the JIT compiler in Java?
- Converts .java to .class files
- Converts bytecode to native machine code at runtime for faster execution
- Checks for syntax errors
- Manages memory allocation
Why does Java not support pointers?
- Because pointers are slow
- For security — pointers allow direct memory access which can be exploited
- Because Java is interpreted
- Because Java uses only integers
Explain the relationship: JDK, JRE, and JVM.
- JVM ⊃ JRE ⊃ JDK
- JDK ⊃ JRE ⊃ JVM
- JRE ⊃ JDK ⊃ JVM
- All three are identical
What happens if you run java HelloWorld.class instead of java HelloWorld?
- It runs normally
- Compilation error
- "Could not find or load main class HelloWorld.class" error
- It runs but with warnings
Apply / Use (Q11–Q15)
What is the output of this code?
public class Test { public static void main(String[] args) { System.out.println("Hello" + 5 + 3); } }
- Hello8
- Hello53
- 8Hello
- Compilation error
What is the output?
public class Test { public static void main(String[] args) { System.out.println(10 + 20 + "Hello" + 5 + 6); } }
- 1020Hello56
- 30Hello56
- 30Hello11
- 36Hello
Given: java MyProg Alpha Beta Gamma — what is args[1]?
- MyProg
- Alpha
- Beta
- Gamma
What is the output?
public class Test { public static void main(String[] args) { int x = Integer.parseInt(args[0]); System.out.println(x * 2); } }
Run as: java Test 15
- 152
- 30
- Compilation error
- Runtime error
Which command correctly compiles and runs a Java program?
- java HelloWorld.java then javac HelloWorld
- javac HelloWorld.java then java HelloWorld
- javac HelloWorld then java HelloWorld.class
- compile HelloWorld.java then run HelloWorld
Analyze / Compare (Q16–Q20)
What will happen if the file is named Hello.java but the class is declared as public class HelloWorld?
- Compiles and runs normally
- Compilation error: class HelloWorld is public, should be declared in HelloWorld.java
- Runtime error
- Warning but runs
Analyze: Which feature makes Java different from C in terms of memory safety?
- Java uses pointers while C doesn't
- Java has automatic garbage collection while C requires manual memory management
- Java is faster than C
- Java is procedural while C is object-oriented
Analyze the following code. Why does it produce different outputs?
System.out.println(5 + 3); // Line 1 System.out.println("5" + 3); // Line 2 System.out.println("5" + "3"); // Line 3
- All produce 8
- Line 1: 8, Line 2: 53, Line 3: 53
- Line 1: 53, Line 2: 8, Line 3: 53
- All produce 53
Compare: Why is JVM platform-dependent but Java is called platform-independent?
- Both JVM and Java are platform-independent
- JVM is platform-dependent because it translates bytecode to OS-specific native code; Java bytecode itself is platform-independent
- JVM is platform-independent; Java is platform-dependent
- Neither is platform-independent
Analyze: What happens inside the JVM when you run java HelloWorld?
- JVM directly reads the .java file
- ClassLoader loads .class → Bytecode Verifier checks → JIT compiles → Executes
- JVM compiles .java to .class first, then runs
- JVM sends the code to a remote server for execution
Evaluate / Justify (Q21–Q25)
A student argues: "Python is easier than Java, so companies should use Python for everything." Evaluate this claim.
- Correct — Python is better for all use cases
- Incorrect — Java is preferred for large-scale enterprise systems due to strong typing, performance, and mature ecosystem
- Correct — syntax simplicity is the only factor
- Incorrect — Java is easier than Python
Evaluate: Is the statement "Java is 100% object-oriented" correct?
- Yes, everything in Java is an object
- No, because Java has primitive data types (int, char, boolean) which are not objects
- Yes, because Java has the Object class
- No, because Java doesn't support inheritance
Evaluate: Why do Indian IT companies (TCS, Infosys, Wipro) prefer Java over other languages for enterprise projects?
- Java is free
- Java's platform independence, strong community, enterprise frameworks (Spring), and long-term support make it reliable for large-scale projects
- Java is the newest language
- Java has the simplest syntax
A program uses args[0] without checking args.length. Evaluate the code quality.
- Good — it's concise
- Bad — it will crash with ArrayIndexOutOfBoundsException if no arguments are provided
- Good — JVM handles it automatically
- Bad — but only on Linux, not Windows
Evaluate: Can a Java .class file generated on Windows run on Linux without recompilation?
- No, it needs recompilation on Linux
- Yes, because bytecode is platform-independent — only a Linux JVM is needed
- Yes, but only if Linux has the same JDK version
- No, because Windows and Linux use different file systems
Create / Design (Q26–Q30)
An Indian startup wants to build a cross-platform mobile app that also has a strong backend. Which Java technology stack would you recommend?
- Java + Spring Boot (backend) + Android SDK (mobile)
- Java + Django (backend) + Flutter (mobile)
- Java + Node.js (backend) + React Native (mobile)
- Java + Flask (backend) + Kotlin (mobile)
Design a command-line program for an Indian college that takes student name, roll number, and 3 marks as cmd args and prints a marksheet. Which approach is best?
- Accept all data as args[0] to args[4], validate, calculate percentage, print formatted output
- Hardcode all values inside the program
- Accept only the name, skip the rest
- Use a GUI instead of command-line
A bank in India (like SBI) needs a Java program that verifies if a given Aadhaar number format is valid (12 digits). Which validation logic would you design?
- Check if args[0].length() == 12 and all characters are digits
- Just check if args[0] is not null
- Convert to int and check range
- No validation needed
Design a Java program for Ola that calculates fare. It takes ride_type and distance as cmd args. Mini=₹7/km, Sedan=₹10/km, SUV=₹14/km with ₹50 base fare. What's the correct structure?
- Parse args, use if-else for ride type, calculate fare = base + rate × distance, print result
- Hardcode distance as 10km for all rides
- Only support one ride type
- Use Scanner instead of cmd args
An Infosys team needs a Java utility that takes a date of birth (DD-MM-YYYY format) as a cmd arg and calculates age. What design considerations are needed?
- Just subtract years — no other considerations
- Parse the date string, extract day/month/year, handle current date calculation, account for whether birthday has occurred this year, validate format
- Use a database to store ages
- Ask the user to input age directly
Short Answer Questions (8 Questions)
Definition-Type (3 Questions)
Q1. Define JDK and list its main components.
Answer: JDK (Java Development Kit) is a software development environment used for developing Java applications. It contains: (1) Java compiler (javac) — converts .java to .class, (2) Java Runtime Environment (JRE) — for executing programs, (3) Java debugger (jdb) — for debugging, (4) Javadoc — for generating documentation, (5) Other tools like jar, jps, jstack. The JDK is required by developers; end-users only need the JRE.
Q2. What is bytecode in Java?
Answer: Bytecode is the intermediate, platform-independent code generated by the Java compiler (javac) from .java source files. It is stored in .class files. Bytecode is not native machine code — it cannot be directly executed by the OS. Instead, it is executed by the JVM, which translates it into platform-specific native code using the JIT compiler. This is the key mechanism behind Java's "Write Once, Run Anywhere" philosophy.
Q3. Define the term "Platform Independence" in the context of Java.
Answer: Platform independence means a Java program compiled on one operating system (e.g., Windows) can run on any other operating system (e.g., Linux, macOS) without modification or recompilation. This is achieved because Java source code is compiled into bytecode (.class files), which is platform-neutral. The platform-specific JVM installed on each OS interprets/compiles this bytecode into native instructions for that OS.
Short Code-Type (3 Questions)
Q4. Write a Java program that prints "Hello, [name]!" where name is passed as a command-line argument.
Java public class Hello { public static void main(String[] args) { if (args.length > 0) { System.out.println("Hello, " + args[0] + "!"); } else { System.out.println("Hello, World!"); } } }
Q5. Write a Java program that prints the number of command-line arguments passed.
Java public class ArgCounter { public static void main(String[] args) { System.out.println("Number of arguments: " + args.length); for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] = " + args[i]); } } }
Q6. Write the smallest possible Java program that prints "Java" to the console.
Java class J{public static void main(String[]a){System.out.print("Java");}}
Comparison-Type (2 Questions)
Q7. Compare System.out.print() and System.out.println().
| Feature | print() | println() |
|---|---|---|
| Newline | Does NOT add newline after output | Adds newline (\n) after output |
| Cursor Position | Cursor stays on same line | Cursor moves to next line |
| Example | print("A"); print("B"); → AB | println("A"); println("B"); → A\nB |
| Use Case | When you want to print multiple things on one line | When each output should be on its own line |
Q8. Compare Java's compilation process with Python's execution process.
| Aspect | Java | Python |
|---|---|---|
| Type | Compiled + Interpreted (hybrid) | Interpreted |
| Step 1 | javac compiles .java → .class (bytecode) | Python interpreter reads .py directly |
| Step 2 | JVM interprets/JIT-compiles bytecode | Interprets line by line (creates .pyc internally) |
| Error Detection | Compile-time + Runtime | Mostly Runtime |
| Speed | Faster (JIT optimization) | Slower (pure interpretation) |
| Deployment | Distribute .class files | Distribute .py source files |
Long Answer & Case Studies
📘 Case Study 1: Academic (10-Mark Question)
Explain the complete Java program execution process from source code to output, with a diagram description and examples.
Expected Answer Structure:
- Source Code: Developer writes .java file (e.g., HelloWorld.java) using any text editor or IDE.
- Compilation:
javac HelloWorld.java→ Java compiler checks syntax, performs type checking, and generates bytecode →HelloWorld.class - ClassLoader: When
java HelloWorldis executed, the ClassLoader subsystem loads the .class file into JVM memory. It also loads dependent classes (java.lang.System, java.lang.String, etc.) - Bytecode Verifier: Verifies that the bytecode is valid, doesn't violate security constraints, doesn't perform illegal type casts, and doesn't overflow the stack.
- Interpreter + JIT: The interpreter executes bytecode line by line. The JIT (Just-In-Time) compiler identifies frequently executed code ("hot spots") and compiles them to native machine code for direct CPU execution — dramatically improving performance.
- Execution: The execution engine runs the native code. Output is produced via System.out.
Diagram: .java → javac → .class → ClassLoader → Bytecode Verifier → JIT/Interpreter → Native Code → CPU → Output
Why this matters: Understanding this pipeline explains why Java is both platform-independent (bytecode) and fast (JIT compilation).
🏢 Case Study 2: Indian Industry — Infosys Employee ID Generator
Scenario:
Infosys Pune office needs a Java-based Employee ID Generator for their onboarding process. The program should:
- Accept employee name, department (BFS/ECS/HLS/RET), joining year, and serial number as cmd args
- Generate an Employee ID in format:
INF-[DEPT]-[YEAR]-[SERIAL] - Print a formatted employee card
Sample:
Terminal
java EmployeeIDGen "Ravi Kumar" BFS 2024 0042
Discussion Questions:
- How would you validate the department code (only BFS/ECS/HLS/RET allowed)?
- How would you ensure the serial number is always 4 digits (e.g., "42" → "0042")?
- How would you extend this to support multiple employees? (Hint: loop + file reading — covered in later units)
🎨 Case Study 3: Design — Console App Architecture
Design a Java console application for a college library management system.
Requirements (Unit 1 scope — no OOP, just main method):
- Accept operation type as first cmd arg: ADD, SEARCH, LIST
- For ADD: accept book name and author as additional args
- For SEARCH: accept search term as additional arg
- Print appropriate messages for each operation
Design Considerations:
- How do you use
args[0]to determine which operation to perform? (if-else or switch) - How do you handle variable number of arguments for different operations?
- How do you display user-friendly error messages for invalid operations?
- What's the limitation of this approach? (No data persistence — every run starts fresh. This is solved with files/databases in later units.)
Lab Programs
📋 Lab Programs Note
Lab programs for the Programming in Java course are mapped in Units 6–12. Unit 1 covers foundational theory — Java history, features, program structure, JVM architecture, and command-line compilation. The hands-on lab programs (implementing data structures, file handling, GUI, networking, etc.) begin from Unit 6 onwards.
However, you should complete the 3-Tier Labs in Section D to build practical command-line Java skills. These labs are your foundation for all future lab programs.
Recommended Practice:
- Write and compile at least 10 programs using
javacandjavacommands - Practice all 5 programs from Section C.9
- Complete the Tier 3 Student ID Card challenge
- Set up IntelliJ IDEA and create your first project
Industry Spotlight — A Day in the Life
👨💻 Ankit Sharma, 26 — Java Developer at Infosys, Pune
Background: B.Tech (IT) from Pune University. No coding before college. Learned Java in 2nd year through college curriculum + YouTube. Built 3 projects during internship. Cracked TCS NQT (qualified) and Infosys SP (selected). Joined Infosys in July 2023.
A Typical Day:
9:00 AM — Morning standup with the banking project team. Discuss yesterday's progress and today's tasks.
10:00 AM — Code review of a teammate's pull request. Check for coding standards, null checks, and proper exception handling.
11:30 AM — Develop a new REST API endpoint using Spring Boot. Write the controller, service, and repository layers.
1:00 PM — Lunch at Infosys Hinjewadi campus cafeteria. Chat with friends about the upcoming hackathon.
2:00 PM — Debug a production issue — a NullPointerException in the payment module. Use IntelliJ's debugger to trace the bug.
4:00 PM — Write unit tests using JUnit. Push code to Git. Update Jira ticket status.
5:30 PM — Learning hour — studying microservices architecture on Infosys's internal learning platform (Lex).
| Detail | Info |
|---|---|
| Tools Used Daily | Java 17, IntelliJ IDEA, Maven, Git, Spring Boot, MySQL, Postman, Jira |
| Entry Salary (2024) | ₹3.6–6 LPA (Infosys Power Programmer: ₹6.5 LPA) |
| Mid-Level (3–5 yrs) | ₹8–15 LPA |
| Senior (7+ yrs) | ₹18–35 LPA |
| Companies Hiring Java Devs | TCS, Infosys, Wipro, HCL, Cognizant, Capgemini, Accenture, Tech Mahindra, L&T Infotech |
Earn With It — Freelance & Income Roadmap
💰 Your Earning Path After This Unit
What you can do right now:
• Teach Java basics on Chegg India — ₹300–600/hr answering student questions
• Create YouTube tutorials — "Java for Beginners" series → ₹5,000–₹20,000/month (after 1K subs)
• Tutor college juniors — ₹200–500/hr for Java fundamentals coaching
• Answer on Vedantu — ₹150–400/session for doubt clearing
• Write Java programming articles on Medium/Hashnode — build audience for future earnings
| Platform | Best For | Typical Rate |
|---|---|---|
| Chegg India | Answering Java/Programming questions | ₹300–600/hr (per question basis) |
| Vedantu | Live tutoring for school/college students | ₹200–500/session |
| YouTube | Tutorial creation — long-term passive income | ₹5K–₹20K/month (with consistency) |
| Internshala | Java internships and mini-projects | ₹5,000–₹15,000/month |
| Fiverr | Small Java coding tasks for global clients | $5–$50/task (₹400–₹4,000) |
Chapter Summary — Tweet-Sized Bullets
☕ Unit 1 in 60 Seconds
🐣 Java was born as Oak (1991) at Sun Microsystems → renamed Java after Indonesian coffee → now runs on 3 billion+ devices.
👨💻 James Gosling = Father of Java. Sun → acquired by Oracle (2010). Latest: Java 21 LTS.
⭐ Key Features: OOP, Platform-Independent, Robust, Secure, Multithreaded, High-Performance.
🔧 JDK ⊃ JRE ⊃ JVM — Toolkit contains Vehicle contains Engine.
📝 Java source (.java) → javac → Bytecode (.class) → JVM → Runs EVERYWHERE.
🚀 public static void main(String[] args) — the ONE method JVM looks for to start your program.
🖨️ System.out.println() = your first best friend in Java. Prints text + newline.
📦 args[0] = first command-line argument. NOT the program name (unlike C's argv[0])!
📁 File name MUST match public class name. HelloWorld.java for public class HelloWorld.
🇮🇳 Java is India's #1 enterprise language — TCS, Infosys, Wipro, HDFC, SBI all run on Java backends.
💡 JVM is platform-dependent. Bytecode is platform-independent. That's how WORA works.
⚡ JIT compiler = why Java is fast. Converts hot bytecode → native code at runtime.
Code Tweet — Smallest HelloWorld
Java — 73 characters class Hi{public static void main(String[]a){System.out.println("☕");}}
Java Checkpoint — Self-Assessment
| Topic | Tool / Practice | Portfolio Piece | Earn-Ready? |
|---|---|---|---|
| Java History & Features | Conceptual | — | ✅ Yes — can discuss in interviews |
| Java vs C/C++/Python | Comparison Table | — | ✅ Yes — TCS NQT/Infosys SP ready |
| Program Structure | Text Editor + javac/java | HelloWorld.java | ✅ Yes — basic teaching ability |
| HelloWorld Compilation | CMD / Terminal | Compiled & ran first program | ✅ Yes — can teach on Chegg/Vedantu |
| Command-Line Arguments | CMD args + Integer.parseInt | NamePrinter + AdderProgram | ✅ Yes — lab exam ready |
| JDK / JRE / JVM | Conceptual + Diagram | — | ✅ Yes — interview favourite question |
| Bytecode & JIT Pipeline | Conceptual | — | ✅ Yes — differentiates you in interviews |
| First 5 Programs | Java + CMD | 5 working Java programs | ✅ Yes — foundation for all future labs |
✅ Unit 1 complete. MCQs: 30. Ready for Unit 2: Data Types & Variables!
[QR: Link to EduArtha video tutorial — Introduction to Java]