1. Explain the Important Features of Java

Features of Java (Java Buzzwords)

1. Simple
  • Java is easy to learn and understand
  • Syntax is similar to C++
  • Eliminates complex features like pointers and operator overloading
  • Makes programs easier to write and maintain

2. Object-Oriented
  • Based on OOP principles: encapsulation, inheritance, polymorphism, abstraction
  • Everything is treated as an object
  • Improves code reusability and modularity

3. Platform Independent
  • Follows Write Once, Run Anywhere (WORA)
  • Code is compiled into bytecode
  • Runs on any system with JVM without modification

4. Portable
  • Programs can be executed on different platforms
  • Fixed size of data types ensures portability
  • Bytecode is platform-independent

5. Secure
  • No use of pointers prevents unauthorized access
  • Bytecode verifier checks code safety
  • Class loader and security manager enhance security
  • Provides secure execution environment

6. Robust
  • Strong memory management
  • Automatic garbage collection
  • Exception handling mechanism
  • Reduces runtime errors and crashes

7. Architecture Neutral
  • Not dependent on any specific hardware architecture
  • Bytecode can run on any system with JVM
  • Ensures cross-platform compatibility

8. Interpreted
  • Java bytecode is interpreted by JVM
  • Enables platform independence
  • Supports flexible execution and debugging

9. High Performance
  • Uses Just-In-Time (JIT) compiler
  • Converts bytecode into native machine code
  • Improves execution speed

10. Multithreaded
  • Supports execution of multiple threads simultaneously
  • Improves CPU utilization
  • Useful in real-time applications

11. Distributed
  • Supports network-based applications
  • Provides APIs like RMI, networking packages
  • Enables communication between systems

12. Dynamic
  • Supports dynamic class loading at runtime
  • Allows modification and extension of programs
  • Makes Java flexible and adaptable

Key Points for Exam
  • Java has 12 main features (buzzwords)
  • Platform independent and secure are most important
  • Supports OOP and multithreading
  • Widely used due to robustness and portability
2. Discuss about Scanner Class with an Example Program

Scanner Class
  • Scanner class is used to take input from the user at runtime
  • It belongs to the java.util package
  • It can read different types of data like int, float, double, String, etc.
  • It uses input streams such as System.in

Working of Scanner Class

Creating Scanner Object
import java.util.Scanner; Scanner sc = new Scanner(System.in);

Common Methods of Scanner Class
MethodDescription
nextInt()Reads integer value
nextFloat()Reads float value
nextDouble()Reads double value
next()Reads single word
nextLine()Reads entire line
nextBoolean()Reads boolean value

Example Program
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name:"); String name = sc.nextLine(); System.out.println("Enter your age:"); int age = sc.nextInt(); System.out.println("Name: " + name); System.out.println("Age: " + age); sc.close(); } }

Explanation of Program
Screenshot-2026-03-29-09-33-33-27-96b26121e545231a3c569311a54cda96
  • Scanner sc = new Scanner(System.in); → creates Scanner object
  • nextLine() → reads string input
  • nextInt() → reads integer input
  • Input is taken from keyboard and displayed

Advantages of Scanner Class
  • Easy to use for input handling
  • Supports multiple data types
  • More flexible than older methods (like BufferedReader)

Key Points for Exam
  • Scanner belongs to java.util
  • Used for user input
  • Methods like nextInt(), nextLine() commonly used
  • Must import package before use
3. Explain in detail on Inheritance and its types with program
Screenshot-2026-03-29-09-50-00-97-96b26121e545231a3c569311a54cda96
Inheritance in Java
Screenshot-2026-03-29-09-49-45-64-96b26121e545231a3c569311a54cda96
  • Inheritance is an OOP concept where a subclass acquires properties and methods of a superclass
  • Implemented using the extends keyword
  • Promotes code reusability and establishes hierarchical relationships

