Java
Unit 1
1. What are the basic concepts of Object-Oriented Programming (OOP)?
Main Concepts:
Concept Description
Object Real-world entity
Class Blueprint for objects
Encapsulation Wrapping data and methods together
Abstraction Hiding internal details and showing functionality
Inheritance Acquiring properties from parent class
Polymorphism Many forms (method overloading/overriding)
Dynamic Binding Runtime decision to call methods
Message Passing Objects communicate via method calls
2. What is a Class and Object in Java? Explain with example.
🔹 Class: Template for objects
🔹 Object: Instance of a class
✅ Code Example:
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving...");
}
public static void main(String[] args) {
Car myCar = new Car(); // Creating object
System.out.println(myCar.color); // Access variable
myCar.drive(); // Call method
}
}
3. Explain Encapsulation and Abstraction with examples.
🧷 Encapsulation Example:
class Employee {
private int salary; // private variable
public void setSalary(int s) {
salary = s;
}
public int getSalary() {
return salary;
}
}
Access through getters and setters → encapsulated!
🧷 Abstraction Example:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
✅ 4. Explain Inheritance in Java.
Types of Inheritance:
Single
Multilevel
Hierarchical
✅ Code Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); d.bark();
}
}
5. Explain Polymorphism with examples.
Compile-time Polymorphism (Overloading)
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Run-time Polymorphism (Overriding)
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
6. What is Dynamic Binding?
Dynamic Binding (Late Binding): Method call is decided at runtime.
Example:
Animal a = new Dog();
a.sound(); // Calls Dog’s sound() method at runtime
7. Explain Message Passing in Java.
Message passing is done through method calls:
class Person {
void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
Person p = new Person(); // Object
p.greet(); // Message (method call)
}
}
8. What are the features of Java?
Feature Description
Platform Independent Bytecode can run on any OS
Simple Easy syntax, no pointers
Object-Oriented Based on OOP concepts
Secure No memory corruption
Robust Strong memory management
Multithreaded Supports multithreaded apps
Distributed Built-in networking features
9. What is JVM and Bytecode in Java?
JVM (Java Virtual Machine): Runs the bytecode
Bytecode: Intermediate code generated by the compiler
Compilation Flow Diagram:
Java Source Code → .class File (Bytecode) → JVM → Machine Code
10. Write a simple Java program to print "Hello World".
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
11. How are Command Line Arguments used in Java?
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}
Run using:
java CommandLineExample Hello
12. List and explain Data Types in Java.
Type Example
int 5
float 5.5f
double 5.55
boolean true/false
Type Example
char 'A'
byte 8-bit value
long 64-bit int
13. What is Type Casting? Explain with example.
Implicit:
int x = 10;
double y = x; // auto type casting
Explicit:
double d = 10.5;
int i = (int)d; // manual casting
14. Explain various operators with examples.
➕ Arithmetic Operators
int a = 5, b = 2;
System.out.println(a + b); // 7
System.out.println(a - b); // 3
System.out.println(a * b); // 10
System.out.println(a / b); // 2
⬆️ Increment/Decrement
int x = 10;
System.out.println(++x); // 11
System.out.println(x--); // 11 then 10
🔢 Relational Operators
System.out.println(10 > 5); // true
System.out.println(10 == 5); // false
✅ Logical Operators
System.out.println(true && false); // false
System.out.println(true || false); // true
🔁 Bitwise Operators
int x = 5 & 3; // 1
int y = 5 | 3; // 7
❓ Conditional (Ternary)
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // 20
OOP and Execution in Java
+---------------+
| Java Code |
+---------------+
|
V
+---------------+ +-----------------+
| .class (Bytecode) | → | JVM Interpreter |
+---------------+ +-----------------+
|
V
+---------------+
| Machine Code |
+---------------+
Unit 2
1. Explain if, if-else, else-if ladder and switch statements in Java.
if Statement
int a = 10;
if (a > 5) {
System.out.println("a is greater than 5");
}
if-else Statement
if (a % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
else-if Ladder
int marks = 75;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 60) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
switch Statement
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid");
}
2. Explain Looping in Java with examples.
For Loop
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
While Loop
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Do-While Loop
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
3. Define Class, Object, and Method with example.
🔹 Class → A blueprint of object
🔹 Object → Instance of a class
🔹 Method → Behavior of object
Example:
class Car {
String color = "Red";
void start() {
System.out.println("Car is starting...");
}
public static void main(String[] args) {
Car myCar = new Car(); // Object
System.out.println(myCar.color); // Accessing variable
myCar.start(); // Calling method
}
}
4. What are constructors in Java? How are they different from methods?
Constructor is a special method that is called automatically when an object is
created.
Example:
class Student {
String name;
// Constructor
Student(String n) {
name = n;
}
void show() {
System.out.println("Name: " + name);
}
public static void main(String[] args) {
Student s = new Student("Ravi");
s.show();
}
}
5. What are Wrapper Classes in Java?
Java provides wrapper classes to wrap primitive types into objects.
Primitive Wrapper
int Integer
char Character
boolean Boolean
Example:
int a = 10;
Integer i = Integer.valueOf(a); // Boxing
int b = i.intValue(); // Unboxing
System.out.println(i + ", " + b);
6. What is method nesting? Give an example.
Nesting of methods means calling one method from another within the same
class.
Example:
class Nesting {
void display() {
System.out.println("Display method");
greet(); // Nested method call
}
void greet() {
System.out.println("Hello from greet()");
}
public static void main(String[] args) {
Nesting n = new Nesting();
n.display();
}
}
7. Explain method overriding with example.
Overriding occurs when a subclass provides its own implementation of a method
inherited from the superclass.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Calls overridden method in Dog
}
}
8. What is a final class? Can we override its methods?
A final class cannot be inherited.
If a method is marked final, it cannot be overridden.
Example:
final class FinalClass {
final void display() {
System.out.println("Final method");
}
}
// class Child extends FinalClass { } // ❌ Error
class Example {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}
9. What are visibility controls in Java?
Java uses access modifiers to control the visibility of classes and members:
Modifier Same Class Same Package Subclass Other Packages
private ✅ ❌ ❌ ❌
default ✅ ✅ ✅ ❌
protected ✅ ✅ ✅ ❌ (except subclass)
public ✅ ✅ ✅ ✅
10. How do arrays work in Java? Give example.
Arrays are containers that hold fixed-size values of the same type.
✅ Example:
public class ArrayExample {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
for (int i = 0; i < arr.length; i++) {
System.out.println("Element " + i + ": " + arr[i]);
}
}
}
11. What are Strings in Java? How do you use them?
Strings are objects in Java used to store text.
String Example:
public class StringExample {
public static void main(String[] args) {
String s = "Hello";
System.out.println(s.length()); // 5
System.out.println(s.charAt(1)); // e
System.out.println(s.concat(" World")); // Hello World
System.out.println(s.toUpperCase()); // HELLO
}
}
📘 Summary: Java Control Structures Overview
┌──────────────┐
│ if/else │
│ else-if │
│ switch │
└────┬─────────┘
↓
┌──────────────┐
│ Loops │
│ for │
│ while │
│ do-while │
└────┬─────────┘
↓
┌──────────────┐
│ Classes │
│ Constructors│
│ Wrappers │
└────┬─────────┘
↓
┌──────────────┐
│ Inheritance, │
│ Overriding │
│ final, array │
└──────────────┘
Unit 3
What is Inheritance in Java? Explain its types with example.
Inheritance allows one class (child/subclass) to inherit properties and behavior
(methods and fields) from another class (parent/superclass).
➤ Types of Inheritance in Java:
Type Description Supported in Java
One subclass inherits from one
Single ✅ Yes
parent
Class inherits from a derived
Multilevel ✅ Yes
class
Multiple classes inherit from one
Hierarchical
class ✅ Yes
One class inherits from multiple ❌ No (but can be done using
Multiple
classes interfaces)
Combination of multiple and
Hybrid ✅ Partially (via interfaces)
multilevel
Multilevel Inheritance
Class A
↓
Class B
↓
Class C
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps");
}
public static void main(String[] args) {
Puppy p = new Puppy();
p.sound(); // From Animal
p.bark(); // From Dog
p.weep(); // From Puppy
}
}
What is an abstract class in Java? Give example.
An abstract class is a class that cannot be instantiated and may contain abstract
(unimplemented) methods.
Example:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
class Test {
public static void main(String[] args) {
Shape s = new Circle(); // Upcasting
s.draw();
}
}
3. What is an interface in Java? How is it different from an abstract class?
An interface is a blueprint of a class that contains only abstract methods (till
Java 7) and constants. From Java 8 onwards, interfaces can have default and
static methods.
Example:
interface Drawable {
void draw();
}
class Rectangle implements Drawable {
public void draw() {
System.out.println("Drawing Rectangle");
}
}
class TestInterface {
public static void main(String[] args) {
Drawable d = new Rectangle();
d.draw();
}
}
Abstract Class vs Interface
Abstract Class Interface
Can have constructors Cannot have constructors
Can have instance variables Cannot (only constants)
Can have non-abstract methods Only default/static methods
4. What is a Package in Java? How to create and use it?
A package is a namespace that organizes a set of related classes and interfaces.
✅ Creating and using a package:
1. Create package and class
// File: mypack/Message.java
package mypack;
public class Message {
public void show() {
System.out.println("Hello from package");
}
}
2. Use package in another file
// File: Test.java
import mypack.Message;
class Test {
public static void main(String[] args) {
Message m = new Message();
m.show();
}
}
5. What is Multithreading in Java? Explain the life cycle of a thread.
Multithreading allows the execution of multiple threads simultaneously to
perform tasks concurrently.
Thread Life Cycle:
NEW
↓
RUNNABLE → RUNNING
↑ ↓
WAITING ← BLOCKED
↓
TERMINATED
6. Explain how to create a thread in Java using two methods.
✔️ Method 1: Extending Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running using Thread class");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // starts thread
}
}
✔️ Method 2: Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running using Runnable");
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
7. What are thread methods? Explain with example.
Method Description
start() Starts a thread
run() Defines code to execute in the thread
sleep(ms) Sleeps the thread
join() Waits for a thread to die
isAlive() Checks if thread is alive
Example using sleep and join:
class SleepJoinExample extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(500); // 0.5 sec
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args) {
SleepJoinExample t1 = new SleepJoinExample();
SleepJoinExample t2 = new SleepJoinExample();
t1.start();
try {
t1.join(); // t2 starts after t1 finishes
} catch (Exception e) {
}
t2.start();
}
}
8. What is Thread Priority in Java?
Each thread has a priority: MIN_PRIORITY (1), NORM_PRIORITY (5),
MAX_PRIORITY (10)
class PriorityExample extends Thread {
public void run() {
System.out.println("Running thread: " +
Thread.currentThread().getPriority());
}
public static void main(String[] args) {
PriorityExample t1 = new PriorityExample();
PriorityExample t2 = new PriorityExample();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
9. What is synchronization in Java? Why is it needed?
Synchronization ensures that only one thread can access a resource at a time,
preventing race conditions.
✅ Example without synchronization (may produce inconsistent output):
class Table {
void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) { this.t = t; }
public void run() { t.printTable(5); }
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) { this.t = t; }
public void run() { t.printTable(100); }
}
public class WithoutSync {
public static void main(String[] args) {
Table obj = new Table(); // shared resource
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
With Synchronization:
class Table {
synchronized void printTable(int n) { // synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
Unit 4
1. What is Exception Handling in Java? Explain its fundamentals with an
example.
Answer:
An exception is an abnormal condition that disrupts the normal flow of a
program.
Java handles these using a mechanism known as Exception Handling.
It uses try-catch-finally blocks to handle exceptions gracefully without
crashing the program.
Diagram:
┌────────────┐
│ try │
└────┬───────┘
↓
┌────────────┐
│ catch block│ ← handles specific exception
└────┬───────┘
↓
┌────────────┐
│ finally │ ← always executed
└────────────┘
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
2. What are the types of exceptions in Java?
Answer:
Type Description Example
Checked at compile
Checked IOException, SQLException
time
ArithmeticException,
Unchecked Checked at runtime
NullPointerException
3. How to create a custom exception class in Java?
Answer:
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
static void checkAge(int age) throws AgeException {
if (age < 18)
throw new AgeException("Not eligible to vote");
else
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (AgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
4. Explain AWT controls like Button, Label, List, ComboBox with example.
Answer:
AWT (Abstract Window Toolkit) provides GUI components.
Component Description
Button Used to trigger an action
Label Displays a text
List Shows multiple options
Choice (ComboBox) Drop-down list
Example:
import java.awt.*;
public class AWTExample {
public AWTExample() {
Frame f = new Frame("AWT Controls");
Label label = new Label("Enter Name:");
label.setBounds(50, 50, 100, 30);
TextField tf = new TextField();
tf.setBounds(160, 50, 100, 30);
Button b = new Button("Click");
b.setBounds(100, 100, 80, 30);
f.add(label);
f.add(tf);
f.add(b);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AWTExample();
}
}
5. Explain Event Handling in AWT.
Answer:
Java uses delegation event model. Every GUI component can generate events
(like button click). Listeners handle them.
Steps:
1. Implement listener interface (ActionListener, ItemListener)
2. Override its method (actionPerformed, etc.)
3. Register listener to component using addActionListener()
Example with ActionListener:
import java.awt.*;
import java.awt.event.*;
public class EventExample {
public static void main(String[] args) {
Frame f = new Frame("Event Example");
Button b = new Button("Click Me");
b.setBounds(100, 100, 80, 30);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
f.add(b);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}
6. What are layout managers in Java?
Answer:
Layout managers control the positioning and sizing of components in a container.
Layout Description
FlowLayout Left to right (default for applets)
BorderLayout Divides into 5 regions
GridLayout Grid form
GridBagLayout Flexible grid
Null Layout Manual positioning
Diagram: BorderLayout
┌──────────────┐
│ NORTH │
├────┬────┬────┤
│WEST│CENTER│EAST│
├────┴────┴────┤
│ SOUTH │
└──────────────┘
7. List important string functions with example.
Answer:
public class StringFunctions {
public static void main(String[] args) {
String s = "Hello Java";
System.out.println(s.length()); // 10
System.out.println(s.charAt(1)); // e
System.out.println(s.substring(0, 5)); // Hello
System.out.println(s.toUpperCase()); // HELLO JAVA
System.out.println(s.toLowerCase()); // hello java
System.out.println(s.indexOf("Java")); // 6
System.out.println(s.replace("Java", "World")); // Hello World
}
}
8. Write a program to draw line, rectangle, circle, and ellipse using AWT.
Answer:
import java.awt.*;
import java.awt.event.*;
public class GraphicsExample extends Frame {
public void paint(Graphics g) {
g.drawLine(50, 50, 150, 50); // Line
g.drawRect(50, 70, 100, 50); // Rectangle
g.drawOval(50, 130, 50, 50); // Circle
g.drawOval(120, 130, 80, 40); // Ellipse
}
public static void main(String[] args) {
GraphicsExample f = new GraphicsExample();
f.setSize(300, 250);
f.setTitle("Graphics Demo");
f.setVisible(true);
}
}
Explanation:
drawLine(x1, y1, x2, y2)
drawRect(x, y, width, height)
drawOval(x, y, width, height) — Circle when width = height
Unit 5
1. Explain the overview of networking in Java.
Answer:
Java provides a rich library called java.net for network programming. It supports:
TCP (Transmission Control Protocol) — Reliable, connection-oriented.
UDP (User Datagram Protocol) — Unreliable, connection-less.
Java allows two main types of communication:
Client-Server Communication (Sockets)
Datagram Communication
Common classes:
Socket and ServerSocket (for TCP)
DatagramSocket and DatagramPacket (for UDP)
URL and URLConnection (for web-based access)
2. What is the use of the URL class in Java? Illustrate with a program using
URLConnection.
Answer:
The URL class in Java is used to access data on the internet. It provides methods
to access protocol, host, port, file, etc.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com");
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Explanation:
Creates a URL object.
Opens a connection using URLConnection.
Reads content from the web.
3. Write a Java program using TCP Socket programming (Client-Server
model).
Answer:
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5000);
Socket socket = server.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String message = dis.readUTF();
System.out.println("Client says: " + message);
server.close();
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
DataOutputStream dos = new
DataOutputStream(socket.getOutputStream());
dos.writeUTF("Hello Server!");
socket.close();
}
}
Explanation:
Server waits on port 5000.
Client connects and sends a message.
Server receives and displays the message.
4. Explain DatagramSocket with a program.
Answer:
DatagramSocket is used for UDP communication (no connection needed).
Sender.java
import java.net.*;
public class Sender {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String msg = "Hello via UDP!";
InetAddress ip = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.length(),
ip, 3000);
ds.send(dp);
ds.close();
}
}
Receiver.java
import java.net.*;
public class Receiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buffer = new byte[1024];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String msg = new String(dp.getData(), 0, dp.getLength());
System.out.println("Received: " + msg);
ds.close();
}
}
5. What are Java Beans? What is BDK?
Answer:
Java Beans are reusable software components.
They follow conventions:
o Must be serializable.
o Have a public no-arg constructor.
o Use getters/setters for properties.
BDK (Bean Development Kit) is a tool to:
Develop and test beans.
Visualize JavaBeans interactions.
6. Explain JAR files and their usage.
Answer:
JAR (Java ARchive) is a package file format used to bundle Java classes and
metadata.
Benefits:
Easy deployment.
Compression.
Digital signing.
Creating a JAR:
jar cvf MyApp.jar *.class
Running a JAR:
java -jar MyApp.jar
7. Explain the life cycle of a servlet with diagram.
Answer:
Servlet Life Cycle Methods:
1. init() – Called once during initialization.
2. service() – Called for each request.
3. destroy() – Called before servlet is removed.
┌──────────────┐
│ Loading │
└──────┬───────┘
↓
┌────────┐
│ init() │
└────┬───┘
↓
┌──────────────┐
│ service() │ <--- Called repeatedly for requests
└────┬─────────┘
↓
┌───────┐
│destroy│
└───────┘
8. Write a simple servlet program using HttpServlet.
Answer:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, this is a Servlet!</h1>");
}
}
Deployment:
Compile and place the .class file in WEB-INF/classes
Map in web.xml
9. Explain JDBC connectivity with a program.
Answer:
JDBC (Java Database Connectivity) enables Java programs to access relational
databases.
Steps:
1. Load Driver
2. Establish Connection
3. Create Statement
4. Execute Query
5. Close Connection
Example:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load driver
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}