[Go to site: main page, start]

0% found this document useful (0 votes)
3 views113 pages

Java Programming

The document provides an introduction to Java, detailing its evolution, object-oriented programming structure, and key characteristics. It explains the Java compilation and execution process, the organization of the Java Virtual Machine (JVM), and the relationship between JDK, JRE, and JVM. Additionally, it covers platform independence, security features, naming conventions, data types, and type casting in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views113 pages

Java Programming

The document provides an introduction to Java, detailing its evolution, object-oriented programming structure, and key characteristics. It explains the Java compilation and execution process, the organization of the Java Virtual Machine (JVM), and the relationship between JDK, JRE, and JVM. Additionally, it covers platform independence, security features, naming conventions, data types, and type casting in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT I: INTRODUCTION TO JAVA

1. Evolution of Java

Definition

Java is a high-level, class-based, object-oriented programming language


developed by James Gosling at Sun Microsystems in 1995. It was
originally called Oak and later renamed Java.

Key Points

 Developed by James Gosling and team (Green Team)

 First public release: Java 1.0 in 1996

 Acquired by Oracle Corporation in 2010

 Designed with the motto: "Write Once, Run Anywhere" (WORA)

Timeline

Year Event

1991 Project started as "Oak"

Renamed to Java, released


1995
publicly

1996 JDK 1.0 released

J2SE 5.0 (major features like


2004
Generics)

Oracle acquires Sun


2010
Microsystems

2014
Java 8, 11, 17 LTS versions
+

Real-Life Analogy

Think of Java like a universal translator—you write code once, and it


can run on Windows, Mac, Linux, or mobile devices without changes.

Memory Trick

"JAMES GOT JAVA" — James Gosling, 1995, Oak renamed, Sun


Microsystems

2. Object-Oriented Programming Structure

Definition
Object-Oriented Programming (OOP) is a programming paradigm based on
the concept of objects, which contain data (attributes) and code
(methods).

Four Pillars of OOP

Pillar Description

Encapsulati Wrapping data and methods into a single unit


on (class)

Hiding implementation details, showing only


Abstraction
functionality

Acquiring properties of parent class by child


Inheritance
class

Polymorphi One name, multiple forms


sm (overloading/overriding)

Real-Life Analogy

Concept Real-Life Example

Class Blueprint of a house

Object Actual house built from blueprint

Encapsulatio
Capsule containing medicine
n

Inheritance Child inheriting traits from parents

Polymorphis
A person acting as teacher, parent, friend
m

Car dashboard (you see speed, not engine


Abstraction
mechanics)

Key Points

 Everything in Java is inside a class

 Java does not support multiple inheritance through classes (uses


interfaces)

 Promotes code reusability and modularity

Definition

Java is a robust, secure, platform-independent, high-performance,


multithreaded programming language.
Key Characteristics

Feature Description

Easy to learn, removes complex features like


Simple
pointers

Object-Oriented Everything is an object

Platform
Bytecode runs on any JVM
Independent

Secure No explicit pointers, bytecode verification

Strong memory management, exception


Robust
handling

Portable Same behavior across platforms

Multithreaded Supports concurrent execution

Dynamic Supports dynamic loading of classes

Distributed Built-in support for networking

High
JIT compiler optimizes bytecode
Performance

Simple Explanation

Java removed risky features from C/C++ like pointers and manual memory
management. It has automatic garbage collection and strong type
checking.

Memory Trick

"SIMPLE RODS PHD"

 Simple

 Interpreted

 Multithreaded

 Platform Independent

 Lightweight (Portable)

 Easy to learn

 Robust

 Object-Oriented
 Dynamic

 Secure

 Performance (High)

 High-level

 Distributed

4. Java Program Compilation and Execution Process

Definition

The process by which Java source code (.java) is converted to bytecode


(.class) and then executed by the JVM.

Step-by-Step Process

┌──────────────────┐

│ Source Code │

│ (.java file) │

└────────┬─────────┘

▼ javac (Java Compiler)

┌──────────────────┐

│ Bytecode │

│ (.class file) │

└────────┬─────────┘

▼ Class Loader

┌──────────────────┐

│ Bytecode │

│ Verifier │

└────────┬─────────┘

▼ JVM (Java Virtual Machine)

┌──────────────────┐
│ Interpreter / │

│ JIT Compiler │

└────────┬─────────┘


┌──────────────────┐

│ Machine Code │

│ (Execution) │

└──────────────────┘

Key Components

Component Role

javac Compiles .java to .class (bytecode)

Class Loader Loads .class files into memory

Bytecode
Checks code for security violations
Verifier

Interpreter Executes bytecode line by line

Compiles frequently used bytecode to


JIT Compiler
native code

Example

Source Code ([Link]):