Basic Structure of Inheritance
class Superclass { // properties and methods } class Subclass extends Superclass { // additional features }

Types of Inheritance in Java

1. Single Inheritance

One subclass inherits from one superclass

class Animal { void eat() { System.out.println("Animal eats food"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Test { public static void main(String[] args) { Dog d = new Dog(); d.eat(); // inherited method d.bark(); } }

2. Multilevel Inheritance

A class inherits from another class, forming a chain

class Animal { void eat() { System.out.println("Animal eats"); } } class Mammal extends Animal { void breathe() { System.out.println("Mammal breathes"); } } class Dog extends Mammal { void bark() { System.out.println("Dog barks"); } } public class Test { public static void main(String[] args) { Dog d = new Dog(); d.eat(); d.breathe(); d.bark(); } }

3. Hierarchical Inheritance

Multiple subclasses inherit from one superclass

class Animal { void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } class Cat extends Animal { void meow() { System.out.println("Cat meows"); } } public class Test { public static void main(String[] args) { Dog d = new Dog(); Cat c = new Cat(); d.eat(); c.eat(); } }

4. Multiple Inheritance (Using Interfaces)

Java does not support multiple inheritance using classes

Achieved using interfaces

interface A { void showA(); } interface B { void showB(); } class C implements A, B { public void showA() { System.out.println("Interface A"); } public void showB() { System.out.println("Interface B"); } }

Advantages of Inheritance
  • Code reusability
  • Reduces redundancy
  • Improves readability and maintainability
  • Supports polymorphism

Key Points for Exam
  • Inheritance uses extends keyword
  • Types: Single, Multilevel, Hierarchical, Multiple (via interfaces)
  • Enables reuse and hierarchy
  • Important concept in OOP
4. Differences between Method Overloading and Method Overriding with Examples
Screenshot-2026-03-29-09-56-54-49-96b26121e545231a3c569311a54cda96
Definitions

Method Overloading: Multiple methods with the same name but different parameter lists in the same class (compile-time polymorphism).

Method Overriding: Subclass provides a specific implementation of a method already defined in its superclass (runtime polymorphism).


Comparison Diagram

Difference Table
Feature Method Overloading Method Overriding
Definition Same method name, different parameters Same method name and parameters
Location Same class Parent and child class
Polymorphism Compile-time Runtime
Parameters Must differ (number/type/order) Must be same
Return Type Can differ Must be same or covariant
Binding Early binding Late binding
Inheritance Not required Required
Execution Decided at compile time Decided at runtime

Method Overloading Example
class Sum { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } }

Method Overriding Example
class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } }

Explanation
  • In overloading, methods differ in parameters but exist in the same class
  • In overriding, subclass changes behavior of superclass method
  • Overloading improves readability, overriding enables runtime behavior change

Key Points for Exam
  • Overloading → same class, different parameters, compile-time
  • Overriding → inheritance, same signature, runtime
  • Both support polymorphism in Java
5. Explain the Concept of Java Swing in Java

Java Swing
  • Java Swing is a GUI toolkit used to create window-based desktop applications
  • It is part of the javax.swing package
  • Built on top of AWT but provides more advanced and flexible components

Swing Architecture

Features of Java Swing
  • Platform independent (runs on any system with JVM)
  • Lightweight components (not dependent on OS)
  • Rich set of GUI components
  • Highly customizable (font, color, size)
  • Event-driven programming
  • Follows MVC architecture

Components of Swing
Screenshot-2026-03-29-10-03-32-15-96b26121e545231a3c569311a54cda96
1. Top-Level Containers
  • JFrame → main window
  • JDialog → dialog box
  • JApplet → applet container

2. Intermediate Containers
  • JPanel → used to group components
  • JScrollPane → provides scrolling

3. Basic Components
  • JButton → clickable button
  • JLabel → display text/image
  • JTextField → single-line input
  • JTextArea → multi-line input

Layout Managers
  • FlowLayout → arranges in a row
  • BorderLayout → North, South, East, West, Center
  • GridLayout → grid structure
  • BoxLayout → row/column arrangement

Event Handling in Swing
  • Used to handle user actions like button clicks
  • Uses listeners (e.g., ActionListener)
  • Event → Listener → Response

Example Program
import javax.swing.*; public class SwingExample { public static void main(String[] args) { JFrame frame = new JFrame("Swing Example"); JButton button = new JButton("Click Me"); button.setBounds(150, 120, 100, 30); frame.add(button); frame.setSize(400, 300); frame.setLayout(null); frame.setVisible(true); } }

Applications of Java Swing
  • Desktop applications
  • Banking systems
  • Text editors
  • Management systems
  • GUI-based tools

Key Points for Exam
  • Swing is part of javax.swing
  • Used for GUI development
  • Provides rich and flexible components
  • Event-driven and platform independent
6. Explain Threads in Java. Write about two ways of creating thread with suitable program

Thread in Java
  • A thread is a lightweight process that allows multiple tasks to run concurrently within a program
  • Used to achieve multitasking and improve performance
  • Threads share the same memory space

Thread Life Cycle (Overview)
Screenshot-2026-03-29-10-13-13-47-96b26121e545231a3c569311a54cda96
Advantages of Threads
  • Improves CPU utilization
  • Enables multitasking
  • Faster program execution
  • Efficient resource sharing

Two Ways to Create Threads in Java

1. By Extending Thread Class
Steps
  • Create a class that extends Thread
  • Override run() method
  • Call start() method
Program

class MyThread extends Thread 
{
    public void run() 
    {
        System.out.println("Thread using Thread class");
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        MyThread t1 = new MyThread(); // New state
        t1.start(); // Runnable → Running
    }
}

2. By Implementing Runnable Interface
Steps
  • Create a class that implements Runnable
  • Override run() method
  • Pass object to Thread and call start()
Program

class MyRunnable implements Runnable 
{
    public void run() 
    {
        System.out.println("Thread using Runnable interface");
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        MyRunnable obj = new MyRunnable();
        Thread t2 = new Thread(obj);
        t2.start();
    }
}

Difference Between Two Methods
Feature Thread Class Runnable Interface
Inheritance Extends Thread Implements Runnable
Flexibility Less flexible (cannot extend another class) More flexible
Code Reuse Limited Better reuse
Recommended Less preferred More preferred

Important Methods of Thread
  • start() → starts thread execution
  • run() → contains logic
  • sleep() → pauses execution
  • join() → waits for another thread
  • yield() → gives chance to other threads

Key Points for Exam
  • Thread enables multitasking
  • Two ways: Thread class & Runnable interface
  • start() method is used to begin execution
  • Runnable method is preferred in real applications
7. Define Package in Java. Explain the procedure to create and access it with example

Definition of Package

A package in Java is a collection of related classes and interfaces grouped together to organize code and avoid naming conflicts.


Structure of Package
Screenshot-2026-03-29-10-27-52-16-96b26121e545231a3c569311a54cda96
Need for Packages
  • Organizes large programs into logical groups
  • Avoids naming conflicts
  • Provides access protection
  • Improves code reusability and maintainability

Procedure to Create a Package
Screenshot-2026-03-29-10-27-39-64-96b26121e545231a3c569311a54cda96
Step 1: Declare Package

Use package keyword at the beginning of the program


package mypackage;

Step 2: Define Class inside Package

package mypackage;

public class Test 
{
    public void display() 
    {
        System.out.println("Package created");
    }
}

Step 3: Compile the Program

Use command:


javac -d . Test.java

This creates a folder named mypackage


Accessing a Package
1. Using import statement

import mypackage.Test;

public class Demo 
{
    public static void main(String[] args) 
    {
        Test t = new Test();
        t.display();
    }
}

2. Using fully qualified name

public class Demo 
{
    public static void main(String[] args) 
    {
        mypackage.Test t = new mypackage.Test();
        t.display();
    }
}

Types of Packages
  • Built-in packages → Provided by Java (e.g., java.lang, java.util)
  • User-defined packages → Created by programmer

Advantages of Packages
  • Prevents naming conflicts
  • Provides access control using modifiers
  • Improves readability and structure
  • Supports modular programming

Key Points for Exam
  • Package = group of related classes
  • Use package keyword to create
  • Use import to access
  • Two types: Built-in and User-defined
8. Explain the Different Control Statements in Java with Suitable Examples

Control Statements in Java
Screenshot-2026-03-29-10-32-27-12-96b26121e545231a3c569311a54cda96

Control statements are used to control the flow of execution of a program based on conditions, loops, and branching.


Classification of Control Statements
  • 1. Conditional (Decision-Making) Statements
  • 2. Looping (Iterative) Statements
  • 3. Jumping (Branching) Statements

1. Conditional Statements
a) if Statement

Executes block only if condition is true


int x = 10;

if(x > 0)
{
    System.out.println("Positive number");
}

b) if-else Statement

Executes one block if condition is true, otherwise another


int x = -5;

if(x > 0)
{
    System.out.println("Positive");
}
else
{
    System.out.println("Negative");
}

c) if-else-if Ladder

