1.
this and super (10 Marks)
In Java, this and super are special keywords used to refer to objects. They help in
accessing variables, methods, and constructors in situations where ambiguity occurs due to
inheritance or naming conflicts.
this keyword
this refers to the current object inside a method or constructor. It is used when the local
variable name and instance variable name are the same.
Uses of this:
1. To refer to instance variables:
When local and instance variables have the same name, this removes confusion.
2. To call current class methods:
[Link]() is used when we want to call another method of the same class.
3. To invoke current class constructor:
this() is used for constructor chaining inside the same class.
4. To return the current object:
Useful in method chaining patterns.
5. To pass the current object as an argument:
It is used with event handlers and callbacks.
super keyword
super represents the parent class object. It is mainly used in inheritance to access parent
features.
Uses of super:
1. To access parent class variables:
Used when both parent and child have variables with the same name.
2. To call parent class method:
Helpful in method overriding to call the original version.
3. To call parent class constructor:
super() is always the first statement in a constructor.
4. To differentiate parent methods and child methods.
Both keywords help in avoiding ambiguity, supporting inheritance, and improving readability.
---
2. Types of Inheritance (10 Marks)
Inheritance allows a class to acquire properties and behaviors of another class. Java
supports inheritance to promote code reuse and achieve polymorphism.
Types of Inheritance in Java:
1. Single Inheritance:
One parent class and one child class.
Example: A → B
2. Multilevel Inheritance:
One class extends another class, forming a chain.
Example: A → B → C
3. Hierarchical Inheritance:
Multiple child classes inherit from the same parent class.
Example:
A
/ \
B C
4. Hybrid Inheritance:
A combination of different inheritance types.
Achieved using interfaces only.
Not Supported in Java:
Multiple inheritance using classes (because of ambiguity known as the “Diamond Problem”).
But Java supports it using interfaces.
Importance:
Reusability of code
Reduces redundancy
Helps achieve runtime polymorphism
Improves class structure and maintenance
---
3. Static Keyword (10 Marks)
The static keyword is used to make members belong to the class, not to individual objects.
Forms of Static Members:
1. Static Variables:
Shared by all objects; only one copy exists.
2. Static Methods:
Can be called without creating an object.
They cannot use non-static members directly.
3. Static Blocks:
Executed when the class loads.
Used for initializing static data.
4. Static Nested Classes:
Can be accessed without object of the outer class.
Advantages:
Memory efficient
Easy access
Useful for utility functions
Supports shared resources
Example:
public static void main(String[] args) is static so the JVM can run it without creating an object.
---
4. Abstract Keyword (10 Marks)
The abstract keyword is used to define abstract classes and abstract methods.
Abstract Class:
Cannot be instantiated.
Can have both abstract and concrete methods.
Provides partial implementation.
Used as a base class for subclasses.
Abstract Method:
Declared without body.
Must be implemented by subclass.
Ensures that all subclasses follow a common structure.
Uses of Abstract Keyword:
Helps achieve abstraction.
Supports dynamic polymorphism.
Helps create templates for child classes.
Forces subclasses to implement required methods.
Features:
Can have constructors.
Can have variables and non-abstract methods.
Cannot be final.
---
5. throws & throw (10 Marks)
Both are used in exception handling but serve different purposes.
throw keyword:
Used to throw an exception manually.
Used inside method body.
Can throw only one exception at a time.
Syntax: throw new ExceptionType();
throws keyword:
Used in method declaration.
Specifies that method may throw an exception.
Transfers responsibility to the caller.
Can declare multiple exceptions.
Differences:
throw → actually throws the exception
throws → declares the exception
throw inside method; throws in method signature
throw is for one exception; throws can declare many
---
6. final, finally, finalize (10 Marks)
These three terms look similar but serve different purposes.
final
A keyword.
Used to make:
Variable → constant
Method → cannot be overridden
Class → cannot be inherited
finally
A block used in exception handling.
Executes whether exception occurs or not.
Used for closing files, releasing resources.
finalize()
A method called by Garbage Collector.
Used to release non-memory resources.
Execution is not guaranteed.
Conclusion:
final is for restriction,
finally is for cleanup,
finalize is for garbage collection.
---
7. Object and Class (10 Marks)
A class is a blueprint and an object is an instance created using that blueprint.
Class:
Logical structure
Contains data members (variables) and methods
Does not take memory until object creation
Helps implement OOP concepts
Object:
Real-world entity
Created using new keyword
Has identity, state, and behavior
Occupies memory in RAM
Relationship:
Class = Design
Object = Actual product
---
8. Constructor (10 Marks)
A constructor is a special method used to initialize objects.
Properties:
Has same name as class
No return type
Automatically invoked during object creation
Used to set initial values
Types:
1. Default Constructor:
Provided by compiler if no constructor exists.
2. Parameterized Constructor:
Accepts parameters to initialize variables with custom values.
3. Copy Constructor (user-defined):
Copies values from one object to another.
Constructor Overloading:
Multiple constructors with different parameter lists.
Importance:
Initializes objects
Allocates resources
Ensures proper setup of object state
---
9. Stream Classes in Java I/O (10 Marks)
Streams are used for data input and output in Java.
Types of Streams:
1. Byte Streams:
Used for binary data.
FileInputStream
FileOutputStream
2. Character Streams:
Used for text data.
FileReader
FileWriter
3. Buffered Streams:
Used to increase performance.
BufferedReader
BufferedWriter
4. Data Streams:
Used to read/write primitive data types.
DataInputStream
DataOutputStream
5. Object Streams:
Used for object serialization.
ObjectInputStream
ObjectOutputStream
Advantages of Streams:
Efficient data handling
Supports file processing
Supports reading/writing primitives and objects
Helps in communication with external devices
---
10. Polymorphism (10 Marks)
Polymorphism means “many forms”. In Java, same method behaves differently based on the
object.
Types of Polymorphism:
1. Compile-Time Polymorphism:
Method Overloading
Same method name with different parameters
Resolved during compile time
2. Runtime Polymorphism:
Method Overriding
Same method name in parent and child
Resolved at runtime using dynamic binding
Importance:
Increases flexibility
Code becomes reusable
Supports OOP concepts
Improves readability and scalability
---
11. Interface (10 Marks)
An interface in Java is a 100% abstract type used to define a contract.
Features:
Contains abstract methods (before Java 8)
From Java 8: can include default, static, and private methods
Supports multiple inheritance
Variables are public, static, and final
Cannot be instantiated
Implemented using implements keyword
Uses:
Achieve abstraction
Achieve multiple inheritance
Create loose coupling
Define common behavior for unrelated classes
---
12. Encapsulation (10 Marks)
Encapsulation means binding data and methods in a single unit (class) and protecting data
from outside access.
Features:
1. Data is declared as private.
2. Public getter and setter methods are used for access.
3. Prevents unauthorized access.
4. Improves data security.
5. Helps maintain code easily.
Advantages:
Data hiding
Controlled data access
Increased reliability
Better code maintainability
---
13. Usage of this (10 Marks)
this refers to the current object. It is used when the method or constructor needs to access
object-level properties.
Major Uses:
1. To refer current object instance variables
2. To call another method of the same class
3. For constructor chaining using this()
4. To pass the current object as argument
5. To return current object
6. To avoid naming conflicts
7. To improve clarity and readability
---
14. Identifier (10 Marks)
An identifier is the name given to variables, classes, objects, methods, packages, or
interfaces in Java.
Rules for Identifiers:
1. Cannot start with a digit
2. Cannot contain spaces
3. Cannot be a Java keyword
4. Only letters, digits, underscore, and $ allowed
5. Case-sensitive
6. Should be meaningful for better readability
EXAMPLES:
Valid: studentName, _count, $value
Invalid: 2number, class, my name
Importance:
Identifiers help the compiler and programmer refer to data and methods accurately and
clearly.
✅ 15. Exception Handling (try–catch) – 10 Marks
Exception handling in Java is a mechanism to handle runtime errors so the program doesn’t
crash unexpectedly. Java provides a robust structure using try, catch, finally, throw, and
throws to manage abnormal conditions.
Why Exception Handling is Needed
Prevents sudden termination of programs
Makes applications more reliable
Separates “error-handling logic” from “normal logic”
Helps identify and debug problems easily
try–catch Explanation
try block
Contains code that may cause an exception. Only risky statements are placed here.
catch block
Executes when a matching exception occurs. Java allows multiple catch blocks for handling
different exception types.
General Syntax
try {
// risky code
} catch (ExceptionType e) {
// handling code
}
How It Works
1. Code inside try executes normally.
2. If an exception occurs → try block stops immediately.
3. JVM searches for a matching catch block.
4. If found → that catch handles the exception.
5. If NOT found → program terminates with an error.
Example
public class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0; // risky code
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
}
}
Advantages
Makes applications robust and crash-free
Helps in clean error messages
Allows grouping of error-prone code
---
✅ 16. Exception Handling Keywords – 10 Marks
Java provides five main keywords for exception handling:
---
1. try
Used to enclose statements that may cause exceptions.
Without try, catch cannot exist.
---
2. catch
Handles the specific exception thrown by the try block.
Multiple catch blocks are allowed.
Syntax:
catch (ExceptionType e) { }
---
3. finally
Executes always, whether an exception occurs or not.
Used for closing resources like files, DB connections.
---
4. throw
Used to throw an exception intentionally.
Example:
throw new ArithmeticException("Error!");
---
5. throws
Used in method declaration to indicate that the method may throw exceptions.
Delegates handling responsibility to the calling method.
Example:
void test() throws IOException { }
---
Extra – Optional
Checked vs Unchecked exceptions
Checked: must be handled (IOException, SQLException)
Unchecked: runtime exceptions (ArithmeticException, NullPointerException)
---
✅ 17. Event Handling (10 Marks)
Event handling is a mechanism in Java used to manage user actions such as clicking,
typing, dragging, or pressing keys. It is essential for building GUI applications using AWT
and Swing.
---
What is an Event?
An event is any interaction by the user or system, such as:
Button click
Mouse movement
Key press
Window closing
---
Event Handling Model (Delegation Model)
Java follows the Delegation Event Model, which has 3 main components:
---
1. Event Source
The object that generates the event
Example: Button, TextField, Window
2. Event Object
Contains information about the event
E.g., ActionEvent, MouseEvent, KeyEvent
3. Event Listener
Interface that receives the event and performs action
Example: ActionListener, MouseListener
---
Steps in Event Handling
1. Create GUI components
2. Register listeners to components
3. Write event-handling code inside listener methods
---
Example
import [Link].*;
import [Link].*;
class Demo extends Frame implements ActionListener {
Button b;
Demo() {
b = new Button("Click");
add(b);
[Link](this);
setSize(300, 300);
setLayout(new FlowLayout());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
}
---
✅ 18. ActionEvent – 10 Marks
ActionEvent is a class in the [Link] package.
It is generated when a user performs an “action” such as:
Clicking a button
Pressing Enter in TextField
Selecting menu items
---
Important Features
Part of event-handling mechanism
Works with ActionListener interface
Contains action command and event details
---
Constructor
ActionEvent(Object source, int id, String command)
---
Useful Methods
getActionCommand() → returns command string
getSource() → returns event source
getID() → returns ID of event
---
Example Using ActionEvent
public void actionPerformed(ActionEvent e) {
String cmd = [Link]();
[Link]("You clicked: " + cmd);
}
---
✅ 19. Working of Event Handling – 10 Marks
Event handling in Java works using the Delegation Event Model, where events are
generated by sources and handled by listeners.
---
Working Process
1. Event Occurs
User interacts (click, type, mouse move).
2. Event Source Generates Event Object
Example: Button → ActionEvent
3. Event Object Is Passed to Listener
Example: ActionListener receives ActionEvent
4. Listener Executes Handler Method
Example: actionPerformed() executes
5. Appropriate Action Happens
Output displayed, window updated, etc.
---
Why Delegation Model?
Fast and efficient
Only the listener who is registered receives the event
Better separation of GUI and logic
---
Main Listener Interfaces
ActionListener
MouseListener
KeyListener
WindowListener
---
Example Flow
Button click → ActionEvent → ActionListener → actionPerformed() runs
---
✅ 20. File Handling – 10 Marks
File handling in Java allows programs to store, read, and write data permanently on disk.
---
Why File Handling?
Data persistence
Reading configuration files
Writing logs
Processing external files
---
Main Classes ([Link] package)
1. File – represents a file or directory
2. FileInputStream – reads bytes
3. FileOutputStream – writes bytes
4. FileReader – reads characters
5. FileWriter – writes characters
6. BufferedReader – efficient reading
7. BufferedWriter – efficient writing
---
Reading a File Example
import [Link].*;
class ReadDemo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
}
}
---
Writing to a File Example
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello World");
[Link]();
---
Advantages
Permanent storage
Efficient input/output
Can handle text, binary files, media, etc.
21. String & StringBuffer / StringBuilder (10 Marks)
String in Java
A String in Java is an object that represents a sequence of characters. Strings are
immutable, meaning once a string is created, it cannot be changed. Any modification creates
a new string object.
Features of String
1. Stored in String Constant Pool for memory efficiency.
2. Immutable → safer in multithreading.
3. Provides many utility methods like length(), substring(), charAt(), toUpperCase(), etc.
4. Since every change creates a new object, it is less efficient for repeated modifications.
StringBuffer
StringBuffer is a mutable (modifiable) sequence of characters.
Methods modify the same object instead of creating new ones.
Thread-safe (synchronized).
Slightly slower because of synchronization.
StringBuilder
StringBuilder is also mutable like StringBuffer but
Not thread-safe
Faster than StringBuffer
Preferred when a single thread modifies strings repeatedly.
Differences
Feature String StringBuffer StringBuilder
Mutability Immutable Mutable Mutable
Thread safety Yes Yes No
Speed Slow Medium Fast
Best Use Fixed text Multiple appends/updates High-performance updates
Conclusion
Use String for constant data, StringBuffer when thread safety is needed, and StringBuilder
for fast, single-thread string operations.
---
22. Swing Example Program (10 Marks)
A simple Swing program that displays a window with a button.
Explanation
Swing is an advanced GUI toolkit in Java that provides lightweight components like JFrame,
JButton, JLabel, JTextField, etc. Swing is platform-independent and built on top of AWT.
Program
import [Link].*;
class SimpleSwing {
public static void main(String[] args) {
JFrame f = new JFrame("Simple Swing Window");
JButton b = new JButton("Click Me");
[Link](100, 100, 120, 40);
[Link](b);
[Link](300, 300);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Explanation
JFrame creates the main window
JButton creates a button
setBounds() sets position and size
setVisible(true) displays the frame
This demonstrates basic Swing GUI creation.
---
23. Swing Application Program (10 Marks)
A Swing application that takes input from the user.
Program: Simple Login Window
import [Link].*;
import [Link].*;
class LoginApp extends JFrame implements ActionListener {
JTextField user;
JPasswordField pass;
JButton login;
LoginApp() {
JLabel l1 = new JLabel("Username:");
[Link](50, 50, 100, 30);
JLabel l2 = new JLabel("Password:");
[Link](50, 100, 100, 30);
user = new JTextField();
[Link](150, 50, 150, 30);
pass = new JPasswordField();
[Link](150, 100, 150, 30);
login = new JButton("Login");
[Link](120, 160, 100, 35);
[Link](this);
add(l1); add(l2);
add(user); add(pass);
add(login);
setSize(400, 300);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String u = [Link]();
String p = [Link]([Link]());
[Link](this, "Welcome " + u);
}
public static void main(String[] args) {
new LoginApp();
}
}
Explanation
This program creates a login form using Swing components.
Uses ActionListener to handle button clicks.
JTextField, JPasswordField, and JButton are core input controls.
---
24. How to Create a Frame (AWT / Swing) (10 Marks)
Creating Frame Using AWT
AWT (Abstract Window Toolkit) is Java’s original GUI library. It uses native system
components.
Program
import [Link].*;
class AwtFrame {
AwtFrame() {
Frame f = new Frame("AWT Frame");
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new AwtFrame();
}
}
Creating Frame Using Swing
Swing uses lightweight components and provides more features.
Program
import [Link].*;
class SwingFrame {
SwingFrame() {
JFrame f = new JFrame("Swing Frame");
[Link](300, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
public static void main(String[] args) {
new SwingFrame();
}
}
Explanation
AWT uses Frame
Swing uses JFrame
Both need size and visibility
Swing supports advanced GUI components and is preferred for modern applications
---
25. AWT Example (Application) (10 Marks)
A simple AWT application that displays a GUI with label, text field, and button.
Program: AWT Form
import [Link].*;
import [Link].*;
class AwtApp extends Frame implements ActionListener {
TextField tf;
Button b;
AwtApp() {
Label l = new Label("Enter Name:");
[Link](50, 50, 100, 30);
tf = new TextField();
[Link](160, 50, 150, 30);
b = new Button("Submit");
[Link](120, 120, 80, 30);
[Link](this);
add(l);
add(tf);
add(b);
setSize(350, 250);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String name = [Link]();
[Link]("Entered: " + name);
}
public static void main(String[] args) {
new AwtApp();
}
}
✅ 26. Final Keyword and Where It Is Used – (10 Marks)
The final keyword in Java is a non-access modifier used to restrict modification of variables,
methods, and classes. It ensures that once something is declared as final, it cannot be
changed further. It helps in security, optimization, and preventing accidental changes in
code.
---
1. final Variable
A final variable becomes a constant.
Once assigned, its value cannot be changed.
Must be initialized at declaration or inside a constructor.
Example:
final int MAX = 100;
---
2. final Method
A final method cannot be overridden in subclasses.
Useful for keeping important logic unchanged.
Example:
final void display() { }
---
3. final Class
A final class cannot be inherited.
Used for security and avoiding misuse.
Example:
final class Bank { }
---
4. final with Reference Variables
The reference cannot change,
But the internal data of the object can change.
---
5. Uses of final Keyword
To create constants
To improve security
To prevent inheritance
To prevent method overriding
To ensure fixed values (e.g., Pi, fees, interest rate)
---
Example Combining All
final class Demo {
final int x = 10;
final void show() {
[Link](x);
}
}
---
✅ 27. Autoboxing & Unboxing (Difference) – (10 Marks)
Java introduces autoboxing and unboxing to automatically convert between primitive types
and wrapper classes.
---
Autoboxing
Automatic conversion primitive → object (wrapper)
Example:
int a = 10;
Integer obj = a; // autoboxing
---
Unboxing
Automatic conversion object (wrapper) → primitive
Example:
Integer x = 20;
int y = x; // unboxing
---
Difference Table
Feature Autoboxing Unboxing
Meaning primitive → wrapper wrapper → primitive
Direction Upgrading to object Downgrading to primitive
Who does it? Compiler Compiler
Example int → Integer Integer → int
Purpose Use primitives in collections Extract primitive for calculation
---
Why Needed?
Collections like ArrayList work only with objects
Avoids writing manual conversions
Makes code clean and readable
---
✅ 28. Autoboxing vs Boxing (Difference) – (10 Marks)
These two terms look similar but they are different.
---
Boxing
Manual conversion of primitive to wrapper class.
Example:
int a = 5;
Integer obj = new Integer(a); // boxing
---
Autoboxing
Automatic conversion of primitive to wrapper class.
Example:
Integer obj = 5; // autoboxing
---
Difference Table
Feature BoxingAutoboxing
Type Manual Automatic
Requires new operator? Yes No
Code size Long and messy Short and clean
Available fromJava 1.2 Java 1.5
Example new Integer(10) Integer x = 10
---
PACKAGES
---
✅ 29. Access Modifiers (Types) – (10 Marks)
Access modifiers control the visibility and accessibility of classes, methods, and variables.
Java provides four types:
---
1. public
Accessible from anywhere
No restrictions
Example:
public int x;
---
2. private
Accessible only inside the same class
Highest level of protection
Example:
private int age;
---
3. protected
Accessible within:
✔ same class
✔ same package
✔ child class in another package
Example:
protected void show() { }
---
4. default (no modifier)
Accessible only in same package
Also called package-private
Example:
int speed;
---
Why Access Modifiers?
Data security
Encapsulation
Controlled access
Implementation hiding
---
✅ 30. Types of Packages – (10 Marks)
Packages in Java group related classes and interfaces together.
They help in organizing large projects.
---
1. Built-in Packages
Provided by Java library (JDK). Examples:
[Link] – String, Math
[Link] – Scanner, ArrayList
[Link] – file handling
[Link] – GUI components
[Link] – Swing GUI
---
2. User-Defined Packages
Packages created by the programmer.
Example:
package mypack;
public class Hello {
void show() { }
}
---
Advantages of Packages
Avoid name conflicts
Easy maintenance
Reusability
Improved organization
---
✅ 31. How to Create a Package – (10 Marks)
To create your own package in Java:
---
Step 1: Create a Class
package mypack;
public class Test {
public void show() {
[Link]("Hello from package");
}
}
---
Step 2: Save the File
Save as:
[Link] inside folder mypack
---
Step 3: Compile with -d Option
javac -d . [Link]
This creates proper directory structure.
---
Step 4: Use Package in Another Program
import [Link];
class Demo {
public static void main(String[] args) {
Test t = new Test();
[Link]();
}
}
---
Benefits
Cleaner project structure
Code reusability
Modular development
---
CLASS CONCEPTS
---
✅ 32. Class Inside Class (Nested Class) – (10 Marks)
A nested class is a class defined inside another class.
Useful for grouping classes that belong together logically.
---
Types of Nested Classes
1. Member Inner Class
Defined inside another class but outside methods.
class Outer {
class Inner { }
}
---
2. Static Nested Class
Acts like a static member.
class Outer {
static class Inner { }
}
---
3. Local Inner Class
Class defined inside a method.
void show() {
class Inner { }
}
---
4. Anonymous Inner Class
Class without a name; used for event handling.
new Thread() {
public void run() { }
};
---
Advantages
Logical grouping
Better encapsulation
Can access private members of outer class
---
Example
class Outer {
int data = 10;
class Inner {
void display() {
[Link](data);
}
}
}
---
✅ 33. Class vs Object (Class Society Difference) – (10 Marks)
This simply means difference between class and object.
---
Class
A blueprint or template
Does not occupy memory
Defines properties and behavior
Example:
class Student { }
---
Object
A real instance of a class
Occupies memory
Accesses methods and variables
Example:
Student s = new Student();
---
Difference Table
Feature Class Object
Meaning Blueprint Real instance
Memory No memory Takes memory
Purpose Defines structure Performs actions
Keyword class new
Example class Car {} Car c = new Car()
---
Why Both Are Needed?
Class gives structure
Object brings structure to life