Questions & Answers
Object Oriented Programming with JAVA
⏱ Exam tomorrow? Open
07-WRITE-THIS.mdinstead.That file is the same 21 questions at the size you can handwrite in 15 minutes. This file teaches you the ideas; that one is what you actually put on the answer sheet. Read both only if you have the time.
Written for a beginner. No prior Java needed. Every answer follows the same six steps so nothing feels new from question to question:
In simple words → Think of it like → How it works → Code → Output → Exam tip
If you only have one night, read Part 1 (10 minutes), then Part 2 (the 21 questions), then Part 6 (the cheat tables). That is enough to pass well.
Java version — 2025, not 2026. Every program here is written for Java 25 LTS (the 2025 release). Each one also compiles unchanged on Java 21 and Java 17, so it will work in your college lab whatever JDK is installed. All 20 programs were compile-tested with
javac --release 25,--release 21and--release 17— zero errors. No Java 26 features, no preview features.
Contents
| Part | What's in it | Time |
|---|---|---|
| 1 | Start here — how Java actually works | 10 min |
| 2 | The 21 questions that matter, explained simply | 3 hrs |
| 3 | Quick answers to all 41 question-bank questions | 1 hr |
| 4 | The 3 assignments, solved | 45 min |
| 5 | 12 programs you must be able to write | 1.5 hrs |
| 6 | Cheat tables — memorise these | 45 min |
| 7 | Last 6 hours before the exam | — |
PART 1 · Start Here
Before any question makes sense, you need four ideas. Ten minutes.
1.1 What Java actually does
You write a file called Hello.java. Java turns it into Hello.class. Then a
program called the JVM runs that .class file.
Hello.java ──► Hello.class ──► JVM ──► Your output
(your code) (bytecode) "Hello"
Why this matters: the .class file works on any computer — Windows, Mac,
Linux — as long as a JVM is installed. That is what "platform independent" means.
It is the single most-asked idea in Unit 1.
1.2 The three names everyone confuses
| Name | What it is | Remember it as |
|---|---|---|
| JVM | Java Virtual Machine — runs the .class file |
The player |
| JRE | JVM + the built-in libraries | The player plus the DVDs |
| JDK | JRE + the tools to write code (javac) |
Player + DVDs + the camera |
They nest inside each other: JDK ⊃ JRE ⊃ JVM. You write code with the JDK. You run code with the JRE.
1.3 What a class and an object are
class Dog { // ← this is the CLASS (the plan)
String name;
void bark() {
System.out.println(name + " says woof");
}
}
Dog d = new Dog(); // ← this is an OBJECT (a real dog made from the plan)
d.name = "Tommy";
d.bark(); // Tommy says woof
The class is the plan. The object is the thing. You write the plan once and make as many objects as you like.
1.4 The four words you'll see constantly
| Word | Plain meaning |
|---|---|
new |
"Make a real object from this class" |
this |
"This object right here" |
extends |
"Child of" — a class taking after another |
void |
"This method gives nothing back" |
That's it. You're ready.
1.5 The exact syntax to write in the exam
Write these forms. They compile on Java 17, 21 and 25 — which means they compile on whatever the lab has installed.
| Task | ✅ Write this | ❌ Not this |
|---|---|---|
| Make a list | ArrayList<String> list = new ArrayList<>(); |
var list = new ArrayList<String>(); |
| Multi-line text | String s = "line one\nline two"; |
String s = """line one..."""; |
| Choose a branch | switch (x) { case 1: ...; break; } |
switch (x) { case 1 -> ...; } |
| Hold a group of pairs | class Pair { int a; int b; } |
record Pair(int a, int b) {} |
| Print money | System.out.println("Rs. " + amt); |
System.out.println("₹" + amt); |
| Loop over an array | for (int n : arr) { } |
Arrays.stream(arr).forEach(...) |
| Friendly method | // comment above the method |
/** javadoc with tags */ |
Why avoid the right-hand column? None of it is wrong Java — but records, var,
text blocks and arrow-switches are newer than most college syllabi. A marker who
hasn't seen them may not give the mark. The left column is unmistakable.
The skeleton every exam program needs
public class ProgramName { // file must be named ProgramName.java
public static void main(String[] args) {
// your code here
}
}
Three things students lose marks on:
- File name must match the public class name —
ProgramName.java public static void main(String[] args)— all five parts, in that orderimport java.util.*;at the very top if you useArrayList,HashMaporScanner
PART 2 · The 21 Questions That Matter
Ranked by how likely they are to be on your paper.
Q1. What is the difference between a class and an object? ⭐⭐⭐
Appears in: Assignment 1 Q3 · Question Bank Ch1 Q3, Ch5 Q1
In simple words
A class is the plan. An object is the real thing built from the plan.
Think of it like
A class is a cookie cutter. An object is a cookie. One cutter, many cookies. The cutter has no taste — only the cookies do.
The difference
| Class | Object |
|---|---|
| The plan / blueprint | The real thing |
| Takes no memory | Takes memory when created |
| Written once | Can be many |
class Dog { } |
Dog d = new Dog(); |
Code
class Dog {
String name; // what the dog is called
int age; // how old the dog is
void bark() {
System.out.println(name + " says woof! Age " + age);
}
}
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog(); // object 1
d1.name = "Tommy";
d1.age = 3;
Dog d2 = new Dog(); // object 2 — completely separate
d2.name = "Sheru";
d2.age = 5;
d1.bark();
d2.bark();
}
}
Output
Tommy says woof! Age 3
Sheru says woof! Age 5
Exam tip
Say this exact line: "A class is a blueprint and takes no memory; an object is an instance of a class and is stored in memory." Then give the cookie-cutter analogy.
Q2. What is a constructor, and what is constructor overloading? ⭐⭐⭐
Appears in: Assignment 2 Q3 · Question Bank Ch5 Q2
In simple words
A constructor is the setup code that runs automatically the moment you create an object. It fills in the starting values.
Constructor overloading means writing several constructors in the same class, each taking different inputs.
Think of it like
Ordering a pizza. You don't assemble it — you say what you want and it arrives ready.
- "One margherita" → one constructor
- "One margherita with extra cheese" → another constructor
Same shop, different orders.
How it works
- You write
new Student(101, "Aarav") - Java reserves memory for the object
- Java finds the constructor that takes
(int, String) - That constructor runs and fills in the values
- You get back a ready-to-use object
Three rules:
- The name is exactly the class name
- It has no return type — not even void
- If you write none, Java gives you an empty one
Code
class Student {
int id;
String name;
double marks;
// constructor 1 — no inputs
Student() {
id = 0;
name = "Unknown";
marks = 0;
}
// constructor 2 — two inputs
Student(int id, String name) {
this.id = id; // 'this.id' = this object's id
this.name = name; // 'id' alone = the parameter
this.marks = 0;
}
// constructor 3 — three inputs (overloaded)
Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
void show() {
System.out.println(id + " | " + name + " | " + marks);
}
}
public class Demo {
public static void main(String[] args) {
Student s1 = new Student(); // uses constructor 1
Student s2 = new Student(101, "Aarav"); // uses constructor 2
Student s3 = new Student(102, "Diya", 88.5); // uses constructor 3
s1.show();
s2.show();
s3.show();
}
}
Output
0 | Unknown | 0.0
101 | Aarav | 0.0
102 | Diya | 88.5
Exam tip
If they ask for types of constructors, list all five:
- Default — Java writes it for you (empty)
- No-argument — you write it yourself
- Parameterized — takes inputs
- Overloaded — several in one class
- Copy — builds a new object from an existing one
Q3. What is the difference between method overloading and method overriding? ⭐⭐⭐
The single most likely question on your paper. It is in the question bank, in Assignment 2, and in the sample paper.
In simple words
- Overloading = same method name, different inputs, in the same class
- Overriding = same method name, same inputs, but the child class rewrites it
Think of it like
- Overloading — one person named "Alex" who can carry 1 bag, or 2 bags, or 3 bags. Same name, different jobs.
- Overriding — your father says "we eat dinner at 8". You say "in our house, we eat at 9". Same rule, you replaced it.
The difference
| Overloading | Overriding |
|---|---|
| Same class | Parent + child class |
| Inputs must differ | Inputs must be identical |
| Java decides before running | Java decides while running |
| Compile-time polymorphism | Runtime polymorphism |
| No inheritance needed | Needs inheritance |
Code
// ---------- OVERLOADING ----------
class Calculator {
int add(int a, int b) { return a + b; } // 2 numbers
int add(int a, int b, int c) { return a + b + c; } // 3 numbers
double add(double a, double b) { return a + b; } // decimals
}
// ---------- OVERRIDING ----------
class Animal {
void sound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
@Override
void sound() { // same name, same inputs
System.out.println("Dog barks");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println("--- Overloading ---");
Calculator c = new Calculator();
System.out.println(c.add(10, 20)); // 30
System.out.println(c.add(10, 20, 30)); // 60
System.out.println(c.add(2.5, 3.5)); // 6.0
System.out.println("--- Overriding ---");
Animal a = new Dog(); // a parent variable holding a child object
a.sound(); // Dog barks — not "Some animal sound"
}
}
Output
--- Overloading ---
30
60
6.0
--- Overriding ---
Dog barks
Exam tip
Why does a.sound() print "Dog barks"?
a is declared as Animal but it actually holds a Dog. Java looks at the real
object, not the label. That is dynamic method dispatch — and it's worth its own
question on the paper.
Write this sentence in the answer: "The method is chosen at run time based on the actual object, not the reference type."
Q4. What is inheritance, and what are its types? ⭐⭐⭐
Appears in: Assignment 2 Q5 · Question Bank Ch6 Q1
In simple words
Inheritance lets a child class reuse everything from a parent class, then add its own extra features.
Think of it like
A child inherits their parent's surname and house, then builds their own room on top. They didn't rebuild the house — they extended it.
The five types
| Type | Shape | Works in Java? |
|---|---|---|
| Single | A → B | ✅ Yes |
| Multilevel | A → B → C | ✅ Yes |
| Hierarchical | A → B, A → C, A → D | ✅ Yes |
| Multiple | A + B → C | ❌ Not with classes · ✅ with interfaces |
| Hybrid | Mix of the above | ❌ Not with classes · ✅ with interfaces |
Single Multilevel Hierarchical
A A A
↓ ↓ ↙ ↓ ↘
B B B C D
↓
C
Code
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal { // Dog IS-A Animal
void bark() {
System.out.println("Dog barks");
}
}
public class Demo {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // comes from Animal (inherited)
d.bark(); // Dog's own method
}
}
Output
This animal eats food
Dog barks
Exam tip
Why can't Java do multiple inheritance with classes?
Because of the diamond problem. If C extends both A and B, and both have a
method show(), which one does C get? Java can't decide — so it forbids it.
Interfaces solve this because an interface has no method body — there is nothing to be confused about. Write this. It's a full mark on its own.
Q5. What is an interface? ⭐⭐⭐
Appears in: Assignment 2 Q1, Q2 · Question Bank Ch7 Q2, Q3
In simple words
An interface is a contract. It says what a class must do, but not how. Any class that signs the contract must provide all the methods listed.
Think of it like
A job description. It says "must know Java, must know SQL". It does not say how you learned it. Two different people can both fit the description and do the work completely differently.
How it works
interface Shape { // the contract
double area(); // no body — just the promise
}
Any class that writes implements Shape must write an area() method. If it
doesn't, the code won't compile.
Code — multiple inheritance (Assignment 2 Q1)
interface Shape {
double area();
}
interface Measurable {
double perimeter();
}
// Circle signs BOTH contracts
class Circle implements Shape, Measurable {
double radius;
Circle(double radius) {
this.radius = radius;
}
public double area() { // must be public
return Math.PI * radius * radius;
}
public double perimeter() {
return 2 * Math.PI * radius;
}
}
// Square also signs BOTH contracts
class Square implements Shape, Measurable {
double side;
Square(double side) {
this.side = side;
}
public double area() { return side * side; }
public double perimeter() { return 4 * side; }
}
public class Demo {
public static void main(String[] args) {
Circle c = new Circle(7);
Square s = new Square(5);
System.out.printf("Circle area = %.2f%n", c.area());
System.out.printf("Circle perimeter = %.2f%n", c.perimeter());
System.out.println("Square area = " + s.area());
System.out.println("Square perimeter = " + s.perimeter());
}
}
Output
Circle area = 153.94
Circle perimeter = 43.98
Square area = 25.0
Square perimeter = 20.0
Rules to remember
| Rule | Detail |
|---|---|
You cannot do new Shape() |
Interfaces can't be created |
You can write Shape s = new Circle(7); |
They work as a type |
Methods are public by default |
You must still write public in the class |
Variables are public static final |
Constants only |
| No constructors | None at all |
| A class can implement many interfaces | This is multiple inheritance |
Exam tip
implements for interfaces, extends for classes. Mixing them up loses easy marks.
Q6. What is the difference between an abstract class and an interface? ⭐⭐⭐
In simple words
- Abstract class = a half-built house. Some rooms are finished, some you must finish.
- Interface = an empty plot with a list of rooms you must build.
Think of it like
An abstract class is a recipe half-cooked by a chef — you finish the last steps. An interface is just a shopping list — you cook everything yourself, your way.
The difference
| Abstract class | Interface |
|---|---|
| Can have normal methods and abstract ones | All methods are abstract |
| Can have constructors | No constructors |
| Can have any type of variable | Only public static final |
| A class extends one | A class implements many |
| Use when classes share code | Use when classes share only a promise |
Code
abstract class Shape {
int color; // can hold data
Shape(int color) { // can have a constructor
this.color = color;
}
abstract void draw(); // must be finished by the child
void describe() { // already finished
System.out.println("A shape with color " + color);
}
}
class Square extends Shape {
Square(int color) {
super(color); // calls the parent constructor
}
void draw() { // the child finishes it
System.out.println("Drawing a square");
}
}
public class Demo {
public static void main(String[] args) {
// Shape s = new Shape(1); ❌ cannot create an abstract class
Shape s = new Square(5); // ✅ but this is fine
s.draw();
s.describe();
}
}
Output
Drawing a square
A shape with color 5
Exam tip
The table is the whole answer. Learn five rows and you're safe.
Q7. What is try-catch-finally? ⭐⭐⭐
Appears in: Assignment 3 Q5 · Question Bank Ch8 Q2, Q5
In simple words
When code might fail, you try it. If it fails, you catch the error. Whatever happens, finally runs.
Think of it like
Driving to work.
- try — you attempt the drive
- catch — if there's a roadblock, you take the detour
- finally — you park the car when you arrive, roadblock or not
The parking happens no matter what.
How it works
try {
// code that might break
}
catch (ExceptionType e) {
// what to do if it breaks
}
finally {
// always runs — clean up here
}
Code
public class Demo {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
System.out.println("Dividing...");
int result = a / b; // 💥 breaks here
System.out.println("Result = " + result); // never reached
} catch (ArithmeticException e) {
System.out.println("Caught: cannot divide by zero");
System.out.println("Java says: " + e.getMessage());
} finally {
System.out.println("Finally: cleanup always runs");
}
System.out.println("Program continues normally");
}
}
Output
Dividing...
Caught: cannot divide by zero
Java says: / by zero
Finally: cleanup always runs
Program continues normally
Exam tip
Three facts that score marks:
finallyruns even iftryhas areturnfinallydoes not run if you callSystem.exit()- When catching several exceptions, specific ones must come first — otherwise the code won't compile
Q8. What is the difference between checked and unchecked exceptions? ⭐⭐⭐
In simple words
- Checked — the compiler forces you to handle it. Your code won't compile otherwise.
- Unchecked — the compiler doesn't care. It blows up at run time.
Think of it like
- Checked = airport security. You cannot board without going through it.
- Unchecked = tripping on a step. Nobody warns you — it just happens.
The difference
| Checked | Unchecked |
|---|---|
| Compiler checks it | Compiler ignores it |
Must catch or declare throws |
Optional |
| Happens at compile time | Happens at run time |
IOException, SQLException |
ArithmeticException, NullPointerException |
| Usually a file/network problem | Usually a coding mistake |
Code
import java.io.*;
public class Demo {
public static void main(String[] args) {
// ❌ This line ALONE will not compile:
// FileReader f = new FileReader("data.txt");
// because FileNotFoundException is CHECKED.
// ✅ So we must handle it:
try {
FileReader f = new FileReader("data.txt");
f.close();
} catch (IOException e) {
System.out.println("Handled checked exception: " + e.getMessage());
}
// Unchecked — compiles fine, breaks only if it actually happens:
int[] arr = {1, 2, 3};
// arr[10] = 5; // ArrayIndexOutOfBoundsException at RUN time
System.out.println("Unchecked code compiled fine");
}
}
Output
Handled checked exception: data.txt (The system cannot find the file specified)
Unchecked code compiled fine
Exam tip
One sentence: "A checked exception is verified by the compiler; an unchecked exception is only discovered at run time."
Q9. What are the four pillars of OOP? ⭐⭐⭐
Appears in: Assignment 1 Q2 · Question Bank Ch1 Q1 · almost every sample paper
In simple words
All of object-oriented programming rests on four ideas.
| Pillar | Plain meaning | Java keyword |
|---|---|---|
| Encapsulation | Keep data private, let people use it only through doors you provide | private + getters |
| Inheritance | Child reuses parent's code | extends |
| Polymorphism | One name, many behaviours | overloading / overriding |
| Abstraction | Show what it does, hide how | abstract, interface |
Think of it like
| Pillar | Real-life picture |
|---|---|
| Encapsulation | A TV remote — you press buttons, you don't touch the circuit board |
| Inheritance | You inherit your father's business and open a new branch |
| Polymorphism | The word "draw" — an artist draws, a bank draws money, a card game draws a card |
| Abstraction | A car's steering wheel — you turn it, you don't think about the gears |
Code — all four in one file
// 1. ENCAPSULATION - data is private, accessed through methods
class BankAccount {
private double balance; // hidden
public void deposit(double amount) {
if (amount > 0) balance += amount; // checked before allowing
}
public double getBalance() {
return balance;
}
}
// 2. INHERITANCE - Dog reuses Animal's code
class Animal {
void eat() { System.out.println("Animal eats"); }
}
class Dog extends Animal {
void bark() { System.out.println("Dog barks"); }
}
// 3. POLYMORPHISM - same method, different behaviour
class Shape {
void draw() { System.out.println("Drawing a shape"); }
}
class Circle extends Shape {
void draw() { System.out.println("Drawing a circle"); }
}
// 4. ABSTRACTION - promise without implementation
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() { System.out.println("Car starts with a key"); }
}
public class FourPillars {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(5000);
System.out.println("1. " + acc.getBalance());
Dog d = new Dog();
System.out.print("2. ");
d.eat();
Shape s = new Circle();
System.out.print("3. ");
s.draw();
Vehicle v = new Car();
System.out.print("4. ");
v.start();
}
}
Output
1. 5000.0
2. Animal eats
3. Drawing a circle
4. Car starts with a key
Exam tip
This one program answers the entire question. Memorise it — it's the highest-value 25 lines in this file.
Q10. What are JDK, JRE and JVM? ⭐⭐⭐
In simple words
Three layers of the same thing, nested inside each other.
| Name | Full name | Job | One word |
|---|---|---|---|
| JVM | Java Virtual Machine | Runs the .class file |
Player |
| JRE | Java Runtime Environment | JVM + standard libraries | Player + films |
| JDK | Java Development Kit | JRE + compiler and tools | Player + films + camera |
Nesting: JDK ⊃ JRE ⊃ JVM
You write with the JDK. You run with the JRE. The JVM does the actual work.
Think of it like
- JVM = the engine of a car
- JRE = the engine plus the wheels
- JDK = the engine + wheels + the tools to build the car
Bytecode — the thing in the middle
Hello.java ──javac──► Hello.class ──java──► output
(source) (bytecode)
Bytecode is the halfway language. Not human-readable, not machine-code. It's a language only the JVM understands.
| Bytecode | Machine code |
|---|---|
| Runs on any JVM | Runs only on one type of CPU |
File: .class |
File: .exe, .dll |
| Platform independent | Platform dependent |
Exam tip
Write this sentence: "JVM is platform-dependent, but Java is not." The JVM is built separately for each operating system. The bytecode it runs is the same everywhere.
Then draw the JVM diagram — four boxes: Class Loader → Memory Areas → Execution Engine → JNI / Native.
Q11. What are the primitive data types and their default values? ⭐⭐
Appears in: Assignment 1 Q5 · Question Bank Ch2 Q1
In simple words
Java has 8 basic types for storing simple values. Everything else is an object.
The table you must know
| Type | Size | Holds | Default | Example |
|---|---|---|---|---|
byte |
1 byte | tiny integers (−128 to 127) | 0 |
byte a = 10; |
short |
2 bytes | small integers | 0 |
short b = 1000; |
int |
4 bytes | normal integers | 0 |
int age = 21; |
long |
8 bytes | huge integers | 0L |
long id = 9999999999L; |
float |
4 bytes | decimals (less precise) | 0.0f |
float pi = 3.14f; |
double |
8 bytes | decimals (more precise) | 0.0 |
double d = 3.14159; |
char |
2 bytes | one character | '\u0000' |
char c = 'A'; |
boolean |
1 bit | true / false | false |
boolean ok = true; |
Non-primitive: String, arrays, classes. Their default is null.
Type casting
Widening (automatic) — small → big. Safe. No cast needed.
int a = 10;
double b = a; // 10.0 — Java does it for you
Narrowing (manual) — big → small. Needs a cast. May lose data.
double x = 9.78;
int y = (int) x; // 9 — the .78 is chopped off, not rounded
Exam tip
(int) 9.99 gives 9, not 10. It truncates, it does not round.
If rounding is wanted, use Math.round().
Q12. What are the types of operators in Java? ⭐⭐
Appears in: Assignment 1 Q4 · Question Bank Ch2 Q3
The eight families
| Family | Symbols | Example |
|---|---|---|
| Arithmetic | + - * / % |
10 % 3 → 1 |
| Relational | == != > < >= <= |
5 > 3 → true |
| Logical | && \|\| ! |
true && false → false |
| Bitwise | & \| ^ ~ << >> |
5 & 3 → 1 |
| Assignment | = += -= *= /= |
a += 5 → a = a + 5 |
| Unary | ++ -- ! |
++a, a-- |
| Ternary | ? : |
(a > b) ? a : b |
| instanceof | instanceof |
obj instanceof String |
Code — the ones that trip people up
public class Demo {
public static void main(String[] args) {
// 1. Integer division drops the decimals
System.out.println(10 / 3); // 3 ← not 3.33
System.out.println(10 / 3.0); // 3.3333333333333335
// 2. Remainder
System.out.println(10 % 3); // 1
// 3. Prefix vs postfix
int a = 5;
System.out.println(a++); // 5 ← prints first, then adds
System.out.println(a); // 6
int b = 5;
System.out.println(++b); // 6 ← adds first, then prints
// 4. Short-circuit — the second half is never checked
int zero = 0;
System.out.println(zero != 0 && 10 / zero > 1); // false, no crash
// 5. String plus number
System.out.println(10 + 20 + "Java" + 10 + 20); // 30Java1020
// 6. Ternary
int x = 10, y = 20;
System.out.println((x > y) ? x : y); // 20
}
}
Output
3
3.3333333333333335
1
5
6
6
false
30Java1020
20
Exam tip
10 + 20 + "Java" + 10 + 20 → 30Java1020.
Why? Java reads left to right. First 10 + 20 = 30 (numbers add). Then it hits
"Java" and everything after becomes text. So 30 + "Java" = "30Java", then
+ 10 = "30Java10", then + 20 = "30Java1020".
This exact line appears on exams constantly.
Q13. What are arrays, and how do 2D arrays work? ⭐⭐
Appears in: Question Bank Ch4 · Unit 4
In simple words
An array is a row of boxes that all hold the same type of thing, and the row is a fixed size.
Think of it like
An egg carton. Exactly 12 slots. All hold eggs. Numbered 0 to 11 — starting at zero, not one.
The four facts
- Fixed size — decided when created, can't grow
- Same type — all
int, or allString - Numbered from 0 — a 5-slot array runs 0 to 4
lengthis a field, not a method —a.length, no brackets
Code
public class Demo {
public static void main(String[] args) {
// ---- 1D array ----
int[] marks = {85, 92, 78, 65, 90};
System.out.println("Length = " + marks.length); // 5
System.out.println("First = " + marks[0]); // 85
System.out.println("Last = " + marks[4]); // 90
int total = 0;
for (int i = 0; i < marks.length; i++) {
total += marks[i];
}
System.out.println("Total = " + total);
System.out.println("Average = " + (double) total / marks.length);
// ---- 2D array ----
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println("\n2D rows = " + grid.length); // 2
System.out.println("2D cols = " + grid[0].length); // 3
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
}
Output
Length = 5
First = 85
Last = 90
Total = 410
Average = 82.0
2D rows = 2
2D cols = 3
1 2 3
4 5 6
Exam tip
A 2D array in Java is an array of arrays. That's why grid.length gives
rows and grid[0].length gives columns. Write that sentence.
Q14. What is the difference between String, StringBuffer and StringBuilder? ⭐⭐
Appears in: Question Bank Ch7 Q1 · sample paper
In simple words
- String — cannot be changed. Every "change" makes a brand new one.
- StringBuffer — can be changed, and is safe for multiple threads.
- StringBuilder — can be changed, and is faster (not thread-safe).
Think of it like
- String is a printed page. Want to change a word? Print a new page.
- StringBuffer / StringBuilder is a whiteboard. Erase and rewrite as you like.
The difference
| String | StringBuffer | StringBuilder | |
|---|---|---|---|
| Changeable? | ❌ No | ✅ Yes | ✅ Yes |
| Thread-safe? | ✅ Yes | ✅ Yes | ❌ No |
| Speed | Slowest | Slow | Fastest |
| Use when | Value never changes | Many threads | One thread (usually) |
Code
public class Demo {
public static void main(String[] args) {
// ---- String: every change creates a NEW object ----
String s = "Java";
s.concat(" Rocks"); // the result is thrown away!
System.out.println(s); // still "Java"
s = s.concat(" Rocks"); // must reassign
System.out.println(s); // "Java Rocks"
// ---- StringBuilder: changes in place ----
StringBuilder sb = new StringBuilder("Java");
sb.append(" Rocks");
sb.append("!");
System.out.println(sb); // Java Rocks!
// ---- building a string in a loop ----
// ❌ slow way
String slow = "";
for (int i = 1; i <= 3; i++) slow = slow + i;
System.out.println(slow); // 123
// ✅ fast way
StringBuilder fast = new StringBuilder();
for (int i = 1; i <= 3; i++) fast.append(i);
System.out.println(fast); // 123
// ---- == vs equals (the classic trap) ----
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b); // true — same object
System.out.println(a == c); // false — different objects
System.out.println(a.equals(c)); // true — same letters
}
}
Output
Java
Java Rocks
Java Rocks!
123
123
true
false
true
Exam tip
== compares where the text lives. .equals() compares what the text says.
Always use .equals() for strings.
Q15. What is a package, and how do you create one? ⭐⭐
Appears in: Assignment 3 Q2 · Question Bank Ch7 Q4
In simple words
A package is a folder for classes. It keeps related classes together and stops name clashes.
Think of it like
A filing cabinet. You could put every paper in one pile, but then two people named "Rahul Sharma" get mixed up. Folders keep things separate.
Why packages matter
- No name clashes — two classes can both be called
Studentin different packages - Group related things together
- Control access — package-only visibility
- Reusable — import them elsewhere
- Easier to maintain
Steps to create one
Step 1 — Put package as the very first line of the file:
package mypack;
public class MyClass {
public void show() {
System.out.println("Hello from mypack");
}
}
Step 2 — Compile with -d:
javac -d . MyClass.java
This creates the folder mypack/ and puts MyClass.class inside it.
Step 3 — Import it in another file:
import mypack.MyClass;
public class Main {
public static void main(String[] args) {
MyClass m = new MyClass();
m.show();
}
}
Step 4 — Run:
java -cp . Main
Built-in packages
| Package | What's inside |
|---|---|
java.lang |
String, Math, System — imported automatically |
java.util |
ArrayList, HashMap, Scanner |
java.io |
File reading and writing |
java.sql |
Database |
java.net |
Networking |
Exam tip
Two full marks:
- javac -d . — the -d flag is what creates the folder structure. Most students forget it.
- PATH vs CLASSPATH — PATH finds programs like javac.exe. CLASSPATH finds your .class files.
Q16. What is the difference between static and final? ⭐⭐
Appears in: Question Bank Ch5 Q5
In simple words
static— belongs to the class, not to any one object. One copy shared by all.final— cannot be changed. Locked.
Think of it like
static= the school notice board. One board, everyone reads the same one.final= a printed certificate. Once printed, it can't be edited.
The difference
static |
final |
|---|---|
| Shared by all objects | Cannot be changed |
| One copy only | Whatever it is, it's locked |
static int count = 0; |
final int MAX = 100; |
Code
class Counter {
static int count = 0; // ONE copy shared by every object
int ownCount = 0; // one copy PER object
Counter() {
count++; // increases the shared one
ownCount++; // increases only this object's one
}
}
class Circle {
final double PI = 3.14159; // locked
void tryToChange() {
// PI = 3.14; ❌ compile error — it's final
}
}
public class Demo {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println("static count = " + Counter.count); // 3
System.out.println("c1.ownCount = " + c1.ownCount); // 1
System.out.println("c3.ownCount = " + c3.ownCount); // 1
}
}
Output
static count = 3
c1.ownCount = 1
c3.ownCount = 1
Exam tip
Don't mix up final, finally and finalize(). They sound alike and mean
completely different things:
| Keyword | What it is | Meaning |
|---|---|---|
final |
a modifier | Cannot change / cannot override / cannot extend |
finally |
a block | Always runs after try-catch |
finalize() |
a method | Called by the garbage collector (old, deprecated) |
Q17. What is the difference between this and super? ⭐⭐
In simple words
this= "me, right here" — the current objectsuper= "my parent" — the class I inherited from
Think of it like
You're filling a form. this.name = your name. super.name = your father's name.
The difference
this |
super |
|---|---|
| Current object | Parent object |
this() — call another constructor in this class |
super() — call the parent's constructor |
this.method() |
super.method() — the parent version |
this.field |
super.field |
Code
class Person {
String name;
Person(String name) {
this.name = name; // 'this' resolves the clash
System.out.println("Person created: " + name);
}
void show() {
System.out.println("Person name: " + name);
}
}
class Employee extends Person {
int empId;
Employee(String name, int empId) {
super(name); // MUST be the first line
this.empId = empId;
System.out.println("Employee created: " + empId);
}
@Override
void show() {
super.show(); // run the parent's version
System.out.println("Employee id: " + empId);
}
}
public class Demo {
public static void main(String[] args) {
Employee e = new Employee("Riya", 501);
System.out.println();
e.show();
}
}
Output
Person created: Riya
Employee created: 501
Person name: Riya
Employee id: 501
Exam tip
Notice the order: the parent constructor runs first, then the child's.
super() must be the very first line in the child constructor — no exceptions.
Q18. What are Collections — List, Set and Map? ⭐⭐
Appears in: Assignment 3 Q1 — and your PPT deck does not cover it at all
In simple words
A collection is a smart box that can grow and shrink. You don't have to decide the size in advance like with an array.
Think of it like
- List = a shopping list. Order matters. You can write "milk" twice.
- Set = a guest list. Order doesn't matter. No duplicates — one entry per person.
- Map = a phone book. You look up a name to get a number.
The difference
| List | Set | Map | |
|---|---|---|---|
| Duplicates? | ✅ Allowed | ❌ Not allowed | ❌ Keys unique |
| Order? | ✅ Kept | ❌ Usually not | Depends |
| Index? | ✅ get(0) |
❌ None | ❌ Key instead |
| Examples | ArrayList, LinkedList |
HashSet, TreeSet |
HashMap, TreeMap |
Important:
Mapis not a Collection. It sits on its own branch because it stores pairs, not single items. Say this — it's a favourite trap question.
Code
import java.util.*;
public class Demo {
public static void main(String[] args) {
// ---- LIST: ordered, duplicates allowed ----
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Java"); // duplicate kept
System.out.println("List : " + list);
System.out.println("size : " + list.size()); // 3
System.out.println("get(0): " + list.get(0));
// ---- SET: no duplicates, no order ----
HashSet<String> set = new HashSet<>(list);
System.out.println("Set : " + set);
System.out.println("size : " + set.size()); // 2 — duplicate gone
// ---- SORTED SET ----
TreeSet<Integer> sorted = new TreeSet<>();
sorted.add(5);
sorted.add(1);
sorted.add(9);
sorted.add(1); // ignored
System.out.println("TreeSet: " + sorted); // sorted
// ---- MAP: key -> value ----
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Aarav");
students.put(102, "Diya");
students.put(101, "Replaced"); // same key -> overwritten
System.out.println("Map : " + students);
System.out.println("get(101): " + students.get(101));
System.out.println("size : " + students.size()); // 2
}
}
Output
List : [Java, Python, Java]
size : 3
get(0): Java
Set : [Java, Python]
size : 2
TreeSet: [1, 5, 9]
Map : {101=Replaced, 102=Diya}
get(101): Replaced
size : 2
Exam tip
Three questions come up again and again:
| Pair | Winner |
|---|---|
| ArrayList vs LinkedList | ArrayList for reading, LinkedList for inserting/deleting |
| HashSet vs TreeSet | HashSet is faster, TreeSet is sorted |
| HashMap vs TreeMap | HashMap is faster, TreeMap is sorted by key |
Q19. What is multithreading? ⭐⭐
Appears in: Assignment 3 Q3, Q4 — also missing from your PPT deck
In simple words
Multithreading means running several tasks at the same time inside one program.
Think of it like
One chef (the program) with four burners (threads). Cooking pasta on one while the sauce simmers on another. One kitchen, several things happening at once.
Two ways to create a thread
Way 1 — extend Thread
class MyThread extends Thread {
public void run() {
System.out.println("Running: " + getName());
}
}
MyThread t = new MyThread();
t.start();
Way 2 — implement Runnable ← the better way
class MyTask implements Runnable {
public void run() {
System.out.println("Running: " + Thread.currentThread().getName());
}
}
Thread t = new Thread(new MyTask(), "MyThread-1");
t.start();
Why Runnable is preferred
Because extends Thread uses up your one inheritance slot — you can't extend
anything else afterwards. Runnable leaves that slot free.
start() vs run() — always asked
start() |
run() |
|---|---|
| Creates a new thread | Just a normal method call |
| Runs at the same time | Runs one after another |
| Call once only | Can call many times |
The thread life cycle
NEW
│ start()
▼
RUNNABLE ◄──────────┐
│ │
│ sleep/wait │ wake up
▼ │
WAITING/BLOCKED ─────┘
│
│ run() finishes
▼
TERMINATED
The six states (Java's Thread.State enum): NEW → RUNNABLE → BLOCKED /
WAITING / TIMED_WAITING → TERMINATED.
Careful: Java actually has six states, not five.
BLOCKED(waiting for a lock),WAITING(indefinitewait()/join()) andTIMED_WAITING(sleep(ms)) are three separate states. If the paper asks you to draw the life cycle, the classic diagram uses five boxes — New, Runnable, Running, Blocked, Dead — which is fine for the drawing. But if it asks you to name the states, give all six.
Code — two threads with a shared counter
class Counter {
private int count = 0;
// synchronized = only one thread at a time may run this
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
class Worker implements Runnable {
private Counter counter;
Worker(Counter c) { this.counter = c; }
public void run() {
for (int i = 0; i < 100000; i++) {
counter.increment();
}
}
}
public class Demo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(new Worker(counter), "Thread-1");
Thread t2 = new Thread(new Worker(counter), "Thread-2");
t1.start();
t2.start();
t1.join(); // wait for t1 to finish
t2.join(); // wait for t2 to finish
System.out.println("Expected: " + 200000);
System.out.println("Actual : " + counter.getCount());
}
}
Output
Expected: 200000
Actual : 200000
Exam tip
Run it without synchronized and the actual count comes out lower — like
174823. That's a race condition. Write both outputs in your answer; it explains
the concept better than words can.
Q20. How do you create a custom exception? ⭐⭐
Appears in: sample paper by name — InvalidAgeException
In simple words
Java has many built-in errors, but sometimes you need your own. You make one by
extending Exception.
Think of it like
Java gives you "wrong password" and "file missing". But "age below 18" is your rule — so you invent your own error for it.
The three steps
- Make a class that
extends Exception - Give it a constructor that passes the message up with
super(message) throwit when the rule is broken
Code
// Step 1 + 2: define your own exception
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message); // hand the message to Java
}
}
public class Demo {
// Step 3: throw it when the rule breaks
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is below 18");
}
System.out.println("Age " + age + " accepted");
}
public static void main(String[] args) {
int[] ages = {25, 15, 18, 10};
for (int age : ages) {
try {
checkAge(age);
} catch (InvalidAgeException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
}
Output
Age 25 accepted
Rejected: Age 15 is below 18
Age 18 accepted
Rejected: Age 10 is below 18
Exam tip
Three things the examiner looks for:
1. extends Exception
2. super(message) inside the constructor
3. throws InvalidAgeException on the method signature
Miss any one and you lose a mark.
Q21. How do you use the String methods? ⭐⭐
Appears in: Question Bank Ch7 Q1
In simple words
String comes with dozens of ready-made tools. You'll be asked about the common ones.
The methods you need
| Method | What it does | Example | Result |
|---|---|---|---|
length() |
count of characters | "Hello".length() |
5 |
charAt(i) |
character at position | "Hello".charAt(1) |
e |
substring(a,b) |
piece from a to b | "Hello".substring(1,4) |
ell |
toUpperCase() |
all capitals | "abc".toUpperCase() |
ABC |
toLowerCase() |
all small | "ABC".toLowerCase() |
abc |
trim() |
removes spaces at the ends | " hi ".trim() |
hi |
indexOf(x) |
position of x | "Hello".indexOf('l') |
2 |
replace(a,b) |
swap text | "cat".replace("c","b") |
bat |
split(",") |
break into pieces | "a,b".split(",") |
[a, b] |
equals(x) |
compare contents | "a".equals("a") |
true |
Code
public class Demo {
public static void main(String[] args) {
String s = " Hello Java ";
System.out.println("1. " + s.length()); // 14
System.out.println("2. [" + s.trim() + "]"); // [Hello Java]
System.out.println("3. " + s.trim().toUpperCase()); // HELLO JAVA
System.out.println("4. " + s.trim().charAt(0)); // H
System.out.println("5. " + s.trim().substring(0, 5)); // Hello
System.out.println("6. " + s.trim().indexOf("Java")); // 6
System.out.println("7. " + s.trim().replace("Java","C++"));
String csv = "Aarav,Diya,Kabir";
String[] names = csv.split(",");
System.out.print("8. ");
for (String n : names) System.out.print(n + " ");
System.out.println("\n9. " + "Java".equals("Java"));
System.out.println("10. " + "Java".equals("java")); // case matters
System.out.println("11. " + "Java".equalsIgnoreCase("java"));
}
}
Output
1. 14
2. [Hello Java]
3. HELLO JAVA
4. H
5. Hello
6. 6
7. Hello C++
8. Aarav Diya Kabir
9. true
10. false
11. true
Exam tip
length() is a method with brackets. array.length is a field without
brackets. Java loves testing that difference.
PART 3 · Quick Answers — All 41 Question-Bank Questions
Compressed for revision. Full answers for the important ones are in Part 2.
Chapter 1 · Unit 1 — OOP and Java
| # | Question | Answer in brief |
|---|---|---|
| 1.1 | Define OOP and its principles | Programming built around objects holding data + methods. Four pillars: encapsulation, inheritance, polymorphism, abstraction |
| 1.2 | Encapsulation with example | private fields + public getters/setters. Hides data, allows validation |
| 1.3 | Class vs object | Class = plan, no memory. Object = real instance, on heap |
| 1.4 | Importance of Java as OOP | Platform independent, secure, robust, multithreaded, no pointers, garbage collected |
| 1.5 | Bytecode vs machine code | Bytecode runs on any JVM (.class). Machine code runs on one CPU (.exe) |
| 1.6 | Role of JVM, JDK, JRE | JVM runs · JRE = JVM + libraries · JDK = JRE + tools. JDK ⊃ JRE ⊃ JVM |
Chapter 2 · Unit 2 — Language Basics
| # | Question | Answer in brief |
|---|---|---|
| 2.1 | Primitive types and defaults | 8 types. byte/short/int/long default 0; float/double 0.0; char '\u0000'; boolean false |
| 2.2 | Type conversion and casting | Widening = automatic, small→big, safe. Narrowing = manual cast, big→small, may lose data |
| 2.3 | Operators | 8 families: arithmetic, relational, logical, bitwise, assignment, unary, ternary, instanceof |
| 2.4 | Scope and lifetime | Local (in a block, dies at block end) · Instance (per object) · Static (one shared copy) |
| 2.5 | Dynamic initialization | Value set at run time by an expression — int sum = a + b; |
Chapter 3 · Unit 2 — Control Statements
| # | Question | Answer in brief |
|---|---|---|
| 3.1 | if-else and switch | if for any boolean condition; switch for equality against constants. break stops fall-through |
| 3.2 | while vs for | while when count unknown; for when count known. do-while runs at least once |
| 3.3 | Jump statements | break (exit loop) · continue (skip iteration) · return (exit method) |
| 3.4 | Program: conditional + looping | See Part 5, program 11 |
| 3.5 | break vs continue | break exits entirely. continue skips one round |
Chapter 4 · Unit 3 — Arrays
| # | Question | Answer in brief |
|---|---|---|
| 4.1 | Arrays and their types | Fixed-size, same-type, indexed from 0. 1D, 2D, multidimensional, jagged |
| 4.2 | Multidimensional arrays | Array of arrays. m.length = rows, m[0].length = columns |
| 4.3 | Largest element program | See Part 5, program 3 |
| 4.4 | Arrays in memory | Objects on the heap, contiguous, accessed by address + i × size |
| 4.5 | Passing arrays to functions | Reference is passed by value — you can change contents, but not the reference |
Chapter 5 · Unit 4 — Classes and Constructors
| # | Question | Answer in brief |
|---|---|---|
| 5.1 | Classes and objects | class Student { } declares; Student s = new Student(); creates |
| 5.2 | Constructors | Same name as class, no return type, runs on new. Five types |
| 5.3 | Overloading vs overriding | Tier 1 — see Part 2, Q3 |
| 5.4 | Garbage collection | JVM automatically frees objects with no references. Cannot be forced |
| 5.5 | static vs final | static = shared by class. final = locked. See Part 2, Q16 |
Chapter 6 · Unit 4 — Inheritance
| # | Question | Answer in brief |
|---|---|---|
| 6.1 | Inheritance with example | class Dog extends Animal. IS-A relationship. See Part 2, Q4 |
| 6.2 | super keyword |
Calls parent constructor, method or field. Must be first line. See Part 2, Q17 |
| 6.3 | Method overriding | Same name/params in child. Rules: no reducing access, no final, no static, no private |
| 6.4 | Abstract classes | abstract keyword. Cannot be instantiated. Can have constructors and normal methods |
| 6.5 | Dynamic method dispatch | Animal a = new Dog(); a.sound(); → runs Dog's version. Decided at run time |
Chapter 7 · Unit 7 — Strings, Interfaces, Packages
| # | Question | Answer in brief |
|---|---|---|
| 7.1 | String manipulation | See Part 2, Q21 |
| 7.2 | Class vs interface | Class = can be instantiated, has constructors. Interface = contract only, many allowed |
| 7.3 | Program implementing an interface | See Part 2, Q5 |
| 7.4 | Purpose of packages | Avoid name clashes, group classes, control access. javac -d . creates them |
| 7.5 | Enumerations | enum Day { MON, TUE, WED } — fixed set of named constants, type-safe |
Chapter 8 · Unit 5 — Exceptions
| # | Question | Answer in brief |
|---|---|---|
| 8.1 | Exceptions and types | Checked (compiler forces handling) vs unchecked (run time) vs Error (not recoverable) |
| 8.2 | try-catch handling | See Part 2, Q7 |
| 8.3 | Multi-catch program | catch (ArithmeticException \| NullPointerException e) { } — Java 7+ |
| 8.4 | Checked vs unchecked | See Part 2, Q8 |
| 8.5 | Significance of finally |
Always runs — even with return. Used for cleanup |
PART 4 · The 3 Assignments, Solved
Assignment 1
Q1 — Compiler vs interpreter
| Compiler | Interpreter |
|---|---|
| Translates the whole program at once | Translates line by line |
Produces a file (.class) |
Produces no file |
| Faster to run | Slower to run |
| Reports all errors together | Stops at the first error |
| C, C++, Java | Python, JavaScript |
Java uses both.
javaccompiles to bytecode; the JVM interprets it.
Q2 — Features of OOP — Encapsulation, inheritance, polymorphism, abstraction, classes and objects, message passing, dynamic binding, reusability.
Q3 — Class vs object — See Part 2, Q1.
Q4 — Types of operators — See Part 2, Q12.
Q5 — Java tokens and data types
Tokens = smallest meaningful pieces of a program:
| Token | Examples |
|---|---|
| Keywords | class, int, new, if |
| Identifiers | Student, main, rollNo |
| Literals | 10, 3.14, 'A', "Hi", true |
| Operators | + - * / = == |
| Separators | ( ) { } [ ] ; , |
Data types — See Part 2, Q11.
Assignment 2
Q1 — Multiple inheritance (circle and square) — See Part 2, Q5. Full program is there.
Q2 — Interface with example — Same as above. Add: "An interface defines what a class must do, but not how."
Q3 — Constructor and overloading — See Part 2, Q2. Include all five types.
Q4 — Method overriding and its rules
The rules (worth full marks):
- Same method name
- Same parameters
- Same return type (or a subclass of it)
- Cannot reduce the access modifier
finalmethods cannot be overriddenstaticmethods cannot be overridden — only hiddenprivatemethods cannot be overridden- Constructors cannot be overridden
- Cannot throw broader checked exceptions
- Use
@Overrideso the compiler checks you
Q5 — Superclass and subclass
Superclass = parent (features come from here). Subclass = child (inherits and adds). See Part 2, Q4.
Assignment 3
Q1 — Java Collection — See Part 2, Q18.
Q2 — Packages — See Part 2, Q15.
Q3 — Thread states, properties, synchronization — See Part 2, Q19.
Q4 — Thread life cycle — Draw this:
NEW ──start()──► RUNNABLE ──┬──► WAITING / BLOCKED
▲ │ (sleep, wait, join)
└─────────┘
│
run() ends
▼
TERMINATED
Q5 — try, catch, finally
| Block | Job |
|---|---|
try |
Holds the risky code |
catch |
Handles the error if it happens |
finally |
Always runs — cleanup |
See Part 2, Q7 for the full program.
PART 5 · 12 Programs to Memorise
Each is short enough to write in an exam. Outputs are real.
Program 1 · Second largest (no sorting) 🔥
public class SecondLargest {
public static void main(String[] args) {
int[] a = {12, 45, 7, 89, 89, 23, 56};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int n : a) {
if (n > first) {
second = first;
first = n;
} else if (n > second && n != first) {
second = n;
}
}
System.out.println("First = " + first);
System.out.println("Second = " + second);
}
}
First = 89
Second = 56
Program 2 · Largest in a 2D array
public class Largest2D {
public static void main(String[] args) {
int[][] m = {{7,3,-5,10}, {11,13,-15,2}};
int max = m[0][0];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
if (m[i][j] > max) max = m[i][j];
System.out.println("Largest = " + max);
}
}
Largest = 13
Program 3 · Remove duplicates and sort 🔥
import java.util.*;
public class UniqueSorted {
public static void main(String[] args) {
int[] a = {5, 3, 8, 3, 1, 5, 9, 1};
TreeSet<Integer> set = new TreeSet<>();
for (int n : a) set.add(n);
System.out.println("Original : " + Arrays.toString(a));
System.out.println("Unique : " + set);
}
}
Original : [5, 3, 8, 3, 1, 5, 9, 1]
Unique : [1, 3, 5, 8, 9]
Program 4 · Reverse a number
public class Reverse {
public static void main(String[] args) {
int n = 12345, rev = 0;
while (n != 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
System.out.println("Reversed = " + rev);
}
}
Reversed = 54321
Program 5 · Prime check
public class Prime {
public static void main(String[] args) {
int n = 29;
boolean isPrime = true;
if (n <= 1) isPrime = false;
else
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) { isPrime = false; break; }
System.out.println(n + " is " + (isPrime ? "prime" : "not prime"));
}
}
29 is prime
Program 6 · Fibonacci
public class Fibonacci {
public static void main(String[] args) {
int a = 0, b = 1;
System.out.print("0 1 ");
for (int i = 3; i <= 10; i++) {
int next = a + b;
System.out.print(next + " ");
a = b;
b = next;
}
System.out.println();
}
}
0 1 1 2 3 5 8 13 21 34
Program 7 · Matrix multiplication 3×3
public class MatrixMul {
public static void main(String[] args) {
int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
int[][] b = {{9,8,7},{6,5,4},{3,2,1}};
int[][] c = new int[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < 3; k++)
c[i][j] += a[i][k] * b[k][j];
for (int[] row : c) {
for (int v : row) System.out.printf("%4d", v);
System.out.println();
}
}
}
30 24 18
84 69 54
138 114 90
Program 8 · Palindrome
public class Palindrome {
public static void main(String[] args) {
String s = "madam";
String rev = new StringBuilder(s).reverse().toString();
System.out.println(s + " -> " + (s.equals(rev) ? "palindrome" : "not"));
}
}
madam -> palindrome
Program 9 · Constructor overloading 🔥
class Box {
double w, h, d;
Box() { this(1, 1, 1); } // chains to the 3-arg one
Box(double side) { this(side, side, side); }
Box(double w, double h, double d) {
this.w = w; this.h = h; this.d = d;
}
double volume() { return w * h * d; }
}
public class Demo {
public static void main(String[] args) {
System.out.println(new Box().volume()); // 1.0
System.out.println(new Box(5).volume()); // 125.0
System.out.println(new Box(2,3,4).volume()); // 24.0
}
}
1.0
125.0
24.0
Program 10 · Custom exception 🔥
See Part 2, Q20. That is the exact program.
Program 11 · Control statements
public class Control {
public static void main(String[] args) {
int marks = 78;
if (marks >= 90) System.out.println("A");
else if (marks >= 75) System.out.println("B");
else System.out.println("C");
int day = 3;
switch (day) {
case 1: System.out.println("Mon"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("Other");
}
for (int i = 1; i <= 5; i++) System.out.print(i + " ");
System.out.println();
}
}
B
Wed
1 2 3 4 5
Program 12 · Threads with shared counter 🔥
See Part 2, Q19. That is the exact program.
PART 6 · Cheat Tables
6.1 The 10 tables you must know cold
| # | Comparison | The one thing to remember |
|---|---|---|
| 1 | JDK / JRE / JVM | JDK ⊃ JRE ⊃ JVM. Write, run, execute |
| 2 | Class vs object | Plan vs thing. No memory vs memory |
| 3 | Overloading vs overriding | Same class/different inputs vs parent-child/same inputs |
| 4 | Abstract class vs interface | Can have constructors + code vs contract only, many allowed |
| 5 | Checked vs unchecked | Compiler forces you vs blows up at run time |
| 6 | String / StringBuffer / StringBuilder | Immutable vs thread-safe mutable vs fast mutable |
| 7 | ArrayList vs LinkedList | Fast reading vs fast inserting |
| 8 | HashSet vs TreeSet | Fast but unordered vs sorted but slower |
| 9 | HashMap vs TreeMap | Fast but unordered vs sorted by key |
| 10 | Process vs thread | Own memory vs shared memory |
6.2 The final family — don't confuse these
| Keyword | Type | Meaning |
|---|---|---|
final |
modifier | Cannot change / override / extend |
finally |
block | Always runs after try-catch |
finalize() |
method | Called by garbage collector (deprecated) |
6.3 Exception hierarchy
Throwable
├── Exception
│ ├── RuntimeException ← UNCHECKED
│ │ ├── ArithmeticException
│ │ ├── NullPointerException
│ │ ├── ArrayIndexOutOfBoundsException
│ │ └── NumberFormatException
│ └── IOException ← CHECKED
│ ├── FileNotFoundException
│ └── SQLException
└── Error ← do NOT catch
├── OutOfMemoryError
└── StackOverflowError
6.4 Output one-liners
| Expression | Output | Why |
|---|---|---|
10 + 20 + "Java" + 10 + 20 |
30Java1020 |
Numbers add first, then everything becomes text |
10 / 3 |
3 |
Integer division drops decimals |
10 / 3.0 |
3.3333... |
One side is a decimal, so the answer is |
10 % 3 |
1 |
Remainder |
(int) 9.99 |
9 |
Truncates, doesn't round |
5 & 3 |
1 |
Bitwise AND |
5 \| 3 |
7 |
Bitwise OR |
'A' + 1 |
66 |
char becomes a number |
(char)('A' + 1) |
B |
Number back to a letter |
"Java" == "Java" |
true |
Same object in the pool |
"Java" == new String("Java") |
false |
Different objects |
"Java".equals(new String("Java")) |
true |
Same letters |
PART 7 · Last 6 Hours
Hour 1 — The four pillars (Q9)
Read Part 2, Q9. Copy the program by hand. Once you can write that from memory, you can answer any "explain OOP" question.
Hour 2 — Overloading vs overriding (Q3)
Read Part 2, Q3. Write the table five times. Then write both programs once.
Hour 3 — Constructors and inheritance (Q2, Q4)
Read both. Write the constructor-overloading program (Part 5, Program 9). Then draw the five inheritance diagrams from memory.
Hour 4 — Interfaces and abstract classes (Q5, Q6)
Read both. Write the Shape / Measurable program (Part 2, Q5).
That single program answers Assignment 2 Q1 and Q2.
Hour 5 — Exceptions (Q7, Q8, Q20)
Read all three. Write InvalidAgeException from memory. It is asked by name in the
sample paper.
Hour 6 — Collections and threads (Q18, Q19)
These are the two topics your PPT deck never covered. Read both carefully. Then read Part 6's cheat tables and Part 3's quick answers.
The 5-minute final check
Before you walk in, confirm you can do these from memory:
- ☐ Write "class vs object" as a 4-row table
- ☐ Write "overloading vs overriding" as a 4-row table
- ☐ Write the constructor-overloading program
- ☐ Write
InvalidAgeException - ☐ Draw the thread life cycle
- ☐ Say why Java can't do multiple class inheritance (diamond problem)
- ☐ Say what
finallydoes even whentryhas areturn - ☐ Explain
10 + 20 + "Java" + 10 + 20
If you can do all eight, you are ready.
The three mistakes that cost the most marks
| Mistake | Fix |
|---|---|
| Writing a definition and stopping | Add a code example and its output. That's 2 of the 5 marks |
| Answering both sides of an OR | Answer one. The second one wastes 12 minutes |
Forgetting import java.util.*; |
Any program using ArrayList, HashMap or Scanner needs it |
Built from your 13 PDFs (261 slides), the 3 assignments, the 41-question bank, and
the college repository github.com/asvi9/Java_Notes.