Used to check multiple conditions


int marks = 75;

if(marks >= 90)
{
    System.out.println("A");
}
else if(marks >= 75)
{
    System.out.println("B");
}
else
{
    System.out.println("C");
}

d) switch Statement

Used to select one case from many options


int day = 2;

switch(day)
{
    case 1:
        System.out.println("Monday");
        break;

    case 2:
        System.out.println("Tuesday");
        break;

    default:
        System.out.println("Invalid");
}

2. Looping Statements
Looping Concept

Used to execute a block of code repeatedly until a condition is satisfied


a) while Loop (Entry Controlled)

Condition is checked before execution


int i = 1;

while(i <= 5)
{
    System.out.println(i);
    i++;
}

b) do-while Loop (Exit Controlled)

Executes at least once


int i = 1;

do
{
    System.out.println(i);
    i++;
}
while(i <= 5);

c) for Loop

Used when number of iterations is known


for(int i = 1; i <= 5; i++)
{
    System.out.println(i);
}

d) Enhanced for Loop

Used for arrays and collections


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

for(int x : arr)
{
    System.out.println(x);
}

3. Jumping (Branching) Statements
a) break Statement

Terminates loop or switch immediately


for(int i = 1; i <= 5; i++)
{
    if(i == 3)
    {
        break;
    }
    System.out.println(i);
}

