Unit 1: Introduction to Java and OOP Concept [4 Hours]
Java is a general-purpose, object-oriented programming language designed to work across platforms without modification. This unit covers the origins and defining characteristics of Java, the three-layer architecture that makes it platform-independent, how it compares to procedural programming, and the mechanics of writing, compiling, and running a Java program. It also covers arrays — one of Java's most frequently tested data structures.
Tested Topics
- Command-line arguments — 2x (2025, 2023)
- Jagged arrays — 1x (2022)
- Java Buzzwords / features — 1x (2023)
- Multi-dimensional arrays / matrix operations — 1x (2024)
1.1 History, Feature or Buzzwords of Java
Definition
Java is a high-level, class-based, object-oriented programming language developed by James Gosling at Sun Microsystems and released in 1995. It was designed with a single guiding promise: write once, run anywhere.
Before Java, if you wrote a program on Windows, you had to rewrite large portions of it to run on Linux or macOS. Java broke that constraint. You write one program, compile it once, and it runs on any machine that has a Java Virtual Machine (JVM) installed — without changing a single line of code.
Detailed Explanation
A Brief History
Java originated from a project called Oak, started around 1991 at Sun Microsystems. The team, led by James Gosling, was originally trying to build software for interactive television and embedded devices. Oak was later renamed Java (after Java coffee) and repositioned as an internet-friendly language. The first public release came in 1995. Sun Microsystems was later acquired by Oracle Corporation in 2010, and Oracle now maintains Java.
Java Buzzwords (Features)
Sun Microsystems described Java through eleven buzzwords. Each one represents a deliberate design decision. These are frequently called Java Buzzwords or Java Features.
| Buzzword | What It Means |
|---|---|
| Simple | Java eliminates complex features found in C/C++ such as explicit pointer manipulation, operator overloading, and multiple inheritance. The syntax is clean and close to C, making it relatively easy to learn. |
| Object-Oriented | Everything in Java (except primitive types) is an object. Programs are built by creating objects, defining their properties, and making them interact. |
| Platform-Independent | Java source code compiles into bytecode, not machine code. Bytecode runs on any device that has a Java Virtual Machine (JVM), making Java truly platform-independent. |
| Secure | Java runs inside the JVM, which acts as a sandbox. It has no explicit pointers and enforces access controls, making it difficult for programs to corrupt memory or access unauthorized data. |
| Robust | Java uses strong type-checking at compile time, exception handling for runtime errors, and garbage collection to prevent memory leaks. These features make programs reliable and crash-resistant. |
| Architecture-Neutral | Java bytecode has a fixed size for data types (e.g., int is always 32 bits) regardless of the hardware architecture. A Java int is the same on a 32-bit and a 64-bit machine. |
| Portable | Since Java is both platform-independent and architecture-neutral, the same compiled bytecode can be physically moved to and run on any platform without recompilation. |
| Interpreted | The JVM interprets (executes line by line) the bytecode at runtime. This allows dynamic loading of code and enables platform independence. |
| High Performance | Java uses Just-In-Time (JIT) compilation, which compiles frequently-used bytecode into native machine code at runtime, significantly speeding up execution. |
| Multithreaded | Java has built-in support for multithreading — running multiple tasks simultaneously within the same program. This is valuable for applications like web servers and GUI programs. |
| Dynamic | Java can load classes dynamically at runtime as they are needed, rather than loading all code at startup. This makes large applications more flexible and memory-efficient. |
Memory Hook
To remember the eleven buzzwords: S-O-P-S-R-A-P-I-H-M-D — Some Old Programmers Still Remember All Principles In High-level Multithreaded Design. (Simple, Object-Oriented, Platform-Independent, Secure, Robust, Architecture-Neutral, Portable, Interpreted, High-Performance, Multithreaded, Dynamic)
Summary
- Java was created by James Gosling at Sun Microsystems in 1995 from a project originally called Oak.
- The core promise is write once, run anywhere — achieved through bytecode and the JVM.
- The eleven buzzwords describe Java's design philosophy: simple, object-oriented, platform-independent, secure, robust, architecture-neutral, portable, interpreted, high-performance, multithreaded, and dynamic.
- The most testable buzzwords are platform-independent (bytecode + JVM), secure (sandbox, no pointers), robust (exception handling, garbage collection), and multithreaded.
Test Yourself
- What is Java? Who developed it and when?
- What is java Buzzwords? Write a java program to find simple interest. Use command line argument to take input. (2023)
- List the eleven Java buzzwords and briefly explain any five.
- What does "platform-independent" mean in the context of Java?
Hints:
- Java is a high-level, object-oriented language developed by James Gosling at Sun Microsystems in 1995. Originally called Oak.
- Java buzzwords are the eleven features that describe Java's design: Simple, Object-Oriented, Platform-Independent, Secure, Robust, Architecture-Neutral, Portable, Interpreted, High-Performance, Multithreaded, Dynamic. For the simple interest program using command-line arguments, see section 1.7 below.
- List all eleven. For explanation, prioritize: Platform-Independent (bytecode runs on any JVM), Secure (no pointers, sandbox), Robust (type-checking, exception handling, garbage collection), Multithreaded (built-in concurrency support), Object-Oriented (everything is an object).
- Platform independence means a compiled Java program (bytecode) runs on any machine with a JVM installed — no recompilation needed. The bytecode acts as an intermediate representation that any JVM can interpret.
1.2 Java Architecture: JVM, JDK and JRE
Definition
Java's execution model rests on three interconnected components: the Java Development Kit (JDK), the Java Runtime Environment (JRE), and the Java Virtual Machine (JVM). Together they form the infrastructure that makes Java platform-independent.
Picture three concentric circles: JVM is the innermost (the actual execution engine), JRE wraps around it (everything needed to run Java programs), and JDK is the outermost (everything needed to write, compile, and run Java programs).
Detailed Explanation
Java Virtual Machine (JVM)
The Java Virtual Machine (JVM) is an abstract computing machine that executes Java bytecode. It is the core that makes Java platform-independent.
When you compile a Java source file, the compiler does not produce machine code. It produces bytecode — a compact, platform-neutral intermediate format stored in .class files. The JVM reads that bytecode and translates it into the native machine instructions of whatever hardware and operating system it is running on.
Key JVM responsibilities:
- Class loading: loads
.classfiles into memory as they are needed. - Bytecode verification: checks bytecode for safety violations before execution.
- Execution: interprets bytecode, and uses Just-In-Time (JIT) compilation to convert hot code paths into native machine code for speed.
- Garbage collection: automatically reclaims memory from objects that are no longer reachable, preventing memory leaks.
- Security enforcement: runs programs in a sandbox, preventing unauthorized memory access.
The JVM is platform-specific — there is a different JVM for Windows, Linux, and macOS. But because every JVM accepts the same bytecode standard, the same .class file runs on all of them.
Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) is the software package needed to run a Java application. It includes:
- The JVM (the execution engine)
- The Java Class Library — a large collection of pre-written classes for I/O, networking, data structures, GUI components, and more (e.g.,
java.lang,java.util,java.io) - Supporting configuration files and property settings
If you only want to run a Java application, the JRE is sufficient. You do not need the full JDK.
Java Development Kit (JDK)
The Java Development Kit (JDK) is the complete development package. It includes the JRE (and therefore the JVM) plus the tools needed to write and compile Java programs:
- javac: the Java compiler, which converts
.javasource files into.classbytecode files. - java: the launcher that starts the JVM to run a compiled program.
- javadoc: generates HTML documentation from source code comments.
- jar: packages multiple class files into a single archive file.
- jdb: the Java debugger.
Developers need the JDK. End users who only run Java applications need only the JRE.
Relationship and How They Work Together
JDK contains JRE contains JVM. Here is the complete flow from source code to output:
Write Hello.java → javac Hello.java (JDK compiler) → produces Hello.class (bytecode) → java Hello (JVM in JRE) → JVM interprets/compiles bytecode → output on screen
| Component | Contains | Used By | Purpose |
|---|---|---|---|
| JVM | Execution engine, GC, JIT | Developers + End Users | Execute bytecode on host hardware |
| JRE | JVM + Class Libraries | End Users | Run Java applications |
| JDK | JRE + javac + dev tools | Developers | Develop, compile, and run Java programs |
Common Mistake
Students frequently say "install Java" without specifying which component. If you want to write Java programs, you install the JDK. If you only want to run an existing program, the JRE is enough. The JVM is not installed separately — it comes bundled inside both the JDK and JRE.
Summary
- JVM is the execution engine that converts bytecode to native machine instructions; it is platform-specific but bytecode-compatible.
- JRE = JVM + Java Class Library; it is the minimum needed to run a Java application.
- JDK = JRE + compiler (javac) + development tools; developers must install the JDK.
- The compilation flow is: .java source → javac → .class bytecode → JVM → native execution.
Test Yourself
- What is JVM? Explain its role in achieving platform independence.
- Differentiate between JDK, JRE, and JVM with a diagram or table.
- What is bytecode? How is it different from machine code?
Hints:
- JVM (Java Virtual Machine) is an abstract machine that interprets Java bytecode and translates it into platform-specific native instructions. Platform independence is achieved because bytecode is universal — any JVM on any OS can execute the same .class file.
- JDK ⊃ JRE ⊃ JVM. JVM executes bytecode. JRE adds the standard class libraries. JDK adds the compiler and developer tools (javac, javadoc, jar). Developer installs JDK; end-user installs JRE.
- Bytecode is platform-neutral intermediate code produced by javac. It is not machine code (which is hardware-specific binary instructions). Bytecode runs on the JVM, not directly on the CPU.
1.3 Procedural-oriented Vs. Object-oriented Programming
Definition
Procedural-Oriented Programming (POP) organizes a program as a sequence of procedures (functions) that operate on shared data. Object-Oriented Programming (OOP) organizes a program as a collection of objects, each combining its own data and the functions that operate on that data.
In procedural programming, data and the actions that change it live separately. In object-oriented programming, they live together inside an object. This shift in thinking is what separates C from Java.
Detailed Explanation
Procedural-Oriented Programming (POP)
In POP, the program is divided into functions. Data is defined globally or passed between functions. The functions execute in a top-to-bottom sequence. C is the most prominent example.
Problems with POP at scale:
- Global data can be accidentally modified by any function, causing bugs that are hard to trace.
- Code reuse requires copying and adapting functions — changes in one copy don't propagate.
- As programs grow, managing shared state becomes chaotic.
Object-Oriented Programming (OOP)
In OOP, programs are built from objects. An object is an instance of a class. A class defines a blueprint: what data (fields/attributes) an object holds and what it can do (methods). Objects communicate by calling each other's methods.
OOP is built on four pillars:
- Encapsulation: data and methods are bundled inside an object. Internal state is hidden from outside access (controlled via access modifiers like
private). This prevents accidental modification. - Inheritance: a new class (child) can acquire properties and methods of an existing class (parent) without rewriting them. Promotes code reuse.
- Polymorphism: the same method name can behave differently depending on the object calling it. For example, a
draw()method on a Circle draws a circle; on a Square, it draws a square. - Abstraction: complex implementation details are hidden; only the necessary interface is exposed to the user.
| Feature | Procedural-Oriented Programming | Object-Oriented Programming |
|---|---|---|
| Basic unit | Function / Procedure | Object (instance of a class) |
| Data access | Data is shared globally; any function can access it | Data is encapsulated inside objects; accessed via methods |
| Program flow | Top-down sequence of function calls | Objects interact by passing messages (calling methods) |
| Reusability | Limited; code reuse requires copying functions | High; via inheritance and composition |
| Security | Low; global data is accessible everywhere | High; data hiding via encapsulation |
| Problem-solving approach | Focuses on how to do something (algorithm first) | Focuses on what to model (entities and their interactions) |
| Examples | C, Pascal, COBOL | Java, C++, Python, Kotlin |
Summary
- POP builds programs as sequences of functions; data is shared and often global.
- OOP builds programs from objects that combine data and behavior, improving security and reusability.
- OOP's four pillars are encapsulation, inheritance, polymorphism, and abstraction.
- Java is purely object-oriented (except for primitive types), which is why it is more secure and maintainable than C for large systems.
Test Yourself
- Compare procedural-oriented and object-oriented programming with examples.
- What are the four pillars of OOP? Define each briefly.
- Why is OOP considered better than POP for large software projects?
Hints:
- POP: program = sequence of functions + shared data (C). OOP: program = collection of objects, each with own data + methods (Java). Key difference: data hiding. In OOP, only the object's methods can change its data.
- Encapsulation (data + behavior inside object, hidden from outside), Inheritance (child class reuses parent class code), Polymorphism (same method name, different behavior by object type), Abstraction (hide complexity, expose only necessary interface).
- Large systems have many data entities. POP's global data becomes unmanageable: any function can break any data. OOP's encapsulation protects data, inheritance avoids code duplication, polymorphism makes the system extensible without rewriting existing code.
1.4 Setting up Java Environment and IDE in Local Machine
Definition
Setting up the Java environment means installing the Java Development Kit (JDK) on your machine and configuring the system so the compiler and runtime are accessible from the command line. An Integrated Development Environment (IDE) provides a graphical editor, compiler, debugger, and project manager in one tool.
Without this setup, you cannot compile or run Java programs. Once done, the same setup handles every Java project you create afterward.
Detailed Explanation
Step 1 — Download and Install the JDK
Download the JDK from the official Oracle website or adopt an open-source distribution (OpenJDK). Run the installer and follow the prompts. The JDK installs to a directory such as C:\Program Files\Java\jdk-17 on Windows or /usr/lib/jvm/java-17 on Linux.
Step 2 — Set the JAVA_HOME Environment Variable
The JAVA_HOME environment variable tells the operating system and other tools where the JDK is installed. Set it to the JDK root directory (e.g., C:\Program Files\Java\jdk-17). Many build tools (Maven, Gradle) and IDEs rely on this variable.
Step 3 — Update the PATH Variable
Add the JDK's bin directory to your system's PATH environment variable. This makes javac and java accessible from any command-prompt location, so you can compile and run programs without navigating to the JDK directory each time.
Step 4 — Verify the Installation
Open a terminal or command prompt and run:
java -version
javac -versionBoth commands should print a version number (e.g., java version "17.0.1"). If they do, the environment is correctly configured.
Common IDEs for Java
| IDE | Notes |
|---|---|
| IntelliJ IDEA | Most popular professional IDE; powerful auto-complete and refactoring. Community edition is free. |
| Eclipse | Free, open-source; widely used in academic settings and enterprise development. |
| NetBeans | Free, Apache-maintained; simpler interface, good for beginners. |
| VS Code | Lightweight editor; requires Java Extension Pack for full Java support. |
Summary
- Environment setup requires installing the JDK, setting JAVA_HOME, and adding the JDK bin directory to PATH.
- Verify with
java -versionandjavac -versionin the terminal. - IDEs (IntelliJ IDEA, Eclipse, NetBeans) simplify development with editing, compilation, and debugging in one interface.
- The setup is done once per machine and works for all Java projects thereafter.
1.5 Sample Java Programs
Definition
A Java program is a set of instructions written in Java syntax, organized into classes and methods, compiled into bytecode, and executed by the JVM. Every executable Java program must have at least one class containing a main method — the entry point.
Detailed Explanation
Anatomy of a Java Program
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Breaking down each component:
public class HelloWorld— declares a class namedHelloWorld. The filename must match the class name exactly (case-sensitive):HelloWorld.java.public static void main(String[] args)— the entry point.public: accessible from outside the class.static: belongs to the class itself, not an object — the JVM calls it without creating an instance.void: returns nothing.String[] args: array of strings passed as command-line arguments.System.out.println(...)— prints a line to the standard output (the console).
Sample Program 2 — Adding Two Numbers
public class AddNumbers {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}Summary
- Every Java program is enclosed in a class. The class name must match the filename.
- The
mainmethod is the entry point:public static void main(String[] args). System.out.println()prints to the console with a newline;System.out.print()prints without.- Java is case-sensitive:
Mainandmainare different identifiers.
1.6 Compiling and Running a Java Program
Definition
Compilation converts a Java source file (.java) into bytecode (.class) using the javac compiler. Running a Java program means launching the JVM with java to execute that bytecode.
Detailed Explanation
The Two-Step Process
Step 1 — Compile:
javac HelloWorld.javaIf there are no errors, this produces HelloWorld.class in the same directory. If there are errors, the compiler prints them with line numbers; no .class file is created.
Step 2 — Run:
java HelloWorldNote: do not include .class when running — pass only the class name. The JVM locates HelloWorld.class in the current directory and begins execution at main.
Full Execution Flow
Write HelloWorld.java → run javac HelloWorld.java → JDK compiler produces HelloWorld.class (bytecode) → run java HelloWorld → JVM loads class, verifies bytecode, executes main → output appears on screen
Common Mistake
Two frequent errors beginners encounter: (1) typing java HelloWorld.class — the .class extension must be omitted; (2) a filename mismatch — if the file is named helloworld.java but the class is HelloWorld, the compiler will reject it. Java file names are case-sensitive.
Summary
- Compilation:
javac FileName.java→ producesFileName.class. - Execution:
java ClassName(no extension) → JVM runs themainmethod. - The JVM goes through class loading → bytecode verification → execution.
- Compilation errors are caught by the compiler at compile time; runtime errors are caught by the JVM during execution.
1.7 Command-line Arguments
Definition
Command-line arguments are values passed to a Java program at the time of execution, directly on the command line after the class name. They are received by the main method as a String array: String[] args.
Instead of embedding input values directly in the code, command-line arguments let you pass different values each time you run the program — without modifying or recompiling it. Run the same class with different numbers and it produces different results.
Detailed Explanation
How Command-line Arguments Work
When you run a Java program, the JVM splits everything typed after the class name into separate strings and places them into the args array.
java MyProgram hello 42 NepalInside main:
args[0]="hello"args[1]="42"args[2]="Nepal"
All arguments arrive as Strings. If you need a number, you must parse it: Integer.parseInt(args[0]) converts a String to an int; Double.parseDouble(args[0]) converts to a double.
Program: Sum of Two Numbers Using Command-line Arguments
This program demonstrates the concept asked directly in past exam questions:
// SumArgs.java
public class SumArgs {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Compile and run:
javac SumArgs.java
java SumArgs 15 25Output: Sum = 40
Program: Simple Interest Using Command-line Arguments (2023 Exam Question)
Simple Interest formula: SI = (P × R × T) / 100 where P = Principal, R = Rate of interest (%), T = Time (years).
// SimpleInterest.java
public class SimpleInterest {
public static void main(String[] args) {
double principal = Double.parseDouble(args[0]);
double rate = Double.parseDouble(args[1]);
double time = Double.parseDouble(args[2]);
double si = (principal * rate * time) / 100;
System.out.println("Simple Interest = " + si);
}
}
Compile and run:
javac SimpleInterest.java
java SimpleInterest 10000 5 3Output: Simple Interest = 1500.0
Explanation of the run: Principal = 10000, Rate = 5%, Time = 3 years. SI = (10000 × 5 × 3) / 100 = 1500.
Checking the Number of Arguments
It is good practice to verify that the correct number of arguments was passed before accessing them, to avoid an ArrayIndexOutOfBoundsException:
if (args.length != 2) {
System.out.println("Usage: java SumArgs <num1> <num2>");
return;
}Summary
- Command-line arguments are passed after the class name at runtime:
java ClassName arg1 arg2. - They are received in
String[] args;args[0]is the first argument. - Numeric arguments must be parsed:
Integer.parseInt()for int,Double.parseDouble()for double. - They allow the same compiled program to run with different inputs without recompilation.
Test Yourself
- What is command-line arguments? Write a program to accept two numbers and display their sum using command-line arguments. (2025)
- What is java Buzzwords? Write a java program to find simple interest. Use command line argument to take input. (2023)
- What happens if you pass fewer arguments than the program expects?
- Why must numeric command-line arguments be parsed before arithmetic operations?
Hints:
- Command-line arguments are values passed after the class name at runtime; received in
String[] args. Sum program: parseargs[0]andargs[1]withInteger.parseInt(), add, print. See program above. - Java Buzzwords are the eleven design features of Java (Simple, OOP, Platform-Independent, Secure, Robust, Architecture-Neutral, Portable, Interpreted, High-Performance, Multithreaded, Dynamic). Simple Interest program: parse principal, rate, time from args[0], args[1], args[2]; apply SI = (P×R×T)/100. See program above.
- If fewer arguments are passed than the program expects, accessing a missing index (e.g.,
args[1]when only one was passed) throwsArrayIndexOutOfBoundsExceptionat runtime and the program crashes. - All command-line arguments arrive as Strings. Adding two Strings with
+concatenates them ("15" + "25" = "1525"), not adds them numerically. You must convert to int or double first usingInteger.parseInt()orDouble.parseDouble().
1.8 Scanner Class for Input
Definition
The Scanner class, found in the java.util package, provides methods to read input from various sources — most commonly the keyboard (standard input, System.in). It parses the input stream into tokens and converts them to the desired data type.
While command-line arguments pass values before the program runs, Scanner reads values interactively while the program is running — prompting the user and waiting for their response.
Detailed Explanation
Importing and Creating a Scanner
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // connect Scanner to keyboard
System.out.print("Enter a number: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
sc.close(); // release the resource
}
}Key Scanner Methods
| Method | Reads | Example |
|---|---|---|
nextInt() | An integer | int n = sc.nextInt(); |
nextDouble() | A double | double d = sc.nextDouble(); |
nextLine() | An entire line (String) | String s = sc.nextLine(); |
next() | One word (whitespace-delimited token) | String w = sc.next(); |
nextLong() | A long integer | long l = sc.nextLong(); |
Comparison: Scanner vs. Command-line Arguments
| Feature | Scanner | Command-line Arguments |
|---|---|---|
| When input is provided | While the program runs (interactive) | Before the program starts |
| User prompt | Can display a prompt message | No prompt; values typed before run |
| Type conversion | Automatic (nextInt(), nextDouble()) | Manual (Integer.parseInt()) |
| Multiple inputs | Can read unlimited inputs in a loop | All inputs must be known before execution |
Summary
- Scanner is in
java.util; must be imported before use. - Create with
new Scanner(System.in)for keyboard input. - Use
nextInt(),nextDouble(),nextLine()for different data types. - Close the Scanner with
sc.close()when done to release system resources.
Test Yourself
- Write a Java program using Scanner to read two integers and print their product.
- What is the difference between
next()andnextLine()? - Why must you import
java.util.Scannerbefore using Scanner?
Hints:
- Import Scanner. Create
Scanner sc = new Scanner(System.in). Read two ints withsc.nextInt(). Multiply and print. Close scanner. next()reads a single whitespace-delimited token (stops at space or newline).nextLine()reads the entire line including spaces until newline. UsenextLine()for full sentences.- Scanner is not in the default package. Without the import statement, the compiler cannot locate the
Scannerclass and reports an error.
1.9 Handling Common Errors
Definition
In Java, errors are divided into three categories: compile-time errors (syntax mistakes caught before the program runs), runtime errors (exceptions that occur while the program is running), and logical errors (wrong output due to incorrect program logic, not caught by the compiler or JVM).
Detailed Explanation
1. Compile-time Errors
These are caught by javac before the program runs. No .class file is produced. Common causes:
- Missing semicolons:
int x = 5→ error. - Mismatched braces: an unclosed
{. - Undeclared variables: using a variable without declaring its type.
- Type mismatch: assigning a double to an int without casting.
2. Runtime Errors (Exceptions)
These occur while the program is running. The JVM throws an exception and prints a stack trace. Common runtime exceptions in beginners' programs:
| Exception | Cause |
|---|---|
ArrayIndexOutOfBoundsException | Accessing an array index that does not exist (e.g., args[2] when only one argument was passed). |
NumberFormatException | Parsing a non-numeric string as a number: Integer.parseInt("abc"). |
NullPointerException | Calling a method on a variable that is null. |
ArithmeticException | Division by zero: int x = 10 / 0;. |
StackOverflowError | Infinite recursion — a method calls itself without a base case. |
3. Logical Errors
The program compiles and runs without crashing, but produces the wrong answer. Example: computing average as sum / count but forgetting that integer division truncates (e.g., 7 / 2 = 3 instead of 3.5). These require careful testing and debugging.
Basic Exception Handling with try-catch
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("Sum = " + (a + b));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Please provide two arguments.");
} catch (NumberFormatException e) {
System.out.println("Arguments must be integers.");
}Summary
- Compile-time errors: syntax mistakes caught by javac before execution; no .class file is produced.
- Runtime errors: exceptions thrown by the JVM during execution; program crashes with a stack trace.
- Logical errors: program runs but produces wrong output; must be found through testing.
- Use
try-catchblocks to handle expected runtime exceptions gracefully rather than letting the program crash.
Test Yourself
- Differentiate between compile-time, runtime, and logical errors with one example each.
- What exception is thrown if you access
args[1]but only one command-line argument was passed? - Write a try-catch block that handles a NumberFormatException.
Hints:
- Compile-time: missing semicolon (caught by javac). Runtime: dividing by zero throws ArithmeticException (caught by JVM). Logical: using wrong formula — wrong answer, no error thrown.
ArrayIndexOutOfBoundsException— the index 1 does not exist in an array of length 1.- Wrap the
Integer.parseInt()call intry { ... } catch (NumberFormatException e) { System.out.println("Not a valid number."); }.
Arrays in Java
Definition
An array in Java is a fixed-size, ordered collection of elements, all of the same data type, stored in contiguous memory locations. Each element is accessed by its integer index, starting at 0.
When you need to store fifty student marks, declaring fifty separate variables is impractical. An array lets you store all fifty in one named container and access any of them by position.
Detailed Explanation
Declaring and Initializing Arrays
There are two common approaches:
Method 1 — Declare, then allocate, then assign:
int[] marks; // declare array reference
marks = new int[5]; // allocate memory for 5 integers
marks[0] = 85; // assign values individually
marks[1] = 90;
marks[2] = 78;Method 2 — Declare and initialize in one step:
int[] marks = {85, 90, 78, 92, 88};Accessing Elements and Traversal
Elements are accessed via their index: marks[0] is the first element, marks[4] is the fifth (last) in a 5-element array. The valid index range is always 0 to length-1. Accessing marks[5] in a 5-element array throws ArrayIndexOutOfBoundsException.
for (int i = 0; i < marks.length; i++) {
System.out.println("marks[" + i + "] = " + marks[i]);
}Or, using the enhanced for-each loop:
for (int m : marks) {
System.out.println(m);
}Summary
- Arrays store multiple values of the same type under one name; size is fixed at creation.
- Index starts at 0; last valid index is
length - 1. - Declaration:
int[] arr = new int[n];orint[] arr = {v1, v2, v3};. - Traverse with a for loop using
arr.lengthor with enhanced for-each.
Test Yourself
- Define array and multi dimensional array. Write a program to read two m x n matrices, perform multiplication operation and store result in third matrix. (2024)
- Write a Java program to find the sum and average of elements in an integer array.
- What exception is thrown when an invalid array index is accessed?
Hints:
- Array = fixed-size, same-type collection indexed from 0. Multi-dimensional array = array of arrays. Matrix multiplication program: see multi-dimensional arrays section below.
- Declare array, iterate with for loop, accumulate sum. Average = (double)sum / array.length (cast to double to avoid integer division).
ArrayIndexOutOfBoundsException.
Multi-dimensional Arrays and Matrix Operations
Definition
A multi-dimensional array in Java is an array whose elements are themselves arrays. A two-dimensional (2D) array represents a matrix: rows and columns, accessed with two indices — arr[row][col].
A spreadsheet is the clearest model: rows run horizontally, columns vertically. The cell at row 2, column 3 is matrix[1][2] (zero-indexed). Two-dimensional arrays make matrix operations like addition and multiplication natural to express in code.
Detailed Explanation
Declaring and Initializing a 2D Array
int[][] matrix = new int[3][3]; // 3 rows, 3 columns
// Or initialize directly:
int[][] A = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Access element at row 1, column 2: A[1][2] = 6.
Matrix Multiplication (2024 Exam Question)
For two matrices A (of size m×n) and B (of size n×p), the product C = A × B has size m×p. Each element C[i][j] is computed as:
C[i][j] = sum of A[i][k] * B[k][j] for k from 0 to n-1.
Rule: the number of columns in A must equal the number of rows in B.
// MatrixMultiplication.java
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows (m) and columns (n): ");
int m = sc.nextInt();
int n = sc.nextInt();
int[][] A = new int[m][n];
int[][] B = new int[n][m]; // n rows, m columns
int[][] C = new int[m][m]; // result: m x m
System.out.println("Enter elements of Matrix A (" + m + "x" + n + "):");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
A[i][j] = sc.nextInt();
System.out.println("Enter elements of Matrix B (" + n + "x" + m + "):");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
B[i][j] = sc.nextInt();
// Matrix multiplication
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
System.out.println("Result Matrix C:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(C[i][j] + "\t");
}
System.out.println();
}
sc.close();
}
}Worked Example of Matrix Multiplication
Let A = [[1,2],[3,4]] (2×2) and B = [[5,6],[7,8]] (2×2).
C[0][0] = 1×5 + 2×7 = 5 + 14 = 19
C[0][1] = 1×6 + 2×8 = 6 + 16 = 22
C[1][0] = 3×5 + 4×7 = 15 + 28 = 43
C[1][1] = 3×6 + 4×8 = 18 + 32 = 50
Result: C = [[19,22],[43,50]]
Summary
- A 2D array stores data in rows and columns:
int[][] matrix = new int[rows][cols]. - Element access:
matrix[row][col], both indices start at 0. - Matrix multiplication requires three nested loops: i (rows of A), j (cols of B), k (shared dimension).
- Multiplication is only valid when columns of A = rows of B.
Test Yourself
- Define array and multi dimensional array. Write a program to read two m x n matrices, perform multiplication operation and store result in third matrix. (2024)
- Write a Java program to display the transpose of a given 2D matrix.
- What is the condition for matrix multiplication to be valid?
Hints:
- Array = fixed-size indexed sequence; 2D array = array of arrays (grid). Program: declare A[m][n] and B[n][p], read with nested for loops, compute C[i][j] using triple nested loop with k as summation index. See program above.
- Transpose: swap rows and columns. For an m×n matrix A, transpose T is n×m where
T[j][i] = A[i][j]. Use two nested loops. - Number of columns in the first matrix must equal number of rows in the second matrix. A[m×n] × B[n×p] is valid; result is [m×p].
Jagged Arrays
Definition
A jagged array (also called a ragged array) is a 2D array where each row can have a different number of columns. Unlike a regular 2D array where every row has the same length, a jagged array's rows are independent arrays of varying sizes.
A normal 2D array is like a perfect rectangular grid. A jagged array is more like a staircase — the first row might have 3 columns, the second row 1, the third row 4. Each row is a separate array allocated independently.
Detailed Explanation
Declaring and Initializing a Jagged Array
int[][] jagged = new int[3][]; // 3 rows; column count not specified
jagged[0] = new int[3]; // row 0 has 3 elements
jagged[1] = new int[1]; // row 1 has 1 element
jagged[2] = new int[4]; // row 2 has 4 elementsOr initialize directly with values:
int[][] jagged = {
{1, 2, 3},
{4},
{5, 6, 7, 8}
};Program: Initialize, Display Jagged Array, and Compute Sum of Each Row (2022 Exam Question)
// JaggedArray.java
public class JaggedArray {
public static void main(String[] args) {
int[][] jagged = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
System.out.println("Jagged Array Elements and Row Sums:");
for (int i = 0; i < jagged.length; i++) {
int rowSum = 0;
System.out.print("Row " + i + ": ");
for (int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
rowSum += jagged[i][j];
}
System.out.println(" -> Sum = " + rowSum);
}
}
}Output:
Row 0: 1 2 3 -> Sum = 6
Row 1: 4 5 -> Sum = 9
Row 2: 6 7 8 9 -> Sum = 30Key detail: jagged[i].length gives the length of the i-th row — this changes per row in a jagged array, unlike a regular 2D array where all rows have the same length.
| Feature | Regular 2D Array | Jagged Array |
|---|---|---|
| Row size | All rows same length | Each row can have different length |
| Memory | Rectangular block | Non-rectangular; each row is independent |
| Declaration | int[][] a = new int[3][4] | int[][] a = new int[3][] then allocate each row |
| Use case | Matrices, grids | Triangular tables, variable-length row data |
Summary
- A jagged array is a 2D array where each row is a separate array of potentially different length.
- Declare the row count first (
new int[n][]), then allocate each row individually. - Use
jagged[i].length(not a fixed column count) to iterate correctly through each row. - Useful when rows naturally have unequal sizes — triangular data, passenger counts by day, etc.
Test Yourself
- What is jagged array? Write a java program to initialize and display jagged array element with sum of each row. (2022)
- How is a jagged array different from a regular 2D array?
- Write a jagged array with 4 rows where row i has (i+1) elements.
Hints:
- Jagged array = 2D array with variable-length rows. Declaration:
int[][] j = new int[n][]thenj[i] = new int[size]for each row. Traverse withjagged[i].lengthin inner loop. See program above. - Regular 2D: all rows have the same column count (rectangular). Jagged: each row is an independent array; rows can differ in length. Memory layout is non-rectangular.
int[][] j = new int[4][]; thenj[0]=new int[1]; j[1]=new int[2]; j[2]=new int[3]; j[3]=new int[4];— row 0 has 1 element, row 3 has 4.
Exam Questions
- What is command-line arguments? Write a program to accept two numbers and display their sum using command-line arguments. (2025)
- What is java Buzzwords? Write a java program to find simple interest. Use command line argument to take input. (2023)
- Define array and multi dimensional array. Write a program to read two m x n matrices, perform multiplication operation and store result in third matrix. (2024)
- What is jagged array? Write a java program to initialize and display jagged array element with sum of each row. (2022)
Whole Chapter Summary
- 1.1 History and Buzzwords: Java was created by James Gosling at Sun Microsystems in 1995. Its eleven buzzwords describe its design: platform-independent (bytecode+JVM), secure (no pointers, sandbox), robust (type-checking, GC), multithreaded, and object-oriented are the most testable.
- 1.2 JVM, JDK, JRE: JVM executes bytecode; JRE = JVM + class libraries (for running); JDK = JRE + compiler + tools (for development). The flow is: .java → javac → .class (bytecode) → java → JVM → output.
- 1.3 POP vs. OOP: POP separates data and functions; OOP bundles them into objects. OOP's four pillars — encapsulation, inheritance, polymorphism, abstraction — make large systems more manageable and secure.
- 1.4 Environment Setup: Install JDK, set JAVA_HOME, add bin to PATH, verify with javac -version and java -version. Use an IDE (IntelliJ, Eclipse, NetBeans) for efficient development.
- 1.5 Sample Programs: Every Java program has a class matching the filename and a public static void main(String[] args) entry point.
- 1.6 Compile and Run: javac FileName.java produces bytecode; java ClassName executes it. Compile errors are caught at compile time; exceptions at runtime.
- 1.7 Command-line Arguments: Passed as String[] args at runtime; parse with Integer.parseInt() or Double.parseDouble() for numeric use. Allows the same compiled program to handle different inputs without recompilation.
- 1.8 Scanner Class: Reads interactive input during runtime using nextInt(), nextDouble(), nextLine(). Imported from java.util. Complementary to command-line arguments — use Scanner when the user types values while the program runs.
- 1.9 Error Handling: Three error types: compile-time (syntax, caught by javac), runtime (exceptions thrown by JVM), logical (wrong output, no crash). Use try-catch to handle expected runtime exceptions.
- Arrays: Fixed-size, same-type, indexed from 0. Declare as int[] arr = new int[n] or int[] arr = {v1,v2}. Access with arr[i]; traverse with arr.length.
- Multi-dimensional Arrays: int[][] for matrices; triple nested loop for multiplication. Condition: columns of A must equal rows of B.
- Jagged Arrays: 2D arrays with variable-length rows. Allocate rows independently. Use jagged[i].length to iterate each row correctly.
Last-Minute Revision Sheet
- Java creator → James Gosling, Sun Microsystems, 1995; originally called Oak
- Buzzwords count → 11; most tested: platform-independent, secure, robust, multithreaded, OOP
- Platform independence → bytecode (.class) + JVM; JVM is platform-specific, bytecode is universal
- JVM ⊂ JRE ⊂ JDK; developer installs JDK; end-user needs only JRE
- Compile:
javac File.java→ Run:java ClassName(no .class) - CMD args →
String[] args; parse int withInteger.parseInt(args[0]) - Scanner →
import java.util.Scanner;new Scanner(System.in); close withsc.close() - 3 error types → compile-time (javac), runtime (JVM exception), logical (wrong output)
- Array → fixed size, same type, index 0 to length-1; access: arr[i]
- 2D array → int[m][n]; traverse with two nested loops
- Matrix multiply → C[i][j] += A[i][k] * B[k][j]; condition: cols(A) = rows(B)
- Jagged → rows have different lengths; declare:
new int[n][]; iterate withjagged[i].length - OOP pillars → Encapsulation, Inheritance, Polymorphism, Abstraction
- POP vs OOP → POP: functions + shared data; OOP: objects with own data + methods