public class Hello {

public static void main(String[] args) {

[Link]("Hello, World!");

Compilation:

javac [Link]

This creates [Link]

Execution:
java Hello

Output:

Hello, World!

Line-by-Line Explanation

1. public class Hello — Declares a public class named Hello

2. public static void main(String[] args) — Entry point of the program

3. [Link](...) — Prints text to console

5. Organization of Java Virtual Machine (JVM)

Definition

JVM is an abstract computing machine that enables a computer to run


Java programs. It converts bytecode into machine-specific code.

JVM Architecture

┌─────────────────────────────────────────────────────────────

│ JVM │

├─────────────────────────────────────────────────────────────

│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────┐ │

│ │ Class Loader │ │ Runtime Memory │ │ Execution │ │

│ │ Subsystem │ │ Areas │ │ Engine │ │

│ └─────────────────┘ └─────────────────┘ └─────────────┘ │

├─────────────────────────────────────────────────────────────

│ Native Method Interface │

├─────────────────────────────────────────────────────────────

│ Native Method Libraries │

└─────────────────────────────────────────────────────────────

Components of JVM

1. Class Loader Subsystem


 Loading: Reads .class files

 Linking: Verifies, prepares, resolves references

 Initialization: Executes static blocks

2. Runtime Data Areas

Area Description

Stores class structures, methods,


Method Area
constants

Heap Stores objects and instance variables

Stack Stores method frames, local variables

PC Register Address of current instruction

Native Method
For native (non-Java) methods
Stack

3. Execution Engine

 Interpreter: Executes bytecode line by line

 JIT Compiler: Compiles hot spots to native code

 Garbage Collector: Automatically frees unused memory

Key Points

 JVM is platform-dependent (different for each OS)

 Bytecode is platform-independent

 JVM provides security through bytecode verification

Memory Trick

"CLREM" for JVM components:

 Class Loader

 Linking

 Runtime Data Areas

 Execution Engine

 Memory Management (GC)

6. Relation Between JVM, JRE, and JDK

Definitions
Compone
Full Form Description
nt

Complete development
JDK Java Development Kit
environment

Java Runtime
JRE Runtime libraries + JVM
Environment

JVM Java Virtual Machine Executes bytecode

Relationship Diagram

┌─────────────────────────────────────────────────────────┐

│ JDK │

│ ┌───────────────────────────────────────────────────┐ │

│ │ JRE │ │

│ │ ┌─────────────────────────────────────────────┐ │ │

│ │ │ JVM │ │ │

│ │ │ (Executes bytecode) │ │ │

│ │ └─────────────────────────────────────────────┘ │ │

│ │ + Java Libraries ([Link], etc.) │ │

│ └───────────────────────────────────────────────────┘ │

│ + Development Tools (javac, javadoc, jar, etc.) │

└─────────────────────────────────────────────────────────┘

Comparison Table

Feature JVM JRE JDK


Contains JVM ✓ ✓
(itself)


Contains JRE ✗ ✓
(itself)

Contains Dev Tools ✗ ✗ ✓

Used for Running ✓ ✓ ✓

Used for
✗ ✗ ✓
Development
Feature JVM JRE JDK

Smalle Mediu Larges


Size
st m t

Key Points

 To run a Java program: You need JRE

 To develop a Java program: You need JDK

 JDK = JRE + Development Tools

 JRE = JVM + Libraries

Real-Life Analogy

 JDK = Full kitchen (cooking tools + eating utensils + ingredients)

 JRE = Dining set (only for eating/running)

 JVM = Mouth (actually consumes/executes the food)

``7. Platform Independence and Portability

Definition

Platform independence means Java code can run on any operating system
without modification. Portability means the same compiled code produces
identical results across platforms.

How Java Achieves This

┌─────────────────┐

│ Java Source │

│ (.java) │

└────────┬────────┘

│ javac


┌─────────────────┐

│ Bytecode │ ← Platform Independent

│ (.class) │

└────────┬────────┘

┌────┴────┬────────┬────────┐
▼ ▼ ▼ ▼
┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐

│Windows│ │ Linux │ │ macOS │ │Android│

│ JVM │ │ JVM │ │ JVM │ │ JVM │

└───────┘ └───────┘ └───────┘ └───────┘

Key Points

 Source code → Bytecode (platform-independent)

 Bytecode → Machine code (done by JVM, platform-specific)

 "Write Once, Run Anywhere" (WORA)

Comparison with C/C++

Feature Java C/C++

Output Bytecode Machine code

Independe
Platform Dependent
nt

Needs Yes, for each


No
recompilation platform

Intermediate
Yes (.class) No
format

8. Security in Java

Definition

Java provides multiple layers of security to protect systems from malicious


code.

Security Features

Feature Description

Cannot access arbitrary memory


No Pointers
locations

Bytecode
Checks code before execution
Verification

Class Loader Separates local and network classes


Feature Description

Security
Controls access to system resources
Manager

Sandbox Model Restricts applet capabilities

Exception Prevents crashes from runtime


Handling errors

Garbage
Prevents memory leaks
Collection

Security Layers

┌─────────────────────────────────┐

│ Java Application │

├─────────────────────────────────┤

│ Security Manager │

├─────────────────────────────────┤

│ Bytecode Verifier │

├─────────────────────────────────┤

│ Class Loader │

├─────────────────────────────────┤

│ Java Virtual Machine │

└─────────────────────────────────┘

Key Points

 Java is strongly typed (type safety)

 Array bounds checking prevents buffer overflow

9. Introduction to JAR Format

Definition

JAR (Java Archive) is a package file format used to aggregate multiple Java
class files, metadata, and resources into a single file.

Key Points

 Extension: .jar

 Based on ZIP file format


 Contains: .class files, images, audio, manifest file

 Manifest file: META-INF/[Link]

Creating a JAR File

jar cvf [Link] *.class

Running a JAR File

java -jar [Link]

Manifest File Example

Manifest-Version: 1.0

Main-Class: MainClassName

Advantages

 Compact distribution

 Easy deployment

 Faster downloads (compressed)

 Version control through manifest

10. Naming Conventions in Java

Definition

Naming conventions are guidelines for naming identifiers in Java to


improve code readability.

Conventions Table

Identifi
Convention Example
er

PascalCase (start StudentRecord,


Class
uppercase) BankAccount

Interfa
PascalCase Runnable, Serializable
ce

camelCase (start calculateTotal(),


Method
lowercase) getName()

Variabl studentName,
camelCase
e totalAmount
Identifi
Convention Example
er

Consta ALL_CAPS with


MAX_VALUE, PI
nt underscores

Packag
all lowercase [Link], [Link]
e

Rules for Identifiers

1. Can contain letters, digits, underscore (_), dollar sign ($)

2. Cannot start with a digit

3. Cannot be a reserved keyword

4. Case-sensitive

Valid vs Invalid

Invali
Valid Reason
d

2myV
myVar Starts with digit
ar

my- Contains
_value
var hyphen

Reserved
$price class
keyword

student my
Contains space
1 var

Viva Questions

1. What naming convention is used for classes?

2. How should constants be named in Java?

3. Is _123 a valid identifier?

11. Data Types in Java

Definition

Data types specify the type and size of values that can be stored in
variables.

Categories
Data Types

┌───────┴───────┐

▼ ▼
Primitive Reference

│ │

┌───┴───┐ ┌───┴───┐

│ │ │ │

Numeric Non-Numeric Class Array

│ │ Interface String

│ │

┌──┴──┐ ┌─┴──┐

│ │ │ │

Integer Float char boolean

Primitive Data Types

Defau
Type Size Range Example
lt

byte 1 byte 0 -128 to 127 byte b = 100;

2 -32,768 to short s =
short 0
bytes 32,767 5000;

4
int 0 -2³¹ to 2³¹-1 int i = 100000;
bytes

8 long l =
long 0L -2⁶³ to 2⁶³-1
bytes 100000L;

4
float 0.0f ±3.4E38 float f = 10.5f;
bytes

8 double d =
double 0.0d ±1.7E308
bytes 99.99;

2 '\
char 0 to 65,535 char c = 'A';
bytes u0000'

boolea 1 bit false true/false boolean b =


Defau
Type Size Range Example
lt

n true;

Memory Trick for Sizes

"1-2-4-8" (byte-short-int-long) and "4-8" (float-double)

Reference Data Types

 Class types

 Interface types

 Array types

 String (special class)

Example Program

public class DataTypesDemo {

public static void main(String[] args) {

// Primitive types

byte age = 25;

short year = 2024;

int population = 1000000;

long distance = 9876543210L;

float price = 99.99f;

double pi = 3.14159265359;

char grade = 'A';

boolean isPassed = true;

// Reference type

String name = "Java";

[Link]("Age: " + age);

[Link]("Name: " + name);

}
}

Output:

Age: 25

Name: Java

12. Type Casting in Java

Definition

Type casting is converting a value from one data type to another.

Types of Casting

Type Casting

┌───────┴───────┐

▼ ▼
Implicit Explicit

(Widening) (Narrowing)

Automatic Manual

byte → short → int → long → float → double

← Widening (automatic)

→ Narrowing (manual)

1. Implicit Casting (Widening)

Automatic conversion from smaller to larger type.

int num = 100;

double d = num; // int to double (automatic)

[Link](d); // Output: 100.0

2. Explicit Casting (Narrowing)

Manual conversion from larger to smaller type.

double d = 100.99;

int num = (int) d; // double to int (manual)

[Link](num); // Output: 100 (decimal truncated)


Casting Hierarchy

Directio Data
Type Syntax
n Loss

Widenin Implici double d =


No
g t intVar;

Narrowin Explici int i =


Possible
g t (int)doubleVar;

Example Program

public class TypeCastingDemo {

public static void main(String[] args) {

// Widening (Implicit)

int i = 100;

long l = i; // int to long

float f = l; // long to float

double d = f; // float to double

[Link]("Double: " + d);

// Narrowing (Explicit)

double price = 99.99;

int rounded = (int) price;

[Link]("Rounded: " + rounded);

// char to int

char ch = 'A';

int ascii = ch;

[Link]("ASCII of A: " + ascii);

Output:

Double: 100.0
Rounded: 99

ASCII of A: 65

Common Mistake

// ERROR: Cannot implicitly narrow

int x = 10.5; // Compilation error

// CORRECT:

int x = (int) 10.5; // x = 10

Viva Questions

1. What is type casting?

2. Difference between widening and narrowing?

3. What happens when you cast double to int?

13. Operators in Java

Definition

Operators are symbols that perform operations on variables and values.

Types of Operators

Category Operators

Arithmeti
+, -, *, /, %
c

Relationa ==, !=, >, <,


l >=, <=

Logical &&, `

Assignme =, +=, -=,


nt *=, /=, %=

Unary ++, --, +, -, !

Bitwise &, `

Ternary ?:

instanceo
instanceof
f

Arithmetic Operators
Operat Descriptio
Example
or n

+ Addition 5+3=8

- Subtraction 5 - 3 = 2

Multiplicati
* 5 * 3 = 15
on

5/3=1
/ Division
(integer)

% Modulus 5%3=2

Increment/Decrement

Synt
Type Description
ax

Increment first, then


Pre-increment ++a
use

Post- Use first, then


a++
increment increment

Pre- Decrement first, then


--a
decrement use

Post- Use first, then


a--
decrement decrement

Example Program

public class OperatorsDemo {

public static void main(String[] args) {

int a = 10, b = 5;

// Arithmetic

[Link]("a + b = " + (a + b));

[Link]("a % b = " + (a % b));

// Relational

[Link]("a > b: " + (a > b));


[Link]("a == b: " + (a == b));

// Logical

boolean x = true, y = false;

[Link]("x && y: " + (x && y));

[Link]("x || y: " + (x || y));

// Ternary

int max = (a > b) ? a : b;

[Link]("Max: " + max);

// Increment

int c = 5;

[Link]("c++: " + c++); // prints 5, then c becomes 6

[Link]("++c: " + ++c); // c becomes 7, then prints 7

Output:

a + b = 15

a%b=0

a > b: true

a == b: false

x && y: false

x || y: true

Max: 10

c++: 5

++c: 7

Operator Precedence (High to Low)


Priori
Operators
ty

1 (), [], .

++, --, !, ~
2
(unary)

3 *, /, %

4 +, -

5 <<, >>, >>>

6 <, <=, >, >=

7 ==, !=

8 &

9 ^

10 `

11 &&

12 `

13 ?:

14 =, +=, etc.

MCQs

Q1. What is the output of 5 / 2 in Java?

 a) 2.5

 b) 2 ✓

 c) 3

 d) 2.0

Q2. Which operator has highest precedence?

 a) +

 b) *

 c) () ✓

 d) &&

UNIT I: Important Questions


2-Mark Questions

1. What is bytecode?

2. Define JVM.

3. List any four features of Java.

4. What is type casting?

5. Define platform independence.

5-Mark Questions

1. Explain the compilation and execution process of a Java program


with diagram.

2. Differentiate between JDK, JRE, and JVM.

3. Explain any five characteristics of Java.

4. Describe primitive data types in Java with examples.

5. Explain various operators in Java with examples.

10-Mark Questions

1. Explain the architecture of JVM in detail with diagram.

2. Describe the evolution of Java and its key features.

3. Explain different data types in Java. Write a program demonstrating


type casting.

4. What is platform independence? How does Java achieve WORA?

UNIT I: Quick Revision Sheet

Topic Key Points

Java Creator James Gosling, Sun Microsystems, 1995

Original
Oak
Name

WORA Write Once, Run Anywhere

Encapsulation, Abstraction, Inheritance,


OOP Pillars
Polymorphism

JVM Executes bytecode

JRE JVM + Libraries

JDK JRE + Development Tools


Topic Key Points

Primitive 8 types: byte, short, int, long, float, double,


Types char, boolean

Widening Automatic (small → large)

Narrowing Manual (large → small)

UNIT II: OOPS IMPLEMENTATION

1. Classes and Objects

Definition

Class: A blueprint or template that defines the properties (attributes) and


behaviors (methods) of objects.

Object: An instance of a class that has actual values and can perform
actions.

Syntax

// Class Definition