b) continue Statement

Skips current iteration and continues loop


for(int i = 1; i <= 5; i++)
{
    if(i == 3)
    {
        continue;
    }
    System.out.println(i);
}

c) return Statement

Exits from method and optionally returns value


int add(int a, int b)
{
    return a + b;
}

Overall Flow Representation

Start → Condition → Execution → Update → Repeat → End

Controls decision-making, looping, and branching


Advantages of Control Statements
  • Enables decision making
  • Reduces code repetition
  • Improves program efficiency
  • Makes programs dynamic and flexible

Key Points for Exam
  • Three types: Conditional, Looping, Jumping
  • if, switch → decision making
  • for, while, do-while → looping
  • break, continue, return → control flow
  • Essential for program logic and execution control
9. Explain in detail on Thread Life Cycle with diagram. Illustrate thread creation with program

Thread Life Cycle in Java

Thread life cycle represents the various states a thread goes through from creation to termination during execution.


Thread Life Cycle Diagram

New → Runnable → Running → Waiting/Blocked → Runnable → Running → Terminated

States of Thread Life Cycle
1. New (Born State)
  • Thread is created using new Thread()
  • Not yet started
  • No CPU allocation

2. Runnable State
  • Thread is ready for execution
  • After calling start() method
  • Waiting for CPU scheduling

3. Running State
  • Thread is actively executing
  • CPU is assigned by scheduler
  • Executes run() method

4. Blocked / Waiting State
  • Thread is temporarily inactive
  • Waiting for resource or another thread
  • Methods causing this state:
  • sleep()
  • wait()
  • join()

5. Terminated (Dead State)
  • Thread completes execution
  • Cannot be restarted again

State Transitions
  • New → Runnable → by calling start()
  • Runnable → Running → CPU scheduler selects thread
  • Running → Waiting/Blockedsleep(), wait()
  • Waiting → Runnable → after completion of waiting
  • Running → Terminated → execution finishes

Thread Creation in Java
Method 1: Extending Thread Class

class MyThread extends Thread 
{
    public void run() 
    {
        System.out.println("Thread using Thread class");
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        MyThread t1 = new MyThread(); // New state
        t1.start(); // Runnable → Running
    }
}

Method 2: Implementing Runnable Interface

class MyRunnable implements Runnable 
{
    public void run() 
    {
        System.out.println("Thread using Runnable interface");
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        MyRunnable obj = new MyRunnable();
        Thread t2 = new Thread(obj);
        t2.start();
    }
}

Important Thread Methods
  • start() → starts execution
  • run() → contains logic
  • sleep() → pauses thread
  • join() → waits for another thread
  • yield() → gives chance to other threads

Key Points for Exam
  • Thread has 5 states: New, Runnable, Running, Waiting, Terminated
  • start() begins execution
  • Threads improve multitasking
  • Two ways: Thread class & Runnable interface
10. Explain about String Class and String Functions
Screenshot-2026-03-29-10-38-23-66-96b26121e545231a3c569311a54cda96
String Class in Java
  • String is a class in java.lang used to represent a sequence of characters
  • Strings are immutable, i.e., once created, they cannot be changed
  • Stored in a special memory area called String pool

Internal Representation of String

Creation of String
1. Using String Literal

String s1 = "Java";
  • Stored in String pool
  • Memory efficient

2. Using new Keyword

String s2 = new String("Programming");
  • Stored in heap memory
  • Creates new object

Properties of String
  • Immutable in nature
  • Thread-safe
  • Provides many built-in methods
  • Efficient memory management using String pool

Common String Functions (Methods)
1. length()

Returns length of string


s.length();

2. charAt()

Returns character at specific index


s.charAt(2);

3. substring()

Extracts part of string


s.substring(1,4);

4. equals()

Compares two strings


s1.equals(s2);

5. equalsIgnoreCase()

Compares strings ignoring case


s1.equalsIgnoreCase(s2);

6. concat()

Joins two strings


s1.concat(s2);

7. toUpperCase() / toLowerCase()

Converts case


s.toUpperCase();

8. indexOf()

Finds position of character


s.indexOf('a');

9. replace()

Replaces characters


s.replace('a','b');

10. trim()

Removes leading and trailing spaces


s.trim();

Example Program

class StringDemo 
{
    public static void main(String[] args) 
    {
        String s = "Java Programming";

        System.out.println("Length: " + s.length());
        System.out.println("Uppercase: " + s.toUpperCase());
        System.out.println("Substring: " + s.substring(0,4));
        System.out.println("Character: " + s.charAt(2));
    }
}

String vs StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder
Nature Immutable Mutable Mutable
Thread Safety Yes Yes No
Performance Slow Moderate Fast

Key Points for Exam
  • String belongs to java.lang
  • Immutable and stored in String pool
  • Provides many built-in functions
  • StringBuffer & StringBuilder used for modification
11. Explain in detail on Operators and its types with example programs
Screenshot-2026-03-29-10-40-40-59-96b26121e545231a3c569311a54cda96
Operators in Java

Operators are special symbols used to perform operations on variables and values such as arithmetic, comparison, and logical operations.


Classification of Operators

1. Arithmetic Operators

Used for mathematical calculations

OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
Example Program

class ArithmeticDemo 
{
    public static void main(String[] args) 
    {
        int a = 10, b = 5;

        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println(a / b);
        System.out.println(a % b);
    }
}

2. Relational Operators

Used to compare two values (returns boolean result)

OperatorMeaning
==Equal to
!=Not equal
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal
Example Program

class RelationalDemo 
{
    public static void main(String[] args) 
    {
        int a = 10, b = 5;

        System.out.println(a > b);
        System.out.println(a == b);
    }
}

3. Logical Operators

Used to combine conditions

OperatorMeaning
&&Logical AND
!Logical NOT
Example Program

class LogicalDemo 
{
    public static void main(String[] args) 
    {
        int a = 10;

        System.out.println(a > 0 && a < 20);
        System.out.println(!(a > 5));
    }
}

4. Assignment Operators

Used to assign values

OperatorExample
=a = 10
+=a += 5
-=a -= 2
*=a *= 3
/=a /= 2
Example Program

class AssignmentDemo 
{
    public static void main(String[] args) 
    {
        int a = 10;

        a += 5;

        System.out.println(a);
    }
}

5. Unary Operators

Operate on a single operand

OperatorOperation
++Increment
--Decrement
!Logical NOT
Example Program

class UnaryDemo 
{
    public static void main(String[] args) 
    {
        int a = 5;

        a++;

        System.out.println(a);
    }
}

6. Bitwise Operators

Perform operations on bits

OperatorMeaning
&AND
|OR
^XOR
~Complement
Example Program

class BitwiseDemo 
{
    public static void main(String[] args) 
    {
        int a = 5, b = 3;

        System.out.println(a & b);
        System.out.println(a | b);
    }
}

7. Ternary Operator

Short form of if-else


class TernaryDemo 
{
    public static void main(String[] args) 
    {
        int a = 10, b = 20;

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

        System.out.println(max);
    }
}

8. Shift Operators

Used to shift bits left or right

OperatorMeaning
<<Left shift
>>Right shift
Example Program

class ShiftDemo 
{
    public static void main(String[] args) 
    {
        int a = 4;

        System.out.println(a << 1);
    }
}

Key Points for Exam
  • Operators perform operations on data
  • Types: Arithmetic, Relational, Logical, Assignment, Unary, Bitwise, Ternary, Shift
  • Used for calculations and decision-making
  • Essential for program logic
12. Exception Handling in Java – Detailed Explanation with Output

Exception Handling

Exception handling is a mechanism used to handle runtime errors and continue program execution normally without crashing.


Exception Handling Flow
Screenshot-2026-03-29-10-43-53-03-96b26121e545231a3c569311a54cda96
Components of Exception Handling
1. try Block
  • Contains code that may cause exception
  • Must be followed by catch or finally
2. catch Block
  • Handles specific exception
  • Executes only when exception occurs
3. finally Block
  • Executes always (exception occurs or not)
  • Used for cleanup (closing files, resources)

Working Process (Step-by-Step)
  • Program executes statements inside try block
  • If no exception → skip catch, execute finally
  • If exception occurs → control jumps to matching catch block
  • Exception is handled → finally block executes
  • Program continues normally

Example Program with Output

class ExceptionDemo 
{
    public static void main(String[] args) 
    {
        try 
        {
            System.out.println("Step 1: Before exception");

            int a = 10 / 0;

            System.out.println("Step 2: After exception");
        } 
        catch(ArithmeticException e) 
        {
            System.out.println("Exception caught: Division by zero");
        } 
        finally 
        {
            System.out.println("Finally block executed");
        }

        System.out.println("Program continues normally");
    }
}
Output
Step 1: Before exception Exception caught: Division by zero Finally block executed Program continues normally

Explanation
  • "Step 1" is printed before exception
  • Exception occurs at 10/0, so "Step 2" is skipped
  • Control moves to catch block → prints error message
  • finally block executes always
  • Program continues after exception handling

Example without Exception

class NoException 
{
    public static void main(String[] args) 
    {
        try 
        {
            int a = 10 / 2;

            System.out.println("Result: " + a);
        } 
        catch(ArithmeticException e) 
        {
            System.out.println("Error");
        } 
        finally 
        {
            System.out.println("Finally executed");
        }
    }
}
Output
Result: 5 Finally executed