class ClassName {

// Attributes (Instance Variables)

dataType variableName;

// Methods

returnType methodName(parameters) {

// method body

// Object Creation

ClassName objectName = new ClassName();

Example Program

// Class definition

class Student {

// Attributes
String name;

int rollNo;

double marks;

// Method

void displayDetails() {

[Link]("Name: " + name);

[Link]("Roll No: " + rollNo);

[Link]("Marks: " + marks);

// Main class

public class StudentDemo {

public static void main(String[] args) {

// Creating object

Student s1 = new Student();

// Assigning values

[Link] = "Rahul";

[Link] = 101;

[Link] = 85.5;

// Calling method

[Link]();

// Creating another object

Student s2 = new Student();

[Link] = "Priya";

[Link] = 102;
[Link] = 92.0;

[Link]();

Output:

Name: Rahul

Roll No: 101

Marks: 85.5

Name: Priya

Roll No: 102

Marks: 92.0

Line-by-Line Explanation

1. class Student — Declares a class named Student

2. String name — Instance variable to store student name

3. void displayDetails() — Method that prints student info

4. Student s1 = new Student() — Creates object s1 in heap memory

5. [Link] = "Rahul" — Assigns value to name using dot operator

6. [Link]() — Calls method on object s1

Memory Diagram

Stack Heap

┌─────────┐ ┌──────────────────┐

│ s1 │────────────────→ │ Student Object │

│(reference) │ name: "Rahul" │

└─────────┘ │ rollNo: 101 │

│ marks: 85.5 │

┌─────────┐ └──────────────────┘

│ s2 │────────────────→ ┌──────────────────┐

│(reference) │ Student Object │

└─────────┘ │ name: "Priya" │


│ rollNo: 102 │

│ marks: 92.0 │

└──────────────────┘

Difference Table: Class vs Object

Class Object

Blueprint/Template Instance of class

Logical entity Physical entity

No memory Memory allocated on


allocated heap

Declared once Can create multiple

Defines properties Has actual values

Real-Life Analogy

 Class = House blueprint

 Object = Actual house built from that blueprint

 Multiple houses (objects) can be built from one blueprint (class)

Viva Questions

1. What is the difference between class and object?

2. Where are objects stored in memory?

3. Can we have multiple objects of same class?

4. What is the new keyword used for?

MCQs

Q1. Objects are stored in:

 a) Stack

 b) Heap ✓

 c) Method Area

 d) Register

Q2. The new keyword is used to:

 a) Declare class

 b) Create object ✓
 c) Import package

 d) Define method

2. Data Encapsulation

Definition

Encapsulation is the mechanism of wrapping data (variables) and code


(methods) together into a single unit (class), while hiding the internal
details from outside access.

Implementation

1. Declare variables as private

2. Provide public getter and setter methods

Syntax