Multiple Catch Example with Output

class MultiCatchDemo 
{
    public static void main(String[] args) 
    {
        try 
        {
            int arr[] = new int[3];

            arr[5] = 10;
        } 
        catch(ArrayIndexOutOfBoundsException e) 
        {
            System.out.println("Array index error");
        } 
        catch(Exception e) 
        {
            System.out.println("General exception");
        }
    }
}
Output
Array index error

Important Points
  • try block → risky code
  • catch block → handles exception
  • finally → always executes
  • Multiple catch → handles different exceptions
  • Order: specific → general

Advantages
  • Prevents program crash
  • Maintains smooth execution
  • Improves reliability
  • Helps debugging and error handling

Key Points for Exam
  • Exception handling = try + catch + finally
  • Program does not terminate abruptly
  • finally block always executes
  • Output-based questions are common ✔
13. Explain the Components of MVC Architecture with a Neat Diagram

MVC Architecture

MVC (Model–View–Controller) is a design pattern that separates an application into three components: Model, View, and Controller for better organization and maintainability.


MVC Architecture Diagram
Model → Controller → View

View → Controller → Model

(Model and View do not communicate directly)

Components of MVC Architecture
Screenshot-2026-03-29-10-47-09-91-96b26121e545231a3c569311a54cda96
1. Model
  • Represents data and business logic of the application
  • Responsible for data processing and database operations
  • Independent of user interface
  • Sends updated data to Controller/View

Example:
Student data, database records


2. View
  • Represents the user interface (UI)
  • Displays data to the user
  • Receives input from user (keyboard, mouse)
  • Does not contain business logic

Example:
Forms, buttons, text fields (Swing GUI)


3. Controller
  • Acts as an intermediary between Model and View
  • Receives user input from View
  • Processes input and updates Model
  • Updates View based on Model changes

Working of MVC Architecture
  • User interacts with View
  • View sends input to Controller
  • Controller processes logic and updates Model
  • Model updates data
  • Controller updates View
  • View displays updated output

Responsibilities of Each Component
Component Responsibility
Model Data handling and business logic
View User interface and display
Controller Controls flow and communication

Advantages of MVC
  • Separation of concerns
  • Easy maintenance and scalability
  • Improved code reusability
  • Independent development of components

Applications of MVC
  • Web applications (Spring MVC)
  • Desktop applications (Java Swing)
  • Mobile applications
  • Enterprise systems

Example Structure (Concept)

// Model
class Student 
{
    String name;
}

// View
interface StudentView 
{
    void display(String name);
}

// Controller
class StudentController 
{
    Student model;
    StudentView view;

    StudentController(Student m, StudentView v) 
    {
        model = m;
        view = v;
    }

    void updateView() 
    {
        view.display(model.name);
    }
}

Key Points for Exam
  • MVC = Model + View + Controller
  • Controller connects Model and View
  • Improves modularity and testing
  • Widely used in GUI and web applications
14. Elaborate the Flow Control Statements

a) Conditional Statements with Program
Conditional Statements
  • Used to make decisions based on conditions
  • Executes different blocks of code depending on true/false conditions

Types of Conditional Statements

1. if Statement
Screenshot-2026-03-29-10-50-01-83-96b26121e545231a3c569311a54cda96

Executes block only when condition is true


class IfExample 
{
    public static void main(String[] args) 
    {
        int x = 10;

        if(x > 0)
        {
            System.out.println("Positive number");
        }
    }
}

2. if-else Statement

Executes one block if condition is true, otherwise another


class IfElseExample 
{
    public static void main(String[] args) 
    {
        int x = -5;

        if(x > 0)
        {
            System.out.println("Positive");
        } 
        else 
        {
            System.out.println("Negative");
        }
    }
}

3. if-else-if Ladder

Used to check multiple conditions


class LadderExample 
{
    public static void main(String[] args) 
    {
        int marks = 75;

        if(marks >= 90)
        {
            System.out.println("Grade A");
        }
        else if(marks >= 75)
        {
            System.out.println("Grade B");
        }
        else
        {
            System.out.println("Grade C");
        }
    }
}

4. switch Statement

Used to select one case from many options


class SwitchExample 
{
    public static void main(String[] args) 
    {
        int day = 2;

        switch(day)
        {
            case 1:
                System.out.println("Monday");
                break;

            case 2:
                System.out.println("Tuesday");
                break;

            default:
                System.out.println("Invalid day");
        }
    }
}

b) Looping Statements with Program
Looping Statements
  • Used to execute a block of code repeatedly until a condition becomes false

Types of Looping Statements
Screenshot-2026-03-29-10-49-25-62-96b26121e545231a3c569311a54cda96
1. while Loop (Entry Controlled)

Condition checked before execution


class WhileExample 
{
    public static void main(String[] args) 
    {
        int i = 1;

        while(i <= 5)
        {
            System.out.println(i);
            i++;
        }
    }
}

2. do-while Loop (Exit Controlled)

Executes at least once


class DoWhileExample 
{
    public static void main(String[] args) 
    {
        int i = 1;

        do
        {
            System.out.println(i);
            i++;
        } 
        while(i <= 5);
    }
}

3. for Loop

Used when number of iterations is known


class ForExample 
{
    public static void main(String[] args) 
    {
        for(int i = 1; i <= 5; i++)
        {
            System.out.println(i);
        }
    }
}

4. Enhanced for Loop

Used for arrays and collections


class EnhancedFor 
{
    public static void main(String[] args) 
    {
        int arr[] = {1,2,3};

        for(int x : arr)
        {
            System.out.println(x);
        }
    }
}

Key Points for Exam
  • Conditional → if, if-else, switch
  • Looping → while, do-while, for, enhanced for
  • Used for decision-making and repetition
  • Essential for program control flow
15. Explain any 2 Pillars of Object-Oriented Programming (OOP) in Java with Examples

1. Encapsulation
Concept
  • Encapsulation is the process of wrapping data (variables) and methods into a single unit (class)
  • Data is hidden using access modifiers and accessed through getter and setter methods

Encapsulation Diagram
Screenshot-2026-03-29-11-00-17-87-96b26121e545231a3c569311a54cda96
Private Data → Getter/Setter → Controlled Access

Key Features
  • Uses private access modifier for variables
  • Provides public methods to access data
  • Ensures data security and control

Example Program

class Student 
{
    private String name;

    public void setName(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        Student s = new Student();

        s.setName("John");

        System.out.println(s.getName());
    }
}

Advantages
  • Data hiding
  • Improved security
  • Better control over data
  • Easy maintenance

2. Inheritance
Concept
  • Inheritance allows one class (subclass) to acquire properties and methods of another class (superclass)
  • Implemented using extends keyword

Inheritance Diagram
Superclass → Subclass (Animal → Dog)

Key Features
  • Code reusability
  • Supports hierarchical classification
  • Reduces redundancy
  • Enables method overriding

Example Program

class Animal 
{
    void eat()
    {
        System.out.println("Animal eats");
    }
}

class Dog extends Animal 
{
    void bark()
    {
        System.out.println("Dog barks");
    }
}

public class Test 
{
    public static void main(String[] args) 
    {
        Dog d = new Dog();

        d.eat();

        d.bark();
    }
}

Advantages
  • Code reuse
  • Improves readability
  • Supports polymorphism
  • Easy extension of existing code

Key Points for Exam
  • Encapsulation → data hiding using getters/setters
  • Inheritance → reuse using extends
  • Both are core OOP principles
  • Helps build modular and secure applications
17. Describe in detail on Swing Components. Illustrate Banking Application using Swing Components
Screenshot-2026-03-29-11-02-47-15-96b26121e545231a3c569311a54cda96
Swing Components in Java
Definition
  • Swing components are GUI elements used to build desktop applications
  • Part of javax.swing package
  • Provide rich and flexible UI elements

Hierarchy of Swing Components
Top-Level → Intermediate → Basic Components

Types of Swing Components

1. Top-Level Containers

Main containers that hold all components

ComponentDescription
JFrameMain window of application
JDialogDialog box window
JAppletApplet container

2. Intermediate Containers

Used to organize components

ComponentDescription
JPanelGroups components
JScrollPaneAdds scrolling feature
JSplitPaneDivides window

3. Basic Components
ComponentDescription
JLabelDisplays text or image
JButtonClickable button
JTextFieldSingle-line text input
JTextAreaMulti-line text input
JCheckBoxMultiple selection
JRadioButtonSingle selection
JComboBoxDropdown list
JTableDisplays data in tabular form

Layout Managers

Controls arrangement of components

LayoutDescription
FlowLayoutLeft to right
BorderLayoutNorth, South, East, West, Center
GridLayoutGrid format
BoxLayoutRow/column arrangement

Event Handling
  • Handles user actions
  • Uses listeners (e.g., ActionListener)
  • Event → Listener → Action

Banking Application using Swing Components
Concept
  • A simple banking UI allows user to:
  • Enter account details
  • Deposit or withdraw money
  • Display balance
Screenshot-2026-03-29-11-03-09-69-96b26121e545231a3c569311a54cda96
Banking Application UI Structure
Label → TextField → Buttons → Result Display

Example Program

import javax.swing.*;
import java.awt.event.*;