class ClassName {

private dataType variable;

// Getter

public dataType getVariable() {

return variable;

// Setter

public void setVariable(dataType value) {

[Link] = value;

Example Program

class BankAccount {

// Private variable (hidden)

private double balance;

// Constructor
public BankAccount(double initialBalance) {

if (initialBalance > 0) {

[Link] = initialBalance;

// Getter

public double getBalance() {

return balance;

// Controlled deposit

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

[Link]("Deposited: " + amount);

} else {

[Link]("Invalid amount!");

// Controlled withdrawal

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

[Link]("Withdrawn: " + amount);

} else {

[Link]("Invalid transaction!");

}
}

public class EncapsulationDemo {

public static void main(String[] args) {

BankAccount account = new BankAccount(1000);

[Link]("Balance: " + [Link]());

[Link](500);

[Link]("Balance: " + [Link]());

[Link](200);

[Link]("Balance: " + [Link]());

// Direct access not allowed

// [Link] = 1000000; // Compilation Error!

Output:

Balance: 1000.0

Deposited: 500.0

Balance: 1500.0

Withdrawn: 200.0

Balance: 1300.0

Advantages of Encapsulation

Advantag
Description
e

Data
Internal implementation hidden
Hiding
Advantag
Description
e

Control Validate data before setting

Flexibilit Change implementation without


y affecting users

Reusabili
Easier to test and maintain
ty

Security Prevents unauthorized access

Real-Life Analogy

ATM Machine: You can check balance, deposit, and withdraw, but you
cannot directly access the vault. The internal mechanism is hidden.

Memory Trick

"HIDE VARS, SHOW METHODS" — Private variables, Public


getters/setters

Viva Questions

1. What is encapsulation?

2. How do you achieve encapsulation in Java?

3. Why are getter and setter methods used?

4. What is data hiding?

3. Constructors

Definition

A constructor is a special method used to initialize objects. It has the


same name as the class and no return type (not even void).

Key Properties

 Same name as class

 No return type

 Called automatically when object is created

 Can be overloaded

 Cannot be inherited

Types of Constructors
Type Description

No parameters, provided by compiler if none


Default
defined

Parameteri Takes parameters to initialize with specific


zed values

Copy Creates object by copying another object

Example Program

class Rectangle {

int length, width;

// Default Constructor

Rectangle() {

length = 0;

width = 0;

[Link]("Default Constructor called");

// Parameterized Constructor

Rectangle(int l, int w) {

length = l;

width = w;

[Link]("Parameterized Constructor called");

// Copy Constructor

Rectangle(Rectangle r) {

length = [Link];

width = [Link];

[Link]("Copy Constructor called");


}

int area() {

return length * width;

public class ConstructorDemo {

public static void main(String[] args) {

Rectangle r1 = new Rectangle(); // Default

Rectangle r2 = new Rectangle(10, 5); // Parameterized

Rectangle r3 = new Rectangle(r2); // Copy

[Link]("r1 Area: " + [Link]());

[Link]("r2 Area: " + [Link]());

[Link]("r3 Area: " + [Link]());

Output:

Default Constructor called

Parameterized Constructor called

Copy Constructor called

r1 Area: 0

r2 Area: 50

r3 Area: 50

Constructor vs Method

Constructor Method

Same name as Any valid


class name

No return type Has return


Constructor Method

type

Called Called
automatically explicitly

Cannot be Can be
inherited inherited

Used for Used for


initialization behavior

Viva Questions

1. What is a constructor?

2. Can constructor have return type?

3. What is constructor overloading?

4. Can constructors be private?

4. Method Overloading

Definition

Method overloading is having multiple methods with the same name but
different parameters in the same class. It's a form of compile-time
polymorphism.

Rules for Overloading

 Same method name

 Different parameter list (number, type, or order)

 Return type alone cannot differentiate overloaded methods

Example Program

class Calculator {

// Add two integers

int add(int a, int b) {

return a + b;

// Add three integers


int add(int a, int b, int c) {

return a + b + c;

// Add two doubles

double add(double a, double b) {

return a + b;

// Add int and double

double add(int a, double b) {

return a + b;

public class OverloadingDemo {

public static void main(String[] args) {

Calculator calc = new Calculator();

[Link]("add(10, 20) = " + [Link](10, 20));

[Link]("add(10, 20, 30) = " + [Link](10, 20, 30));

[Link]("add(10.5, 20.5) = " + [Link](10.5, 20.5));

[Link]("add(10, 20.5) = " + [Link](10, 20.5));

Output:

add(10, 20) = 30

add(10, 20, 30) = 60

add(10.5, 20.5) = 31.0

add(10, 20.5) = 30.5


Overloading Scenarios

Valid Overloading Invalid Overloading

Different number of
Only return type different
parameters

Only parameter names


Different data types
different

Different order of types

Real-Life Analogy

A "+" operation that works differently based on context:

 2 + 3 = 5 (numeric addition)

 "Hello" + "World" = "HelloWorld" (string concatenation)

Viva Questions

1. What is method overloading?

2. Can we overload by changing only return type?

3. Is overloading compile-time or runtime polymorphism?

MCQs

Q1. Method overloading is an example of:

 a) Runtime polymorphism

 b) Compile-time polymorphism ✓

 c) Inheritance

 d) Encapsulation

5. Static Members

Definition

Static members belong to the class rather than to any specific object.
They are shared among all instances of the class.

Types of Static Members

 Static variables

 Static methods

 Static blocks

 Static nested classes


Key Points

 Declared using static keyword

 Accessed using class name (recommended) or object reference

 Static methods cannot access non-static members directly

 Static methods cannot use this or super

Example Program

class Counter {

// Static variable - shared by all objects

static int count = 0;

// Instance variable - unique to each object

int id;

// Constructor

Counter() {

count++; // Increment shared counter

id = count; // Assign unique ID

// Static method

static void showCount() {

[Link]("Total objects: " + count);

// [Link](id); // ERROR: Cannot access non-static

// Instance method

void showId() {

[Link]("Object ID: " + id);

}
}

public class StaticDemo {

public static void main(String[] args) {

// Static method called without object

[Link]();

Counter c1 = new Counter();

Counter c2 = new Counter();

Counter c3 = new Counter();

[Link]();

[Link]();

[Link]();

// Static variable accessed via class name

[Link]("Total: " + [Link]);

Output:

Total objects: 0

Object ID: 1

Object ID: 2

Object ID: 3

Total: 3

Static vs Instance

Static Instance

Belongs to class Belongs to object

Shared by all objects Unique to each object

One copy in memory Multiple copies


Static Instance

Accessed via class name Accessed via object

Memory allocated at class Memory allocated at object


loading creation

Static Block

class StaticBlockDemo {

static int value;

// Static block - executed once when class is loaded

static {

[Link]("Static block executed");

value = 100;

public static void main(String[] args) {

[Link]("Main method");

[Link]("Value: " + value);

Output:

Static block executed

Main method

Value: 100

Viva Questions

1. What is a static variable?

2. Can static methods access instance variables?

3. When is static block executed?

4. Why is main() method static?


6. The this Keyword

Definition

this is a reference variable that refers to the current object. It is used to


distinguish between instance variables and parameters with the same
name.

Uses of this

Use Case Syntax

Refer to current instance [Link]


variable e

[Link]
Invoke current class method
e()

Invoke current class


this()
constructor

Pass current object as


method(this)
argument

Return current object return this

Example Program

class Employee {

int id;

String name;

double salary;

// Constructor using 'this' to distinguish parameters

Employee(int id, String name, double salary) {

[Link] = id; // [Link] = instance variable

[Link] = name; // name = parameter

[Link] = salary;

// Method chaining using 'this'

Employee setId(int id) {


[Link] = id;

return this;

Employee setName(String name) {

[Link] = name;

return this;

void display() {

[Link](id + " " + name + " " + salary);

public class ThisDemo {

public static void main(String[] args) {

Employee e1 = new Employee(101, "John", 50000);

[Link]();

// Method chaining

Employee e2 = new Employee(0, "", 0);

[Link](102).setName("Jane").display();

Output:

101 John 50000.0

102 Jane 0.0

Constructor Chaining with this()

class Box {

int length, width, height;


// Default constructor

Box() {

this(0, 0, 0); // Calls parameterized constructor

[Link]("Default constructor");

// Single parameter - cube

Box(int side) {

this(side, side, side); // Calls 3-param constructor

[Link]("Cube constructor");

// Full parameterized constructor

Box(int l, int w, int h) {

length = l;

width = w;

height = h;

[Link]("Parameterized constructor");

int volume() {

return length * width * height;

Viva Questions

1. What is the this keyword?

2. Can this be used in static methods?

3. What is constructor chaining?


4. What does return this do?

7. Inheritance

Definition

Inheritance is the mechanism by which one class (child/subclass) acquires


the properties and behaviors of another class (parent/superclass).

Syntax

class ParentClass {

// parent members

class ChildClass extends ParentClass {

// child members

// inherits parent members

Types of Inheritance

Single Inheritance Multilevel Inheritance

A A

│ │

▼ ▼
B B


C

Hierarchical Inheritance Multiple Inheritance (NOT supported via classes)

A A B

/\ \ /

▼ ▼ ▼▼
B C C

(Use Interfaces)

Example: Single Inheritance


// Parent class

class Animal {

String name;

void eat() {

[Link](name + " is eating");

void sleep() {

[Link](name + " is sleeping");

// Child class

class Dog extends Animal {

String breed;

void bark() {

[Link](name + " is barking");

public class InheritanceDemo {

public static void main(String[] args) {

Dog dog = new Dog();

[Link] = "Buddy"; // Inherited from Animal

[Link] = "Golden Retriever";

[Link](); // Inherited method

[Link](); // Inherited method

[Link](); // Own method


}

Output:

Buddy is eating

Buddy is sleeping

Buddy is barking

Example: Multilevel Inheritance

class Grandparent {

void grandparentMethod() {

[Link]("Grandparent method");

class Parent extends Grandparent {

void parentMethod() {

[Link]("Parent method");

class Child extends Parent {

void childMethod() {

[Link]("Child method");

public class MultilevelDemo {

public static void main(String[] args) {

Child c = new Child();

[Link](); // From Grandparent

[Link](); // From Parent

[Link](); // Own method

}
}

The super Keyword

Use Case Syntax

Access parent [Link]


variable e

[Link]
Call parent method
e()

Call parent super() or


constructor super(args)

Example with super

class Vehicle {

int speed = 50;

Vehicle() {

[Link]("Vehicle constructor");

void display() {

[Link]("Vehicle speed: " + speed);

class Car extends Vehicle {

int speed = 100;

Car() {

super(); // Calls Vehicle constructor

[Link]("Car constructor");

void display() {
[Link]("Car speed: " + speed); // 100

[Link]("Vehicle speed: " + [Link]); // 50

[Link](); // Calls parent method

public class SuperDemo {

public static void main(String[] args) {

Car c = new Car();

[Link]();

Output:

Vehicle constructor

Car constructor

Car speed: 100

Vehicle speed: 50

Vehicle speed: 50

Why Multiple Inheritance Not Supported?

Diamond Problem: If two parent classes have same method, child


doesn't know which to inherit.

/\

B C

\/

D (Ambiguity: Which method to inherit?)

Solution: Use interfaces (a class can implement multiple interfaces).

Viva Questions

1. What is inheritance?

2. Types of inheritance in Java?


3. Why doesn't Java support multiple inheritance through classes?

4. Difference between this and super?

8. Method Overriding

Definition

Method overriding occurs when a subclass provides a specific


implementation of a method that is already defined in its superclass. It's a
form of runtime polymorphism.

Rules for Overriding

1. Method name must be same

2. Parameters must be same

3. Return type must be same (or covariant)

4. Access modifier cannot be more restrictive

5. Cannot override static, final, or private methods

Example Program

class Shape {

void draw() {

[Link]("Drawing a shape");

double area() {

return 0;

class Circle extends Shape {

double radius;

Circle(double r) {

radius = r;

}
@Override // Annotation (optional but recommended)

void draw() {

[Link]("Drawing a circle");

@Override

double area() {

return 3.14159 * radius * radius;

class Rectangle extends Shape {

double length, width;

Rectangle(double l, double w) {

length = l;

width = w;

@Override

void draw() {

[Link]("Drawing a rectangle");

@Override

double area() {

return length * width;

public class OverridingDemo {


public static void main(String[] args) {

Shape s1 = new Circle(5);

Shape s2 = new Rectangle(4, 6);

[Link]();

[Link]("Area: " + [Link]());

[Link]();

[Link]("Area: " + [Link]());

Output:

Drawing a circle

Area: 78.53975

Drawing a rectangle

Area: 24.0

Overloading vs Overriding

Overloading Overriding

Different classes
Same class
(inheritance)

Different parameters Same parameters

Compile-time
Runtime polymorphism
polymorphism

Static binding Dynamic binding

Can have different return Same return type (or


types covariant)

Viva Questions

1. What is method overriding?

2. Can we override private methods?

3. What is the @Override annotation?


4. Difference between overloading and overriding?

MCQs

Q1. Method overriding is:

 a) Compile-time polymorphism

 b) Runtime polymorphism ✓

 c) Encapsulation

 d) Abstraction

Q2. Which cannot be overridden?

 a) Public methods

 b) Protected methods

 c) Static methods ✓

 d) Default methods

9. Wrapper Classes

Definition

Wrapper classes provide a way to use primitive data types as objects.


Each primitive has a corresponding wrapper class.

Primitive to Wrapper Mapping

Primiti Wrapper
ve Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Boxing and Unboxing


Operation Description Example

Primitive →
Boxing Integer i = 10;
Wrapper

Wrapper →
Unboxing int n = i;
Primitive

Automatic (same as
Autoboxing
boxing boxing)

Auto- Automatic (same as


unboxing unboxing unboxing)

Example Program

public class WrapperDemo {

public static void main(String[] args) {

// Boxing (manual - older way)

Integer num1 = [Link](100);

// Autoboxing (automatic - modern way)

Integer num2 = 200;

// Unboxing (manual)

int val1 = [Link]();

// Auto-unboxing (automatic)

int val2 = num2;

[Link]("num1: " + num1);

[Link]("num2: " + num2);

[Link]("val1: " + val1);

[Link]("val2: " + val2);

// Useful methods
[Link]("Max int: " + Integer.MAX_VALUE);

[Link]("Min int: " + Integer.MIN_VALUE);

// Parsing strings to numbers

int parsed = [Link]("500");

[Link]("Parsed: " + parsed);

// Converting numbers to strings

String str = [Link](1000);

[Link]("String: " + str);

Output:

num1: 100

num2: 200

val1: 100

val2: 200

Max int: 2147483647

Min int: -2147483648

Parsed: 500

String: 1000

Why Wrapper Classes?

1. Collections require objects (not primitives)

2. Useful methods for conversion and parsing

3. Constants like MAX_VALUE, MIN_VALUE

4. Allow null values

Viva Questions

1. What are wrapper classes?

2. What is autoboxing?
3. How do you convert String to int?

4. Can wrapper objects be null?

UNIT II: Important Questions

2-Mark Questions

1. Define class and object.

2. What is encapsulation?

3. What is method overloading?

4. Define constructor.

5. What is the this keyword?

5-Mark Questions

1. Explain encapsulation with an example program.

2. Differentiate between method overloading and overriding.

3. Explain different types of constructors with examples.

4. What are static members? Explain with program.

5. Explain inheritance with types and examples.

10-Mark Questions

1. Explain all OOP concepts in Java with programs.

2. Write a program demonstrating inheritance and method overriding.

3. Explain constructor chaining and method chaining with examples.

4. Explain wrapper classes with autoboxing and unboxing examples.

UNIT II: Quick Revision

Topic Key Points

Class Blueprint/template for objects

Object Instance of class, created using new

Encapsulati
Private variables + public getters/setters
on

Same name as class, no return type,


Constructor
initializes object

Overloading Same name, different parameters


Topic Key Points

Static Belongs to class, shared by all objects

this Refers to current object

Child acquires properties of parent using


Inheritance
extends

super Refers to parent class

Overriding Same signature in child class

Wrapper Object version of primitives

UNIT III: PACKAGES, INTERFACES & EXCEPTIONS

1. Packages

Definition

A package is a namespace that organizes classes and interfaces into a


directory structure. It prevents naming conflicts and provides access
protection.

Types of Packages

Type Description Examples

[Link], [Link],
Built-in Provided by Java
[Link]

User- Created by
[Link]
defined programmers

Creating a Package

// File: mypackage/[Link]

package mypackage;

public class Calculator {

public int add(int a, int b) {

return a + b;

public int subtract(int a, int b) {

return a - b;
}

Using Package Members

// Method 1: Import specific class

import [Link];

// Method 2: Import all classes

import mypackage.*;

// Method 3: Fully qualified name

[Link] calc = new [Link]();

Directory Structure

project/

├── mypackage/

│ └── [Link]

│ └── [Link]

└── [Link]

└── [Link]

Compilation and Execution

# Compile

javac -d . [Link]

javac [Link]

# Run

java Main

CLASSPATH

CLASSPATH is an environment variable that tells JVM where to find user-


defined classes.

# Set CLASSPATH

set CLASSPATH=.;C:\myprojects\classes

# Or use -cp flag

java -cp .;lib/[Link] Main


Package Naming Convention

 Use reverse domain name: [Link]

 All lowercase

 Examples: [Link], [Link]

Access Modifiers with Packages

Modifie Same Same Subcla Other


r Class Package ss Package

public ✓ ✓ ✓ ✓

protecte
✓ ✓ ✓ ✗
d

default ✓ ✓ ✗ ✗

private ✓ ✗ ✗ ✗

Example: Complete Package Usage

// File: bank/[Link]

package bank;

public class Account {

private double balance;

public Account(double initial) {

balance = initial;

public void deposit(double amount) {

balance += amount;

public double getBalance() {

return balance;

}
}

// File: [Link]

import [Link];

public class Main {

public static void main(String[] args) {

Account acc = new Account(1000);

[Link](500);

[Link]("Balance: " + [Link]());

Output:

Balance: 1500.0

Viva Questions

1. What is a package in Java?

2. What is CLASSPATH?

3. How do you create a user-defined package?

4. Difference between import and import *?

2. Interfaces

Definition

An interface is a completely abstract type that contains only abstract


methods (until Java 7) and constants. It defines a contract that
implementing classes must follow.

Syntax

interface InterfaceName {

// Constants (public static final by default)

dataType CONSTANT_NAME = value;

// Abstract methods (public abstract by default)

returnType methodName(parameters);

}
Implementing Interface

class ClassName implements InterfaceName {

// Must implement all abstract methods

@Override

public returnType methodName(parameters) {

// implementation

Example Program

// Interface definition

interface Drawable {

int DEFAULT_COLOR = 0; // public static final

void draw(); // public abstract

interface Resizable {

void resize(int percentage);

// Implementing multiple interfaces

class Circle implements Drawable, Resizable {

int radius;

Circle(int r) {

radius = r;

@Override

public void draw() {

[Link]("Drawing circle with radius " + radius);


}

@Override

public void resize(int percentage) {

radius = radius * percentage / 100;

[Link]("Resized to radius " + radius);

public class InterfaceDemo {

public static void main(String[] args) {

Circle c = new Circle(10);

[Link]();

[Link](150);

[Link]();

// Interface reference

Drawable d = new Circle(5);

[Link]();

Output:

Drawing circle with radius 10

Resized to radius 15

Drawing circle with radius 15

Drawing circle with radius 5

Interface Features (Java 8+)

Java
Feature Description
Version

Abstract All Methods without body


Java
Feature Description
Version

methods

Constants All public static final

Default Methods with body using


Java 8+
methods default

Static methods Java 8+ Static methods in interface

Private
Java 9+ Helper methods
methods

Default Methods Example

interface Vehicle {

void start();

// Default method - has implementation

default void horn() {

[Link]("Beep Beep!");

class Car implements Vehicle {

@Override

public void start() {

[Link]("Car started");

// horn() is inherited with default implementation

Interface vs Abstract Class

Interface Abstract Class

Only abstract methods (before Can have both abstract and


Java 8) concrete

Cannot have constructors Can have constructors


Interface Abstract Class

All variables are public static


Can have any type of variables
final

Multiple inheritance supported Single inheritance only

implements keyword extends keyword

100% abstraction (before Java


Partial abstraction
8)

Extending Interfaces

interface A {

void methodA();

interface B extends A {

void methodB();

class MyClass implements B {

@Override

public void methodA() {

[Link]("Method A");

@Override

public void methodB() {

[Link]("Method B");

Viva Questions

1. What is an interface?

2. Can interface have variables?


3. Can a class implement multiple interfaces?

4. Difference between interface and abstract class?

5. What are default methods?

MCQs

Q1. Interface variables are by default:

 a) private static final

 b) public static final ✓

 c) protected static final

 d) public final

Q2. A class can implement:

 a) Only one interface

 b) Multiple interfaces ✓

 c) No interface

 d) Depends on JVM

3. Abstract Classes

Definition

An abstract class is a class that cannot be instantiated and may contain


abstract methods (without body) and concrete methods (with body).

Syntax

abstract class AbstractClassName {

// Instance variables

dataType variable;

// Concrete method

void concreteMethod() {

// implementation

// Abstract method
abstract returnType abstractMethod(parameters);

Example Program

abstract class Animal {

String name;

// Constructor

Animal(String name) {

[Link] = name;

// Concrete method

void sleep() {

[Link](name + " is sleeping");

// Abstract method - must be overridden

abstract void makeSound();

class Dog extends Animal {

Dog(String name) {

super(name);

@Override

void makeSound() {

[Link](name + " barks: Woof!");

}
class Cat extends Animal {

Cat(String name) {

super(name);

@Override

void makeSound() {

[Link](name + " meows: Meow!");

public class AbstractDemo {

public static void main(String[] args) {

// Animal a = new Animal(); // ERROR: Cannot instantiate

Animal dog = new Dog("Buddy");

Animal cat = new Cat("Whiskers");

[Link]();

[Link]();

[Link]();

[Link]();

Output:

Buddy barks: Woof!

Buddy is sleeping

Whiskers meows: Meow!

Whiskers is sleeping
When to Use Abstract Class vs Interface?

Use Abstract Class


Use Interface When
When

Unrelated classes implement common


Related classes share code
behavior

Need constructors Only method signatures needed

Need non-static/non-final
Only constants needed
fields

Close family of classes Multiple inheritance needed

Viva Questions

1. What is an abstract class?

2. Can abstract class have constructor?

3. Can abstract class have concrete methods?

4. When would you use abstract class over interface?

4. Exception Handling

Definition

An exception is an unwanted event that disrupts the normal flow of a


program. Exception handling is a mechanism to handle runtime errors
gracefully.

Exception Hierarchy

Throwable

┌──────────┴──────────┐

▼ ▼
Error Exception

(Unrecoverable) │

│ ┌──────┴──────┐

│ ▼ ▼

OutOfMemoryError RuntimeException IOException

StackOverflowError │ FileNotFoundException
│ etc.

NullPointerException

ArithmeticException

ArrayIndexOutOfBoundsException

etc.

Types of Exceptions

Type Description Example

Compile-time, must be
Checked IOException, SQLException
handled

Uncheck NullPointerException,
Runtime, optional handling
ed ArithmeticException

Serious problems, not


Error OutOfMemoryError
handled

Exception Handling Keywords

Keywo
Purpose
rd

Block of code that might throw


try
exception

catch Block that handles the exception

finally Block that always executes

throw Used to explicitly throw an exception

Declares exceptions a method might


throws
throw

Basic try-catch

public class BasicExceptionDemo {

public static void main(String[] args) {

try {

int result = 10 / 0; // ArithmeticException

[Link]("Result: " + result);

} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero");

[Link]("Exception: " + [Link]());

[Link]("Program continues...");

Output:

Error: Cannot divide by zero

Exception: / by zero

Program continues...

Multiple Catch Blocks

public class MultipleCatchDemo {

public static void main(String[] args) {

try {

int[] arr = {1, 2, 3};

[Link](arr[5]); // ArrayIndexOutOfBoundsException

String str = null;

[Link]([Link]()); // NullPointerException

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Array index error: " + [Link]());

} catch (NullPointerException e) {

[Link]("Null pointer error: " + [Link]());

} catch (Exception e) {

[Link]("General error: " + [Link]());

}
Output:

Array index error: Index 5 out of bounds for length 3

finally Block

public class FinallyDemo {

public static void main(String[] args) {

try {

int result = 10 / 2;

[Link]("Result: " + result);

} catch (ArithmeticException e) {

[Link]("Error occurred");

} finally {

[Link]("Finally block always executes");

Output:

Result: 5

Finally block always executes

throw and throws

class AgeValidator {

// throws - declares exception

static void validateAge(int age) throws Exception {

if (age < 18) {

// throw - throws exception

throw new Exception("Age must be 18 or above");

[Link]("Valid age: " + age);

}
public class ThrowDemo {

public static void main(String[] args) {

try {

[Link](15);

} catch (Exception e) {

[Link]("Exception: " + [Link]());

try {

[Link](20);

} catch (Exception e) {

[Link]("Exception: " + [Link]());

Output:

Exception: Age must be 18 or above

Valid age: 20

throw vs throws

throw throws

Used in method
Used inside method
signature

Throws exception
Declares exception
explicitly

Followed by exception Followed by exception


object class

Can throw one at a time Can declare multiple

Custom Exception

// Custom exception class

class InvalidAgeException extends Exception {


InvalidAgeException(String message) {

super(message);

class VoterRegistration {

static void register(String name, int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Voter must be 18+. Current age: "


+ age);

[Link](name + " registered successfully!");

public class CustomExceptionDemo {

public static void main(String[] args) {

try {

[Link]("John", 20);

[Link]("Mike", 16);

} catch (InvalidAgeException e) {

[Link]("Registration failed: " + [Link]());

Output:

John registered successfully!

Registration failed: Voter must be 18+. Current age: 16

try-with-resources (Java 7+)

// Automatically closes resources

try (FileReader fr = new FileReader("[Link]");


BufferedReader br = new BufferedReader(fr)) {

String line = [Link]();

[Link](line);

} catch (IOException e) {

[Link]("Error reading file");

// Resources automatically closed here

Common Exceptions

Exception Cause

NullPointerException Accessing null reference

ArithmeticException Division by zero

ArrayIndexOutOfBoundsExce
Invalid array index
ption

Invalid string to number


NumberFormatException
conversion

FileNotFoundException File not found

IOException I/O operation failure

ClassNotFoundException Class not found

Viva Questions

1. What is an exception?

2. Difference between checked and unchecked exceptions?

3. Difference between throw and throws?

4. What is the purpose of finally?

5. How do you create custom exceptions?

6. Will finally execute if there's return in try?

MCQs

Q1. Which is unchecked exception?

 a) IOException

 b) SQLException
 c) NullPointerException ✓

 d) FileNotFoundException

Q2. finally block:

 a) Never executes

 b) Executes only on exception

 c) Always executes ✓

 d) Executes only without exception

UNIT III: Important Questions

2-Mark Questions

1. What is a package?

2. What is an interface?

3. Define exception.

4. Difference between throw and throws.

5. What is CLASSPATH?

5-Mark Questions

1. Explain how to create and use packages in Java.

2. Write a program implementing an interface.

3. Explain exception handling with try-catch-finally.

4. Compare interface and abstract class.

5. Explain multiple catch blocks with example.

10-Mark Questions

1. Explain packages in detail with access modifiers.

2. Write a program demonstrating custom exception.

3. Explain interface with default methods and multiple inheritance.

4. Explain exception hierarchy and types of exceptions.

UNIT III: Quick Revision

Topic Key Points

Namespace for classes, package


Package
keyword
Topic Key Points

CLASSPATH Path where JVM looks for classes

100% abstract (pre-Java 8),


Interface
implements

Abstract Class Partial abstraction, extends

Exception Runtime error handling

Code that might fail in try, handle


try-catch
in catch

finally Always executes

throw Explicitly throw exception

Declare exception in method


throws
signature

Custom
extends Exception
Exception

UNIT IV: MULTITHREADING, I/O & STRINGS

1. Multithreading Introduction

Definition

Multithreading is the concurrent execution of two or more threads


(lightweight processes) within a single program. Each thread runs
independently while sharing resources.

Key Terms

Term Definition

An executing program with its own memory


Process
space

A lightweight sub-process, smallest unit of


Thread
execution

Multitaskin
Running multiple processes simultaneously
g

Multithread
Running multiple threads within one process
ing

Advantages of Multithreading
1. Better CPU utilization

2. Improved performance

3. Responsiveness (UI doesn't freeze)

4. Resource sharing

5. Simplified modeling of real-world scenarios

Thread Lifecycle

┌─────────────────────────────────────────────────────┐

│ │

▼ │

┌───────┐ start() ┌──────────┐ │

│ New │──────────────►│ Runnable │◄────────────────────┤

└───────┘ └────┬─────┘ │

│ │

┌──────────────┼──────────────┐ │

▼ ▼ ▼ │

┌─────────┐ ┌─────────┐ ┌──────────┐ │

│ Running │ │ Blocked │ │ Waiting │ │

└────┬────┘ └────┬────┘ └────┬─────┘ │

│ │ │ │

│ └──────────────┴─────────────┘

│ (unlock/notify)


┌─────────────┐

│ Terminated │

│ (Dead) │

└─────────────┘

Thread States

State Description

New Thread object created but not


State Description

started

Thread ready to run, waiting for


Runnable
CPU

Running Thread currently executing

Blocked/ Thread waiting for resource or


Waiting signal

Terminated Thread completed execution

2. Creating Threads

Method 1: Extending Thread Class

class MyThread extends Thread {

@Override

public void run() {

for (int i = 1; i <= 5; i++) {

[Link](getName() + ": " + i);

try {

[Link](500); // Pause for 500ms

} catch (InterruptedException e) {

[Link]("Interrupted");

public class ThreadDemo1 {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

[Link]("Thread-A");
[Link]("Thread-B");

[Link](); // Don't call run() directly!

[Link]();

Sample Output:

Thread-A: 1

Thread-B: 1

Thread-A: 2

Thread-B: 2

...

Method 2: Implementing Runnable Interface

class MyRunnable implements Runnable {

@Override

public void run() {

for (int i = 1; i <= 5; i++) {

[Link]([Link]().getName() + ": " + i);

try {

[Link](500);

} catch (InterruptedException e) {

[Link]("Interrupted");

public class ThreadDemo2 {

public static void main(String[] args) {

MyRunnable r = new MyRunnable();


Thread t1 = new Thread(r, "Thread-X");

Thread t2 = new Thread(r, "Thread-Y");

[Link]();

[Link]();

Thread vs Runnable

Extending Thread Implementing Runnable

Cannot extend another


Can extend another class
class

Less flexible More flexible

Each thread has unique Multiple threads can share one


object object

class A extends Thread class A implements Runnable

The Main Thread

public class MainThreadDemo {

public static void main(String[] args) {

Thread mainThread = [Link]();

[Link]("Main Thread: " + [Link]());

[Link]("Priority: " + [Link]());

[Link]("Thread Group: " +


[Link]().getName());

[Link]("MyMainThread");

[Link]("Renamed to: " + [Link]());

}
Output:

Main Thread: main

Priority: 5

Thread Group: main

Renamed to: MyMainThread

3. Thread Priority

Definition

Thread priority determines the relative importance of threads for


scheduling. Higher priority threads get preference.

Priority Constants

Constant Value

Thread.MIN_PRIORIT
1
Y

Thread.NORM_PRIORI 5
TY (default)

Thread.MAX_PRIORIT
10
Y

Example

class PriorityThread extends Thread {

public void run() {

[Link]("Running: " + getName() + ", Priority: " +


getPriority());

public class PriorityDemo {

public static void main(String[] args) {

PriorityThread t1 = new PriorityThread();

PriorityThread t2 = new PriorityThread();

PriorityThread t3 = new PriorityThread();


[Link]("Low Priority");

[Link]("Normal Priority");

[Link]("High Priority");

[Link](Thread.MIN_PRIORITY); // 1

[Link](Thread.NORM_PRIORITY); // 5

[Link](Thread.MAX_PRIORITY); // 10

[Link]();

[Link]();

[Link]();

Note: Priority doesn't guarantee execution order—it's a hint to the


scheduler.

4. Synchronization

Definition

Synchronization is the mechanism that ensures only one thread accesses


shared resources at a time, preventing data inconsistency.

The Problem: Race Condition

// Without synchronization - causes race condition

class Counter {

int count = 0;

void increment() {

count++; // Not atomic: read, modify, write

Solution: Synchronized Method

class Counter {
int count = 0;

synchronized void increment() {

count++;

synchronized int getCount() {

return count;

public class SyncDemo {

public static void main(String[] args) throws InterruptedException {

Counter counter = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

[Link]();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

[Link]();

});

[Link]();

[Link]();
[Link](); // Wait for t1 to complete

[Link](); // Wait for t2 to complete

[Link]("Final count: " + [Link]());

Output:

Final count: 2000

Synchronized Block

class SyncBlockDemo {

void printNumbers(String threadName) {

synchronized (this) { // Lock on current object

for (int i = 1; i <= 5; i++) {

[Link](threadName + ": " + i);

try {

[Link](100);

} catch (InterruptedException e) {}

5. Inter-Thread Communication

Definition

Inter-thread communication allows synchronized threads to communicate


about the lock status using wait(), notify(), and notifyAll().

Methods

Method Description

Thread releases lock and


wait()
waits
Method Description

Wakes up one waiting


notify()
thread

notifyAll Wakes up all waiting


() threads

Producer-Consumer Example

class SharedBuffer {

int data;

boolean hasData = false;

synchronized void produce(int value) {

while (hasData) {

try {

wait(); // Wait until consumed

} catch (InterruptedException e) {}

data = value;

hasData = true;

[Link]("Produced: " + value);

notify(); // Wake up consumer

synchronized int consume() {

while (!hasData) {

try {

wait(); // Wait until produced

} catch (InterruptedException e) {}

hasData = false;
[Link]("Consumed: " + data);

notify(); // Wake up producer

return data;

public class ProducerConsumerDemo {

public static void main(String[] args) {

SharedBuffer buffer = new SharedBuffer();

Thread producer = new Thread(() -> {

for (int i = 1; i <= 5; i++) {

[Link](i);

});

Thread consumer = new Thread(() -> {

for (int i = 1; i <= 5; i++) {

[Link]();

});

[Link]();

[Link]();

Output:

Produced: 1

Consumed: 1

Produced: 2
Consumed: 2

...

Viva Questions

1. What is multithreading?

2. Two ways to create a thread?

3. What is synchronization?

4. Difference between wait() and sleep()?

5. What is the producer-consumer problem?

6. I/O in Java

Definition

I/O (Input/Output) operations in Java are performed using streams. A


stream is a sequence of data.

Stream Types

Streams

┌───────┴───────┐

▼ ▼
Byte Streams Character Streams

(Binary data) (Text data)

│ │

┌───┴───┐ ┌───┴───┐

▼ ▼ ▼ ▼
Input Output Reader Writer

Important Stream Classes

Character
Byte Streams
Streams

InputStream Reader

OutputStream Writer

FileInputStream FileReader
Character
Byte Streams
Streams

FileOutputStream FileWriter

BufferedInputStrea
BufferedReader
m

BufferedOutputStre
BufferedWriter
am

Console Input (Scanner)

import [Link];

public class ConsoleInputDemo {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter name: ");

String name = [Link]();

[Link]("Enter age: ");

int age = [Link]();

[Link]("Enter salary: ");

double salary = [Link]();

[Link]("\nDetails:");

[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Salary: " + salary);

[Link]();

}
Console Input (BufferedReader)

import [Link].*;

public class BufferedReaderDemo {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new


InputStreamReader([Link]));

[Link]("Enter text: ");

String text = [Link]();

[Link]("You entered: " + text);

[Link]();

File Writing

import [Link].*;

public class FileWriteDemo {

public static void main(String[] args) {

try (FileWriter fw = new FileWriter("[Link]");

BufferedWriter bw = new BufferedWriter(fw)) {

[Link]("Hello, File!");

[Link]();

[Link]("This is line 2.");

[Link]("File written successfully");

} catch (IOException e) {
[Link]("Error: " + [Link]());

File Reading

import [Link].*;

public class FileReadDemo {

public static void main(String[] args) {

try (FileReader fr = new FileReader("[Link]");

BufferedReader br = new BufferedReader(fr)) {

String line;

while ((line = [Link]()) != null) {

[Link](line);

} catch (IOException e) {

[Link]("Error: " + [Link]());

Output (reading [Link]):

Hello, File!

This is line 2.

Byte Stream Example

import [Link].*;

public class ByteStreamDemo {

public static void main(String[] args) {

// Writing bytes
try (FileOutputStream fos = new FileOutputStream("[Link]")) {

byte[] data = {65, 66, 67, 68, 69}; // A, B, C, D, E

[Link](data);

[Link]("Bytes written");

} catch (IOException e) {

[Link]("Error: " + [Link]());

// Reading bytes

try (FileInputStream fis = new FileInputStream("[Link]")) {

int b;

while ((b = [Link]()) != -1) {

[Link]((char) b + " ");

} catch (IOException e) {

[Link]("Error: " + [Link]());

Output:

Bytes written

ABCDE

Viva Questions

1. What is a stream?

2. Difference between byte stream and character stream?

3. What is BufferedReader?

4. How do you read a file in Java?

7. Strings in Java

Definition
A String is a sequence of characters. In Java, strings are objects of the
String class and are immutable (cannot be changed after creation).

Creating Strings

// Method 1: String literal (stored in String Pool)

String s1 = "Hello";

// Method 2: Using new keyword (stored in Heap)

String s2 = new String("Hello");

String Pool vs Heap

String Pool Heap

┌─────────────┐ ┌─────────────┐

│ "Hello" │◄────s1 │ String obj │◄────s2

│ │ │ "Hello" │

└─────────────┘ └─────────────┘

String Methods

Method Description Example

length() Returns length "Hello".length() → 5

charAt(i) Character at index "Hello".charAt(0) → 'H'

"Hello".substring(0,3) →
substring(i,j) Extract portion
"Hel"

concat(s) Join strings "Hello".concat(" World")

equals(s) Compare content [Link](s2)

equalsIgnoreCase
Compare ignoring case Case-insensitive
(s)

"hello".toUpperCase() →
toUpperCase() Convert to uppercase
"HELLO"

"HELLO".toLowerCase() →
toLowerCase() Convert to lowercase
"hello"

Remove leading/trailing
trim() " Hi ".trim() → "Hi"
spaces

replace(a,b) Replace characters "hello".replace('l','x') →


Method Description Example

"hexxo"

indexOf(s) Find index "Hello".indexOf('l') → 2

"a,b,c".split(",") →
split(regex) Split string
["a","b","c"]

"Hello".contains("ell") →
contains(s) Check if contains
true

isEmpty() Check if empty "".isEmpty() → true

"Hello".startsWith("He") →
startsWith(s) Check prefix
true

"Hello".endsWith("lo") →
endsWith(s) Check suffix
true

Example Program

public class StringDemo {

public static void main(String[] args) {

String str = "Hello World";

[Link]("Length: " + [Link]());

[Link]("Char at 0: " + [Link](0));

[Link]("Substring(0,5): " + [Link](0, 5));

[Link]("Uppercase: " + [Link]());

[Link]("Replace: " + [Link]('o', '0'));

[Link]("Index of 'W': " + [Link]('W'));

[Link]("Contains 'World': " + [Link]("World"));

// Splitting

String csv = "apple,banana,cherry";

String[] fruits = [Link](",");

for (String fruit : fruits) {

[Link](fruit);
}

Output:

Length: 11

Char at 0: H

Substring(0,5): Hello

Uppercase: HELLO WORLD

Replace: Hell0 W0rld

Index of 'W': 6

Contains 'World': true

apple

banana

cherry

String Comparison

public class StringCompareDemo {

public static void main(String[] args) {

String s1 = "Hello";

String s2 = "Hello";

String s3 = new String("Hello");

// == compares references

[Link](s1 == s2); // true (same pool object)

[Link](s1 == s3); // false (different objects)

// equals() compares content

[Link]([Link](s2)); // true

[Link]([Link](s3)); // true
// compareTo() - lexicographic comparison

[Link]("apple".compareTo("banana")); // negative

[Link]("banana".compareTo("apple")); // positive

[Link]("apple".compareTo("apple")); // 0

8. StringBuffer and StringBuilder

Definition

StringBuffer and StringBuilder are mutable string classes. Unlike String,


they can be modified without creating new objects.

Comparison

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread Synchronized (thread- Not


N/A
Safety safe) synchronized

Performanc Slow for


Slower Faster
e modifications

Single-
Use Case Fixed strings Multi-threaded
threaded

StringBuffer Methods

Method Description

append(s) Add to end

Insert at
insert(i, s)
position

replace(i, j,
Replace portion
s)

delete(i, j) Delete portion

reverse() Reverse string

Current
capacity()
capacity
Method Description

setCharAt(i, Change
c) character

Example Program

public class StringBufferDemo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Hello");

[Link]("Original: " + sb);

[Link]("Capacity: " + [Link]());

// Append

[Link](" World");

[Link]("After append: " + sb);

// Insert

[Link](5, ",");

[Link]("After insert: " + sb);

// Replace

[Link](0, 5, "Hi");

[Link]("After replace: " + sb);

// Delete

[Link](2, 4);

[Link]("After delete: " + sb);

// Reverse

[Link]();
[Link]("After reverse: " + sb);

Output:

Original: Hello

Capacity: 21

After append: Hello World

After insert: Hello, World

After replace: Hi, World

After delete: Hi World

After reverse: dlroW iH

String vs StringBuffer Performance

public class PerformanceDemo {

public static void main(String[] args) {

// String concatenation (slow)

long start = [Link]();

String str = "";

for (int i = 0; i < 10000; i++) {

str += "a";

[Link]("String time: " + ([Link]() -


start) + "ms");

// StringBuffer (fast)

start = [Link]();

StringBuffer sb = new StringBuffer();

for (int i = 0; i < 10000; i++) {

[Link]("a");

}
[Link]("StringBuffer time: " +
([Link]() - start) + "ms");

Viva Questions

1. Why is String immutable?

2. Difference between String and StringBuffer?

3. When to use StringBuilder over StringBuffer?

4. What is String pool?

5. Difference between == and equals() for Strings?

MCQs

Q1. String in Java is:

 a) Mutable

 b) Immutable ✓

 c) Partially mutable

 d) Depends on JVM

Q2. Which is thread-safe?

 a) String

 b) StringBuffer ✓

 c) StringBuilder

 d) All of above

UNIT IV: Important Questions

2-Mark Questions

1. What is a thread?

2. Define synchronization.

3. What is String pool?

4. Difference between sleep() and wait().

5. What is StringBuffer?

5-Mark Questions
1. Explain thread lifecycle with diagram.

2. Write a program to create threads using Runnable.

3. Explain synchronization with example.

4. Write a program to read and write files in Java.

5. Explain String methods with examples.

10-Mark Questions

1. Explain multithreading with thread creation methods and examples.

2. Explain producer-consumer problem with code.

3. Compare String, StringBuffer, and StringBuilder with programs.

4. Explain I/O streams in Java with file handling examples.

UNIT IV: Quick Revision

Topic Key Points

Lightweight process, extends Thread or implements


Thread
Runnable

Thread States New, Runnable, Running, Blocked, Terminated

Priority MIN=1, NORM=5, MAX=10

Synchronizatio
synchronized keyword prevents race conditions
n

wait/notify Inter-thread communication

Streams Byte (binary) and Character (text)

FileReader/
Character-based file I/O
Writer

String Immutable, stored in String Pool

StringBuffer Mutable, thread-safe, slower

StringBuilder Mutable, not thread-safe, faster

EXAM PREPARATION SECTION

Top 50 Most Important Questions

UNIT I Questions

1. Explain the evolution of Java and its key features.


2. What are the characteristics of Java? Explain any five.

3. Describe the compilation and execution process of Java program


with diagram.

4. Explain the architecture of JVM in detail.

5. Differentiate between JDK, JRE, and JVM.

6. How does Java achieve platform independence?

7. What is WORA? Explain with diagram.

8. Explain different data types in Java.

9. What is type casting? Explain widening and narrowing.

10. Explain various operators in Java with examples.

UNIT II Questions

11. Explain class and object with example program.

12. What is encapsulation? How is it achieved in Java?

13. Explain different types of constructors with programs.

14. What is constructor overloading? Give example.

15. Explain method overloading with example.

16. What are static members? Explain with program.

17. Explain the this keyword with all its uses.

18. What is inheritance? Explain types with diagrams.

19. Explain method overriding with example.

20. Differentiate between method overloading and overriding.

21. Explain the super keyword with examples.

22. What are wrapper classes? Explain autoboxing.

UNIT III Questions

23. What is a package? How do you create and use packages?

24. Explain CLASSPATH and its importance.

25. What is an interface? How do you implement it?

26. Compare interface and abstract class.

27. Can a class implement multiple interfaces? Explain.


28. What are default methods in interface?

29. What is exception? Explain exception hierarchy.

30. Differentiate between checked and unchecked exceptions.

31. Explain try-catch-finally with example.

32. Differentiate between throw and throws.

33. How do you create custom exceptions?

34. Explain multiple catch blocks with example.

UNIT IV Questions

35. What is multithreading? Explain advantages.

36. Explain thread lifecycle with diagram.

37. Explain two ways to create threads with programs.

38. What is synchronization? Why is it needed?

39. Explain inter-thread communication with example.

40. What is producer-consumer problem? Write code.

41. Explain I/O streams in Java.

42. Write a program to read and write text files.

43. Explain String class and its important methods.

44. Why is String immutable in Java?

45. Compare String, StringBuffer, and StringBuilder.

46. What is String pool?

47. Explain thread priority with example.

48. What is the main thread in Java?

49. Explain BufferedReader and Scanner for input.

50. Write a program demonstrating StringBuffer methods.

Top 20 Coding Questions

1. Hello World Program

2. Sum of Array Elements

3. Factorial using Recursion

4. Fibonacci Series
5. Check Prime Number

6. Reverse a String

7. Palindrome Check

8. Sort an Array

9. Matrix Addition/Multiplication

10. Class with Constructor and Methods

11. Inheritance Example (Single/Multilevel)

12. Method Overloading

13. Method Overriding

14. Interface Implementation

15. Exception Handling with Custom Exception

16. Thread Creation (Both Methods)

17. Synchronized Counter

18. File Read/Write

19. StringBuffer Operations

20. Producer-Consumer Problem

Top 30 Viva Questions

1. What is JVM? Is it platform independent?

2. Difference between JDK and JRE?

3. What is bytecode?

4. Why is Java platform independent?

5. What is a constructor?

6. Can constructor be private?

7. Difference between this and super?

8. What is method overloading?

9. Can we override static methods?

10. What is encapsulation?

11. What is polymorphism?

12. Difference between abstract class and interface?


13. Can interface have constructor?

14. What is multiple inheritance?

15. Why doesn't Java support multiple inheritance through


classes?

16. What is an exception?

17. Difference between throw and throws?

18. Will finally block execute if there's return in try?

19. What is a thread?

20. Difference between start() and run()?

21. What is synchronization?

22. Difference between wait() and sleep()?

23. What is deadlock?

24. Why is String immutable?

25. Difference between == and equals()?

26. What is String pool?

27. Difference between StringBuffer and StringBuilder?

28. What are wrapper classes?

29. What is autoboxing?

30. What is the main method signature?

Mark-Wise Questions

2-Mark Questions

1. Define bytecode.

2. What is JVM?

3. What is a class?

4. Define constructor.

5. What is method overloading?

6. Define encapsulation.

7. What is inheritance?

8. What is an interface?
9. Define exception.

10. What is a thread?

11. What is String pool?

12. Define synchronization.

13. What is CLASSPATH?

14. Define wrapper class.

15. What is abstraction?

5-Mark Questions

1. Explain features of Java.

2. Write a program demonstrating constructor overloading.

3. Explain inheritance with program.

4. Compare interface and abstract class.

5. Explain exception handling with example.

6. Write a program to create threads using Runnable.

7. Explain String methods with examples.

8. Write a program for file reading.

9. Explain method overriding with example.

10. Explain encapsulation with program.

10-Mark Questions

1. Explain JVM architecture in detail with diagram.

2. Explain all OOP concepts with programs.

3. Explain exception handling with custom exception program.

4. Explain multithreading with synchronization example.

5. Compare String, StringBuffer, StringBuilder with programs.

6. Explain packages and interfaces with examples.

7. Explain inheritance types with programs.

8. Write a producer-consumer problem solution.

Most Likely to Appear in Exam

High Priority Topics (Almost Certain)


1. ✅ Features/Characteristics of Java

2. ✅ JVM Architecture

3. ✅ JDK vs JRE vs JVM

4. ✅ Data Types

5. ✅ Operators

6. ✅ Class and Object

7. ✅ Constructors (all types)

8. ✅ Method Overloading

9. ✅ Method Overriding

10. ✅ Inheritance

11. ✅ Interface vs Abstract Class

12. ✅ Exception Handling (try-catch-finally)

13. ✅ throw vs throws

14. ✅ Thread Creation (both methods)

15. ✅ Synchronization

16. ✅ String vs StringBuffer vs StringBuilder

17. ✅ String methods

18. ✅ File I/O

Medium Priority Topics (Likely)

1. 📌 Type Casting

2. 📌 Static Members

3. 📌 this and super keywords

4. 📌 Wrapper Classes

5. 📌 Packages and CLASSPATH

6. 📌 Custom Exceptions

7. 📌 Thread Lifecycle

8. 📌 Inter-thread Communication

Program Questions Most Likely

1. Constructor example (default + parameterized)


2. Method overloading example

3. Inheritance (single/multilevel)

4. Interface implementation

5. Exception handling program

6. Thread creation program

7. File read/write program

8. String manipulation program

QUICK REVISION SECTION

Complete Java Cheatsheet

Basic Structure

package packageName;

import [Link].*;

public class ClassName {

// Variables

int instanceVar;

static int classVar;

// Constructor

ClassName() { }

// Methods

void methodName() { }

static void staticMethod() { }

// Main method

public static void main(String[] args) {

ClassName obj = new ClassName();

}
Data Types Quick Reference

Siz Defau Range/


Type
e lt Values

byte 1B 0 -128 to 127

short 2B 0 ±32,767

int 4B 0 ±2.1 billion

±9
long 8B 0L
quintillion

float 4B 0.0f ±3.4E38

double 8B 0.0d ±1.7E308

'\
char 2B 0-65,535
u0000'

boolea
1bit false true/false
n

Operators Quick Reference

Category Operators

Arithmetic + - * / %

== != > <
Relational
>= <=

Logical && `

Assignme = += -= *=
nt /=

Unary ++ -- + - !

Ternary ?:

Control Structures

// if-else

if (condition) { } else if (condition) { } else { }

// switch

switch (variable) {

case value1: break;


case value2: break;

default: break;

// for loop

for (int i = 0; i < n; i++) { }

// for-each

for (type item : array) { }

// while

while (condition) { }

// do-while

do { } while (condition);

OOP Quick Reference

// Class and Object

class MyClass {

int x;

MyClass() { x = 0; }

MyClass(int x) { this.x = x; }

MyClass obj = new MyClass();

// Inheritance

class Child extends Parent { }

// Interface

interface MyInterface {

void method();

class MyClass implements MyInterface {

public void method() { }

// Abstract Class
abstract class AbstractClass {

abstract void method();

Exception Handling Template

try {

// risky code

} catch (SpecificException e) {

// handle specific

} catch (Exception e) {

// handle general

} finally {

// always executes

// throwing

throw new Exception("message");

void method() throws Exception { }

Thread Creation Templates

// Method 1: Extend Thread

class MyThread extends Thread {

public void run() { }

MyThread t = new MyThread();

[Link]();

// Method 2: Implement Runnable

class MyRunnable implements Runnable {

public void run() { }

Thread t = new Thread(new MyRunnable());

[Link]();
// Lambda (Java 8+)

Thread t = new Thread(() -> { });

[Link]();

String Operations Quick Reference

Operation Code

Length [Link]()

Character
[Link](i)
at i

Substring [Link](i, j)

Upper/ [Link]() /
Lower toLowerCase()

Trim [Link]()

Split [Link](",")

Replace [Link]("a", "b")

Contains [Link]("sub")

Equals [Link](other)

Compare [Link](other)

File I/O Templates

// Reading

BufferedReader br = new BufferedReader(new FileReader("[Link]"));

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]();

// Writing

BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));

[Link]("content");

[Link]();
[Link]();

OOP Summary Table

Concept Definition Implementation

Encapsulati private vars + public


Hiding data
on getters/setters

Hiding
Abstraction abstract class / interface
implementation

Inheritance Code reuse extends keyword

Polymorphi
Many forms overloading / overriding
sm

Exception Handling Summary

Keywo
Purpose Usage
rd

Wrap risky
try try { }
code

Handle
catch catch (Ex e) { }
exception

finally Always execute finally { }

Throw
throw throw new Ex()
exception

Declare void m() throws


throws
exception Ex

Thread Summary

Method Purpose

start() Begin thread execution

run() Contains thread code

sleep(ms) Pause thread

Wait for thread to


join()
complete

wait() Release lock and wait

notify() Wake one waiting


Method Purpose

thread

synchroniz Lock for mutual


ed exclusion

Java Keywords Table

Keyword Purpose

class Declare class

interface Declare interface

extends Inheritance

implement
Implement interface
s

abstract Abstract class/method

static Class-level member

Constant/cannot
final
override

this Current object

super Parent class

new Create object

void No return value

return Return value

Accessible
public
everywhere

Accessible only in
private
class

protected Package + subclasses

try Exception try block

catch Handle exception

throw Throw exception

throws Declare exception


Keyword Purpose

synchroniz Thread
ed synchronization

Important Syntax Table

Operation Syntax

public static void main(String[]


Main method
args)

Print [Link]("text");

Input Scanner sc = new


(Scanner) Scanner([Link]);

Array int[] arr = new int[5];

For-each for (int x : arr) { }

ClassName obj = new


Create object
ClassName();

String to int [Link]("123")

int to String [Link](123)

STUDY STRATEGIES

1-Day Study Strategy

Morning (4 hours): Core Concepts

Hour 1-2: Unit I & II Fundamentals

 Java features, JVM architecture

 Classes, objects, constructors

 Encapsulation, inheritance basics

Hour 3-4: Unit II & III

 Method overloading/overriding

 Interfaces vs abstract classes

 Exception handling (try-catch-finally)

Afternoon (4 hours): Remaining Topics

Hour 5-6: Unit III & IV

 Packages, CLASSPATH
 Multithreading basics

 Thread creation methods

Hour 7-8: Unit IV & Programs

 String, StringBuffer, StringBuilder

 File I/O basics

 Practice 5-10 important programs

Evening (2 hours): Revision

 Quick revision sheets

 Important questions

 MCQs

3-Hour Quick Revision Strategy

Hour 1: Concepts (40 min) + Programs (20 min)

 Read all quick revision sheets

 Focus on definitions and key points

 Review 5 most important programs

Hour 2: Questions (60 min)

 Go through top 50 important questions

 Read model answers mentally

 Focus on high-priority topics

Hour 3: Final Prep (60 min)

 Review cheatsheet

 Memorize important tables

 Last look at difference tables

 Relax before exam

Topic Priority for Limited Time

If You Have 6 Hours

Priori
Topics Time
ty

1 OOP (class, object, constructor, 1.5 hr


Priori
Topics Time
ty

inheritance)

2 Exception Handling 1 hr

45
3 Interface & Abstract Class
min

45
4 Multithreading (basics)
min

45
5 String & StringBuffer
min

6 Important Programs 1.5 hr

If You Have 3 Hours

Priori
Topics Time
ty

OOP basics + 45
1
Inheritance min

30
2 Exception Handling
min

30
3 Interface vs Abstract
min

30
4 Thread creation
min

30
5 String operations
min

15
6 Quick program review
min

Last Night Tips

1. Don't learn new topics — only revise what you know

2. Focus on high-weightage topics — OOP, Exception, Threads

3. Review programs — understand logic, not memorize

4. Sleep well — at least 5-6 hours

5. Keep notes handy — quick revision sheets


6. Stay calm — confidence is key

Exam Day Strategy

1. Read questions carefully — understand what's asked

2. Attempt known questions first — secure marks quickly

3. Write programs neatly — include comments

4. Draw diagrams — for architecture, lifecycle questions

5. Use proper formatting — headings, bullets, tables

6. Manage time — don't spend too long on one question

7. Attempt all questions — partial marks count

Best of luck with your exam! 🎯

This comprehensive study material covers all topics from your syllabus
with explanations, programs, and exam-oriented content. Focus on
understanding concepts rather than memorizing, and practice the
important programs.

You might also like