public class BankApp 
{
    public static void main(String[] args) 
    {
        JFrame frame = new JFrame("Banking Application");

        JLabel l1 = new JLabel("Amount:");
        l1.setBounds(50, 50, 100, 30);

        JTextField tf = new JTextField();
        tf.setBounds(150, 50, 150, 30);

        JButton deposit = new JButton("Deposit");
        deposit.setBounds(50, 100, 100, 30);

        JButton withdraw = new JButton("Withdraw");
        withdraw.setBounds(200, 100, 100, 30);

        JLabel result = new JLabel("Balance: 0");
        result.setBounds(50, 150, 200, 30);

        final int[] balance = {0};

        deposit.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                int amt = Integer.parseInt(tf.getText());
                balance[0] += amt;
                result.setText("Balance: " + balance[0]);
            }
        });

        withdraw.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                int amt = Integer.parseInt(tf.getText());
                balance[0] -= amt;
                result.setText("Balance: " + balance[0]);
            }
        });

        frame.add(l1);
        frame.add(tf);
        frame.add(deposit);
        frame.add(withdraw);
        frame.add(result);

        frame.setSize(400, 300);
        frame.setLayout(null);
        frame.setVisible(true);
    }
}

Explanation
  • JFrame → main window
  • JLabel → displays text
  • JTextField → input amount
  • JButton → deposit/withdraw actions
  • ActionListener → handles button clicks
  • Balance updates dynamically

Advantages of Swing Components
  • Platform independent
  • Rich GUI controls
  • Flexible and customizable
  • Supports event-driven programming

Key Points for Exam
  • Swing components belong to javax.swing
  • Three categories: Top-level, Intermediate, Basic
  • Layout managers control UI
  • Used to build real-time applications like banking systems
18. Discuss about Reading from File, Writing to File and Working with Input and Output Streams
Screenshot-2026-03-29-11-06-32-74-96b26121e545231a3c569311a54cda96
Input and Output (I/O) Streams in Java
Concept
  • Streams are used to perform input and output operations in Java
  • A stream is a sequence of data flowing between source and destination
  • Java provides I/O classes in java.io package

I/O Stream Flow
Source → Input Stream → Processing → Output Stream → Destination

Types of Streams
1. Input Stream
  • Used to read data from a source (file, keyboard)
  • Example: FileInputStream, BufferedReader
2. Output Stream
  • Used to write data to a destination (file, console)
  • Example: FileOutputStream, PrintWriter

Byte Streams vs Character Streams
Type Description Classes
Byte Stream Handles binary data FileInputStream, FileOutputStream
Character Stream Handles text data FileReader, FileWriter

Reading from File
Using FileInputStream (Byte Stream)

import java.io.*;

class ReadFile 
{
    public static void main(String[] args) throws Exception 
    {
        FileInputStream fis = new FileInputStream("test.txt");

        int i;

        while((i = fis.read()) != -1)
        {
            System.out.print((char)i);
        }

        fis.close();
    }
}

Using FileReader (Character Stream)

import java.io.*;

class ReadFileChar 
{
    public static void main(String[] args) throws Exception 
    {
        FileReader fr = new FileReader("test.txt");

        int i;

        while((i = fr.read()) != -1)
        {
            System.out.print((char)i);
        }

        fr.close();
    }
}

Writing to File
Using FileOutputStream

import java.io.*;

class WriteFile 
{
    public static void main(String[] args) throws Exception 
    {
        FileOutputStream fos = new FileOutputStream("test.txt");

        String data = "Hello Java";

        fos.write(data.getBytes());

        fos.close();
    }
}

Using FileWriter

import java.io.*;

class WriteFileChar 
{
    public static void main(String[] args) throws Exception 
    {
        FileWriter fw = new FileWriter("test.txt");

        fw.write("Hello World");

        fw.close();
    }
}

Working of I/O Streams
Steps
  • Import java.io package
  • Create stream object
  • Open file
  • Read or write data
  • Close stream

Buffered Streams (Efficient I/O)

Improves performance by reducing I/O operations


BufferedReader br = new BufferedReader(new FileReader("test.txt"));

Example (Read and Write Combined)

import java.io.*;

class FileDemo 
{
    public static void main(String[] args) throws Exception 
    {
        FileWriter fw = new FileWriter("test.txt");

        fw.write("Java I/O Example");

        fw.close();

        FileReader fr = new FileReader("test.txt");

        int i;

        while((i = fr.read()) != -1)
        {
            System.out.print((char)i);
        }

        fr.close();
    }
}

Advantages of I/O Streams
  • Supports file handling
  • Handles both text and binary data
  • Provides efficient data processing
  • Flexible and scalable

Key Points for Exam
  • Streams = flow of data
  • Two types: Input (read), Output (write)
  • Byte stream & Character stream
  • Must close stream after use
  • Important classes: FileInputStream, FileOutputStream, FileReader, FileWriter