0% found this document useful (0 votes)
2 views36 pages

Java Pyq

This document is a solutions manual for previous year questions in Java programming, compiled for exam preparation. It covers various topics including object-oriented programming principles, Java program execution, loop statements, applet vs application, type conversion, command line arguments, event handling, file handling, and more. Each section includes theory, example programs, and explanations to aid in understanding Java concepts.

Uploaded by

chandelnimrat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

Java Pyq

This document is a solutions manual for previous year questions in Java programming, compiled for exam preparation. It covers various topics including object-oriented programming principles, Java program execution, loop statements, applet vs application, type conversion, command line arguments, event handling, file handling, and more. Each section includes theory, example programs, and explanations to aid in understanding Java concepts.

Uploaded by

chandelnimrat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Previous Year Questions


Solutions Manual
Compiled for Exam Preparation
December 12, 2025

Contents
1 Principles of Object-Oriented Programming (OOP) 5
1.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Core OOP Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.1 (1) Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.2 (2) Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.3 (3) Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.4 (4) Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.5 (5) Class and Object . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Java Program Execution Process 6


2.1 What Goes Behind the Scene When Computer Runs Java Program? . . . 6

3 Loop Statements in Java 6


3.1 Types of Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Example Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.1 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2.2 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2.3 Do-While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2.4 For-Each Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

4 Applet vs Application 7
4.1 Comparison Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.2 Example Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.2.1 Simple Applet Code . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.2.2 Simple Application Code (Console Program) . . . . . . . . . . . . 8

5 Type Conversion in Java 8


5.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5.1.1 1. Implicit Conversion (Widening Conversion) . . . . . . . . . . . 8
5.1.2 2. Explicit Conversion (Narrowing Conversion) . . . . . . . . . . 9
5.2 Complete Program Demonstrating Both Conversions . . . . . . . . . . . 9

1
CSE Department Java Programming - PYQ Solutions

6 Command Line Arguments in Java 9


6.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
6.2 Example Program Using Command Line Arguments . . . . . . . . . . . . 10

7 Swapping Numbers Without Third Variable 10


7.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7.2 Method 1: Swap Using Bitwise XOR . . . . . . . . . . . . . . . . . . . . 10
7.3 Method 2: Swap Using Multiplication & Division . . . . . . . . . . . . . 10

8 Event Handling in Java 11


8.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8.2 Program 1: ActionListener Implementation . . . . . . . . . . . . . . . . . 11
8.2.1 Explanation of Program . . . . . . . . . . . . . . . . . . . . . . . 12
8.3 Event Handling Using Anonymous Class . . . . . . . . . . . . . . . . . . 12
8.3.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.4 Program 2: Using Anonymous Class . . . . . . . . . . . . . . . . . . . . 12
8.4.1 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8.5 Final Exam-Ready Summary . . . . . . . . . . . . . . . . . . . . . . . . 13

9 File Handling in Java 13


9.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.1.1 1. FileWriter (Writing to a File) . . . . . . . . . . . . . . . . . . . 14
9.1.2 2. FileReader (Reading from a File) . . . . . . . . . . . . . . . . . 14
9.2 Program: Write to file + Read from file . . . . . . . . . . . . . . . . . . . 14

10 String Immutability in Java 14


10.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.2 Why Strings Are Immutable? . . . . . . . . . . . . . . . . . . . . . . . . 15
10.3 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

11 Recursion vs Iteration 15
11.1 Comparison Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
11.2 Example: Factorial using Recursion & Iteration . . . . . . . . . . . . . . 16
11.2.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
11.2.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

12 Constructor in Derived Class 16


12.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.2 Program Demonstrating Constructor in Derived Class . . . . . . . . . . . 16

13 Objects and Variables as Parameters 17


13.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
13.2 Program Demonstrating Object as Parameter . . . . . . . . . . . . . . . 17

14 Exception Hierarchy in Java 17


14.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
14.1.1 1. Throwable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
14.1.2 2. Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
14.2 try, catch, finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
14.2.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Page 2
CSE Department Java Programming - PYQ Solutions

14.3 Example: try–catch–finally . . . . . . . . . . . . . . . . . . . . . . . . . . 18

15 Method Overloading & Method Overriding 19


15.1 A. Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
15.2 B. Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
15.3 Difference Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
15.4 Roles in Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
15.5 Implications for Maintainability . . . . . . . . . . . . . . . . . . . . . . . 20

16 Constructor Chaining 20
16.1 Can one constructor call another constructor? . . . . . . . . . . . . . . . 20
16.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
16.3 Why Constructor Chaining? . . . . . . . . . . . . . . . . . . . . . . . . . 21
16.4 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

17 Difference: == operator vs = operator 21


17.1 Example Demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
17.2 For Objects — == compares reference, NOT value . . . . . . . . . . . . 22

18 Multiple Exception Handling 22


18.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
18.2 Program: Three Exceptions Demonstrated . . . . . . . . . . . . . . . . . 22

19 Student Marks Program 23


19.1 Accept Marks of 3 Subjects → Calculate Total & Average . . . . . . . . 23
19.1.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
19.2 Program: Student Marks, Total, and Average . . . . . . . . . . . . . . . 23

20 Inheritance Example: Shape → Circle & Rectangle 24


20.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
20.2 Program: Shape → Circle & Rectangle . . . . . . . . . . . . . . . . . . . 24

21 Package Creation and Usage 25


21.1 Theory of Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
21.2 Create Package library with Book Class & Demonstrate Importing . . . . 25
21.2.1 Step 1: Create Package library with Class Book . . . . . . . . . . 25
21.2.2 Step 2: Import & Use the Package . . . . . . . . . . . . . . . . . 26
21.3 How to Compile & Run . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

22 Synchronized Method vs Synchronized Block 27


22.1 Difference Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
22.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

23 Display Current Date and Time 27


23.1 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

24 Operator Precedence 28
24.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
24.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Page 3
CSE Department Java Programming - PYQ Solutions

25 Variable Scope in Java 28


25.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
25.2 1. Local Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
25.3 2. Instance Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
25.4 3. Class Variable (Static) . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

26 Abstraction vs Polymorphism 29
26.1 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
26.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

27 I/O System in Java 29


27.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

28 Byte Stream vs Character Stream 30


28.1 Comparison Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
28.2 Example: Writing & Reading a File (Character Stream) . . . . . . . . . 30
28.2.1 Write: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
28.2.2 Read: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
28.3 Example: Byte Stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

29 Operators in Java 31
29.1 1. Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.2 2. Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.3 3. Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.4 4. Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.5 5. Increment/Decrement Operators . . . . . . . . . . . . . . . . . . . . . 31
29.6 6. Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.7 7. Ternary Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
29.8 8. Instanceof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

30 Java Classes: Inner Classes, Singleton, Sub-Class 32


30.1 (a) Static Nested Classes and Inner Classes . . . . . . . . . . . . . . . . . 32
30.1.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
30.1.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
30.2 (b) Singleton Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
30.2.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
30.2.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
30.3 (c) Sub-Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
30.3.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
30.3.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

31 String to List Conversion 34


31.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
31.2 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

32 Thread Join Example 35


32.1 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
32.2 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

33 Exam Tips 35

Page 4
CSE Department Java Programming - PYQ Solutions

1 Principles of Object-Oriented Programming (OOP)


1.1 Theory
Object-Oriented Programming (OOP) is a programming approach based on the concept
of objects that contain data and methods. Java is a fully object-oriented language and
follows the main OOP principles.

1.2 Core OOP Principles


1.2.1 (1) Encapsulation
• Encapsulation means wrapping data (variables) and methods into a single unit called
a class.

• Access specifiers (private, public, protected) are used to hide data.

• Benefit: Security, data hiding, modular code.

1.2.2 (2) Inheritance


• Inheritance allows one class to acquire features of another class.

• There is a parent (super) class and child (sub) class.

• Benefit: Code reuse, hierarchical structure.

1.2.3 (3) Polymorphism


Polymorphism means “many forms.” In Java:

• Compile-time polymorphism → Method Overloading

• Run-time polymorphism → Method Overriding using dynamic dispatch

• Benefit: Flexibility and maintainability.

1.2.4 (4) Abstraction


• Abstraction means showing only essential features and hiding internal details.

• Achieved using abstract classes and interfaces.

• Benefit: Reduces complexity and increases security.

1.2.5 (5) Class and Object


• Class is a blueprint.

• Object is a real-world entity created from the class.

Page 5
CSE Department Java Programming - PYQ Solutions

2 Java Program Execution Process


2.1 What Goes Behind the Scene When Computer Runs Java
Program?
The complete execution process involves the following steps:

1. Step 1: Writing Java Code (.java file)

2. Step 2: Compilation using javac

• Java compiler converts code into bytecode (.class file).

3. Step 3: Bytecode is given to JVM

4. Step 4: Class Loader

• Loads the .class file into memory.

5. Step 5: Bytecode Verifier

• Checks for security violations


• Checks for illegal code
• Checks for stack overflow errors

6. Step 6: Execution Engine

• Interpreter: Reads bytecode line by line


• JIT Compiler: Improves performance by compiling frequently used code

7. Step 7: Garbage Collector

• Removes unused objects.

Note: This process makes Java secure, portable, and platform-independent.

3 Loop Statements in Java


3.1 Types of Loops
3.2 Example Programs
3.2.1 For Loop

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


2 System . out . println ( i ) ;
3 }

Page 6
CSE Department Java Programming - PYQ Solutions

Loop Usage Condition Runs Short Sample Code


Check Mini-
mum
for When number Before loop 0 times for(int i=1; i<=5;
of iterations is i++)
known
while When iterations Before loop 0 times while(i <= 5)
unknown
do-while Must run at After loop 1 time do {...} while(i
least once <= 5)
for-each Used for ar- Internal All ele- for(int x : arr)
rays/collections ments

Table 1: Comparison of Loop Types in Java

3.2.2 While Loop

1 int i = 1;
2 while ( i <= 5) {
3 System . out . println ( i ) ;
4 i ++;
5 }

3.2.3 Do-While Loop

1 int i = 1;
2 do {
3 System . out . println ( i ) ;
4 i ++;
5 } while ( i <= 5) ;

3.2.4 For-Each Loop

1 int arr [] = {10 ,20 ,30};


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

4 Applet vs Application
4.1 Comparison Table
4.2 Example Programs
4.2.1 Simple Applet Code

Page 7
CSE Department Java Programming - PYQ Solutions

Applet Application
Runs inside a browser or applet Runs independently as a standalone
viewer program
Uses applet viewer Uses JVM (java command)
Cannot access system resources (for Can access system resources easily
security)
Needs an HTML page to run Does not need HTML
Strong security restrictions No such restrictions
Mostly GUI-based Can be GUI or Console
Uses init(), start(), paint() Uses main() method

Table 2: Applet vs Application

1 import java . applet . Applet ;


2 import java . awt . Graphics ;
3

4 public class MyApplet extends Applet {


5 public void paint ( Graphics g ) {
6 g . drawString ( " Hello Applet ! " , 50 , 50) ;
7 }
8 }

HTML to run:
1 < applet code = " MyApplet . class " width = " 200 " height = " 100 " > </
applet >

4.2.2 Simple Application Code (Console Program)

1 class SimpleApp {
2 public static void main ( String [] args ) {
3 System . out . println ( " Hello Application ! " ) ;
4 }
5 }

5 Type Conversion in Java


5.1 Theory
Type Conversion means converting one data type into another. Java supports two types
of type conversion:

5.1.1 1. Implicit Conversion (Widening Conversion)


• Done automatically by Java

• Happens when small data type → larger data type

Page 8
CSE Department Java Programming - PYQ Solutions

• No data loss
• Example: int → long → float → double
Example:
1 int a = 20;
2 double b = a ; // int automatically converted to double

5.1.2 2. Explicit Conversion (Narrowing Conversion)


• Done manually using casting
• Large type → small type
• May cause data loss
• Syntax: (smallerType) value
Example:
1 double x = 9.78;
2 int y = ( int ) x ; // double converted to int ( decimal lost )

5.2 Complete Program Demonstrating Both Conversions


1 class Ty pe Co nv er si on De mo {
2 public static void main ( String [] args ) {
3

4 // Implicit Conversion ( Widening )


5 int a = 10;
6 double b = a ;
7 System . out . println ( " Implicit Conversion : " + b ) ;
8

9 // Explicit Conversion ( Narrowing )


10 double x = 15.75;
11 int y = ( int ) x ;
12 System . out . println ( " Explicit Conversion : " + y ) ;
13 }
14 }

6 Command Line Arguments in Java


6.1 Theory
• Command line arguments are values passed to the program when it is executed.
• They are stored in String[] args of the main() method.
• Each value is a String, so conversion may be required.
Syntax to run program:
java Test 10 20

Page 9
CSE Department Java Programming - PYQ Solutions

6.2 Example Program Using Command Line Arguments


1 class CommandDemo {
2 public static void main ( String args []) {
3

4 String name = args [0];


5 int age = Integer . parseInt ( args [1]) ; // converting
string to int
6

7 System . out . println ( " Name : " + name ) ;


8 System . out . println ( " Age : " + age ) ;
9 }
10 }

7 Swapping Numbers Without Third Variable


7.1 Theory
Swapping means exchanging values of two variables. There are many ways to swap
without a temporary variable.

7.2 Method 1: Swap Using Bitwise XOR


1 class SwapBitwise {
2 static void swap ( int a , int b ) {
3 a = a ^ b;
4 b = a ^ b;
5 a = a ^ b;
6

7 System . out . println ( " After Swap ( XOR ) : a = " + a + " , b = "
+ b);
8 }
9

10 public static void main ( String [] args ) {


11 swap (5 , 10) ;
12 }
13 }

7.3 Method 2: Swap Using Multiplication & Division


1 class SwapMulDiv {
2 static void swap ( int a , int b ) {
3 a = a * b;
4 b = a / b;
5 a = a / b;
6

7 System . out . println ( " After Swap ( Mul / Div ) : a = " + a + " ,
b=" + b);

Page 10
CSE Department Java Programming - PYQ Solutions

8 }
9

10 public static void main ( String [] args ) {


11 swap (4 , 8) ;
12 }
13 }

8 Event Handling in Java


8.1 Theory
• A class must implement ActionListener

• Register listener using addActionListener()

• Write event handling code inside actionPerformed()

8.2 Program 1: ActionListener Implementation


1 import java . awt .*;
2 import java . awt . event .*;
3

4 public class ButtonEventDemo implements ActionListener {


5

6 Frame f ;
7 Button b ;
8 Label l ;
9

10 ButtonEventDemo () {
11 f = new Frame ( " Event Handling Example " ) ;
12 b = new Button ( " Click Me " ) ;
13 l = new Label ( " Waiting for click ... " ) ;
14

15 b . setBounds (100 , 100 , 100 , 40) ;


16 l . setBounds (100 , 150 , 200 , 40) ;
17

18 f . add ( b ) ;
19 f . add ( l ) ;
20 f . setSize (300 , 300) ;
21 f . setLayout ( null ) ;
22 f . setVisible ( true ) ;
23

24 b . addAc tionLi stener ( this ) ; // register the listener


25 }
26

27 // Event Handling Code


28 public void actionPerformed ( ActionEvent e ) {
29 l . setText ( " Button Clicked ! " ) ;
30 }
31

Page 11
CSE Department Java Programming - PYQ Solutions

32 public static void main ( String [] args ) {


33 new ButtonEventDemo () ;
34 }
35 }

8.2.1 Explanation of Program


• We created a window (Frame)

• Added a button → “Click Me”

• Added a label

• Registered ActionListener → [Link](this)

• When button is clicked → actionPerformed() runs → Label text changes

8.3 Event Handling Using Anonymous Class


8.3.1 Theory
Anonymous class is:

• A class with no name

• Defined inside method call

• Used for small event handling tasks

Instead of writing separate class, we write event code directly inside:


1 b . addAct ionLis tener ( new ActionListener () {
2 public void actionPerformed ( ActionEvent e ) {
3 // event code here
4 }
5 }) ;

This reduces code length and is used often in real applications.

8.4 Program 2: Using Anonymous Class


1 import java . awt .*;
2 import java . awt . event .*;
3

4 public class A no ny mo us Ev en tD em o {
5

6 public static void main ( String [] args ) {


7

8 Frame f = new Frame ( " Anonymous Event Example " ) ;


9 Button b = new Button ( " Press " ) ;
10 Label l = new Label ( " No action yet ... " ) ;
11

12 b . setBounds (100 , 100 , 80 , 40) ;

Page 12
CSE Department Java Programming - PYQ Solutions

13 l . setBounds (100 , 150 , 200 , 40) ;


14

15 f . add ( b ) ;
16 f . add ( l ) ;
17 f . setSize (300 , 300) ;
18 f . setLayout ( null ) ;
19 f . setVisible ( true ) ;
20

21 // Event handling using Anonymous Class


22 b . addAc tionLi stener ( new ActionListener () {
23 public void actionPerformed ( ActionEvent e ) {
24 l . setText ( " Button Pressed ! " ) ;
25 }
26 }) ;
27 }
28 }

8.4.1 Explanation
• No class implements ActionListener
• We create an event handler inside the method itself
• It executes when the button is pressed
• Used when event is small and short

8.5 Final Exam-Ready Summary


Event Handling
• Mechanism to handle user actions
• Uses Delegation Event Model
• Important components → Event Source, Listener, Handler
ActionListener
• Interface with method actionPerformed()
• Used for button click events
Two ways to implement ActionListener:
1. Implementing the ActionListener interface
2. Using Anonymous Inner Class

9 File Handling in Java


9.1 Theory
File Handling in Java is done using I/O Streams. Two important classes are:

Page 13
CSE Department Java Programming - PYQ Solutions

9.1.1 1. FileWriter (Writing to a File)


• Used to write text into a file

• Part of [Link] package

• Automatically creates the file if it does not exist

• Must be closed using close() to save data

9.1.2 2. FileReader (Reading from a File)


• Used to read characters from a text file

• Reads one character at a time using read() method

• Returns -1 when end of file (EOF) is reached

9.2 Program: Write to file + Read from file


1 import java . io .*;
2

3 class FileR eadWri teDemo {


4 public static void main ( String [] args ) throws Exception {
5

6 // Writing to file
7 FileWriter fw = new FileWriter ( " demo . txt " ) ;
8 fw . write ( " Welcome to Java File Handling !\ nThis is a
sample text . " ) ;
9 fw . close () ;
10 System . out . println ( " Data written to file successfully .
");
11

12 // Reading from file


13 FileReader fr = new FileReader ( " demo . txt " ) ;
14 int ch ;
15 System . out . println ( " \ nFile Content : " ) ;
16 while (( ch = fr . read () ) != -1) {
17 System . out . print (( char ) ch ) ;
18 }
19 fr . close () ;
20 }
21 }

10 String Immutability in Java


10.1 Theory
A String is immutable which means:

• Once a String object is created, its value cannot be changed

Page 14
CSE Department Java Programming - PYQ Solutions

• If you try to modify a String, Java creates a new object instead of modifying the
existing one

• This improves security, performance, and memory efficiency

10.2 Why Strings Are Immutable?


• Stored in String Constant Pool → Saves memory

• Used in security-sensitive operations like passwords, class names, network connections

• Thread-safe → No need for synchronization

10.3 Example Program


1 class S t r in g I mm u t ab l e De m o {
2 public static void main ( String [] args ) {
3 String s = " Hello " ;
4 s = s + " World " ; // New object created
5 System . out . println ( s ) ;
6 }
7 }

Explanation:

• Initially “Hello” is stored

• When “Hello World” is created, Java creates a new String object, proving immutability

11 Recursion vs Iteration
11.1 Comparison Table

Feature Recursion Iteration


Definition Function calling itself Repeating statements using
loops
Control Method Function call stack Loop (for/while/do-while)
Memory Usage High → uses stack Low → normal variable
Speed Slow due to overhead Faster
Best Used For Tree, factorial, Fibonacci Repetitive tasks
May Cause Stack overflow No overflow

Table 3: Recursion vs Iteration

Page 15
CSE Department Java Programming - PYQ Solutions

11.2 Example: Factorial using Recursion & Iteration


11.2.1 Recursion

1 int fact ( int n ) {


2 if ( n == 1) return 1;
3 return n * fact (n -1) ;
4 }

11.2.2 Iteration

1 int factIter ( int n ) {


2 int result = 1;
3 for ( int i =1; i <= n ; i ++)
4 result *= i ;
5 return result ;
6 }

12 Constructor in Derived Class


12.1 Theory
• When a subclass is created, its constructor must call the constructor of the superclass
• The call is done using the super() keyword
• super() must be the first statement in a constructor
• If you don’t write super(), Java inserts it automatically

12.2 Program Demonstrating Constructor in Derived Class


1 class Animal {
2 Animal () {
3 System . out . println ( " Animal Constructor Called " ) ;
4 }
5 }
6

7 class Dog extends Animal {


8 Dog () {
9 super () ; // calls Animal () constructor
10 System . out . println ( " Dog Constructor Called " ) ;
11 }
12 }
13

14 class Test {
15 public static void main ( String [] args ) {
16 Dog d = new Dog () ;
17 }
18 }

Page 16
CSE Department Java Programming - PYQ Solutions

Output:

Animal Constructor Called


Dog Constructor Called

13 Objects and Variables as Parameters


13.1 Theory
In Java:

• Method parameters are passed using Call by Value

• For objects, the reference value (address) is passed

• So methods can modify object data, but not the reference itself

Types of parameters passed:

• Primitive Types → Copy of value

• Objects → Copy of reference (changes affect original object)

13.2 Program Demonstrating Object as Parameter


1 class Box {
2 int length ;
3 }
4

5 class PassObject {
6 static void change ( Box b ) {
7 b . length = 50; // modifies original object
8 }
9

10 public static void main ( String [] args ) {


11 Box b1 = new Box () ;
12 b1 . length = 10;
13

14 System . out . println ( " Before change : " + b1 . length ) ;


15 change ( b1 ) ;
16 System . out . println ( " After change : " + b1 . length ) ;
17 }
18 }

14 Exception Hierarchy in Java


14.1 Theory
Java has a well-defined exception hierarchy. At the top of the hierarchy is Throwable,
which has two major subclasses:

Page 17
CSE Department Java Programming - PYQ Solutions

Throwable
/ \
Exception Error
/ \
Checked Ex. Unchecked Ex.

14.1.1 1. Throwable
• Superclass of all errors and exceptions

• Contains methods like getMessage(), printStackTrace()

14.1.2 2. Exception
Represents conditions that a program should handle.
A. Checked Exceptions (Compile-time exceptions)

• Checked by compiler → must be handled using try-catch or throws

• Examples: IOException, SQLException, ClassNotFoundException, FileNotFoundEx-


ception

B. Unchecked Exceptions (Runtime Exceptions)

• Occur at runtime → compiler does NOT force handling

• Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsEx-


ception, NumberFormatException

C. Errors

• Not handled by programs. Caused due to environment

• Examples: OutOfMemoryError, StackOverflowError, VirtualMachineError

14.2 try, catch, finally


14.2.1 Theory
• try block: Contains code that may throw exception

• catch block: Handles the exception

• finally block: Always executes — even if exception occurs or program returns

14.3 Example: try–catch–finally


1 class T r y Ca t c hF i n al l y De m o {
2 public static void main ( String [] args ) {
3 try {
4 int a = 10 / 0; // Exception
5 }
6 catch ( A r i th m e ti c E xc e p ti o n e ) {

Page 18
CSE Department Java Programming - PYQ Solutions

7 System . out . println ( " Error : Division by zero ! " ) ;


8 }
9 finally {
10 System . out . println ( " Finally block always runs . " ) ;
11 }
12 }
13 }

Output:

Error: Division by zero!


Finally block always runs.

15 Method Overloading & Method Overriding


15.1 A. Method Overloading
• Same method name

• Different parameter list

• Happens within same class

• Compile-time polymorphism (Static binding)

Example:
1 class OverloadDemo {
2 int add ( int a , int b ) { return a + b ; }
3 double add ( double a , double b ) { return a + b ; }
4 }

15.2 B. Method Overriding


• Same method name

• Same parameters

• Child class redefines parent method

• Runtime polymorphism (Dynamic Method Dispatch)

Example:
1 class Parent {
2 void show () { System . out . println ( " Parent class " ) ; }
3 }
4

5 class Child extends Parent {


6 void show () { System . out . println ( " Child class " ) ; }
7 }

Page 19
CSE Department Java Programming - PYQ Solutions

Feature Overloading Overriding


Meaning Same method, different pa- Same method, same param-
rameters eters
Occurs in Same class Subclass
Binding Compile time Runtime
Polymorphism Static Dynamic
Inheritance No Yes
needed

Table 4: Overloading vs Overriding

15.3 Difference Table


15.4 Roles in Class Hierarchy
Overloading

• Allows multiple ways to call a method

• Increases readability

• Achieves compile-time flexibility

Overriding

• Allows subclass to give its own implementation

• Supports runtime polymorphism

• Improves extensibility

15.5 Implications for Maintainability


• Overloading → reduces method names, easier code

• Overriding → improves extension without touching parent class

16 Constructor Chaining
16.1 Can one constructor call another constructor?
YES — Constructor Chaining

• Java allows calling one constructor from another using this()

• Reduces code duplication

Page 20
CSE Department Java Programming - PYQ Solutions

16.2 Example
1 class Student {
2 Student () {
3 this (100) ; // calling another constructor
4 System . out . println ( " Default constructor " ) ;
5 }
6

7 Student ( int id ) {
8 System . out . println ( " ID = " + id ) ;
9 }
10 }

16.3 Why Constructor Chaining?


• Avoid repetition of initialization logic

• Cleaner code

• Easier maintenance

16.4 Rules
• this() must be FIRST statement in constructor

• Cannot call two constructors at same time

17 Difference: == operator vs = operator

Operator Meaning Example


= Assignment operator int a = 10;
== Comparison operator if(a == b)

Table 5: = vs == operators

• = assigns a value

• == checks equality

17.1 Example Demonstration


1 class OperatorsDemo {
2 public static void main ( String [] args ) {
3 int a = 5; // assignment
4 int b = 5;
5

6 if ( a == b ) // comparison
7 System . out . println ( " Both are equal " ) ;

Page 21
CSE Department Java Programming - PYQ Solutions

8 else
9 System . out . println ( " Not equal " ) ;
10 }
11 }

17.2 For Objects — == compares reference, NOT value


1 String s1 = new String ( " java " ) ;
2 String s2 = new String ( " java " ) ;
3

4 System . out . println ( s1 == s2 ) ; // false ( different memory )


5 System . out . println ( s1 . equals ( s2 ) ) ; // true ( same value )

18 Multiple Exception Handling


18.1 Theory
• Exception handling allows a Java program to handle abnormal conditions gracefully

• Using try–catch blocks, we can catch multiple exceptions individually

• Common exceptions include:

– NullPointerException → accessing methods on a null object


– ArithmeticException → division by zero
– ArrayIndexOutOfBoundsException → accessing invalid array index

18.2 Program: Three Exceptions Demonstrated


1 class M u l t i p l e E x c e p t i o n D e m o {
2 public static void main ( String [] args ) {
3 try {
4 // 1. Arithmetic Exception
5 int a = 10 / 0;
6

7 // 2. Null Pointer Exception


8 String s = null ;
9 System . out . println ( s . length () ) ;
10

11 // 3. Array Index Out of Bounds Exception


12 int arr [] = {1 , 2 , 3};
13 System . out . println ( arr [5]) ;
14 }
15 catch ( A r i th m e ti c E xc e p ti o n e ) {
16 System . out . println ( " Arithmetic Error : Division by
zero occurred ! " ) ;
17 }
18 catch ( N u l l P o i n t e r E x c e p t i o n e ) {

Page 22
CSE Department Java Programming - PYQ Solutions

19 System . out . println ( " Null Pointer Error : Accessing


data on null reference ! " ) ;
20 }
21 catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e ) {
22 System . out . println ( " Array Error : Invalid index
accessed ! " ) ;
23 }
24 finally {
25 System . out . println ( " Program Completed with
Exception Handling . " ) ;
26 }
27 }
28 }

19 Student Marks Program


19.1 Accept Marks of 3 Subjects → Calculate Total & Average
19.1.1 Theory
• Input is taken using Scanner

• Total = sum of three marks

• Average = total / 3

• Data types used: int and double

19.2 Program: Student Marks, Total, and Average


1 import java . util .*;
2

3 class StudentMarks {
4 public static void main ( String [] args ) {
5 Scanner sc = new Scanner ( System . in ) ;
6

7 System . out . print ( " Enter marks of subject 1: " ) ;


8 int m1 = sc . nextInt () ;
9

10 System . out . print ( " Enter marks of subject 2: " ) ;


11 int m2 = sc . nextInt () ;
12

13 System . out . print ( " Enter marks of subject 3: " ) ;


14 int m3 = sc . nextInt () ;
15

16 int total = m1 + m2 + m3 ;
17 double avg = total / 3.0;
18

19 System . out . println ( " Total Marks = " + total ) ;


20 System . out . println ( " Average Marks = " + avg ) ;

Page 23
CSE Department Java Programming - PYQ Solutions

21 }
22 }

20 Inheritance Example: Shape → Circle & Rectan-


gle
20.1 Theory
• Inheritance allows one class to acquire the properties of another

• Base class: Shape

• Derived classes: Circle, Rectangle

• Method Overriding is used to give specific implementation of area

20.2 Program: Shape → Circle & Rectangle


1 class Shape {
2 void area () {
3 System . out . println ( " Area not defined for generic shape
.");
4 }
5 }
6

7 class Circle extends Shape {


8 double radius ;
9

10 Circle ( double r ) {
11 radius = r ;
12 }
13

14 @Override
15 void area () {
16 double a = 3.14 * radius * radius ;
17 System . out . println ( " Area of Circle = " + a ) ;
18 }
19 }
20

21 class Rectangle extends Shape {


22 double length , breadth ;
23

24 Rectangle ( double l , double b ) {


25 length = l ;
26 breadth = b ;
27 }
28

29 @Override
30 void area () {

Page 24
CSE Department Java Programming - PYQ Solutions

31 double a = length * breadth ;


32 System . out . println ( " Area of Rectangle = " + a ) ;
33 }
34 }
35

36 class ShapeTest {
37 public static void main ( String [] args ) {
38 Shape s ;
39

40 s = new Circle (5.0) ;


41 s . area () ;
42

43 s = new Rectangle (4.0 , 6.0) ;


44 s . area () ;
45 }
46 }

Output Sample:
Area of Circle = 78.5
Area of Rectangle = 24.0

21 Package Creation and Usage


21.1 Theory of Packages
• A package is a group of related classes

• Helps in:

– Encapsulation
– Name-space management
– Code reusability

• Two steps:

1. Create a package using package packagename;


2. Use it using import packagename.*;

21.2 Create Package library with Book Class & Demonstrate


Importing
21.2.1 Step 1: Create Package library with Class Book
Directory Structure:
library/
[Link]
[Link]
[Link]:

Page 25
CSE Department Java Programming - PYQ Solutions

1 package library ;
2

3 public class Book {


4 String title ;
5 String author ;
6 double price ;
7

8 public Book ( String t , String a , double p ) {


9 title = t ;
10 author = a ;
11 price = p ;
12 }
13

14 public void show () {


15 System . out . println ( " Title : " + title ) ;
16 System . out . println ( " Author : " + author ) ;
17 System . out . println ( " Price : " + price ) ;
18 }
19 }

21.2.2 Step 2: Import & Use the Package


[Link]:
1 import library .*;
2

3 class LibraryTest {
4 public static void main ( String [] args ) {
5 Book b1 = new Book ( " Java Programming " , " James Gosling "
, 450.00) ;
6 b1 . show () ;
7 }
8 }

21.3 How to Compile & Run


Step 1: Compile the Book class

javac library/[Link]

Step 2: Compile the test class

javac [Link]

Step 3: Run the program

java LibraryTest

Page 26
CSE Department Java Programming - PYQ Solutions

Synchronized Method Synchronized Block


Entire method is locked Only a specific block of code is
locked
Less efficient (locks whole More efficient (locks small part)
method)
Uses method header synchronized Uses synchronized(obj) inside
method
One lock per object Multiple locks can be used
Simple to implement More flexible

Table 6: Synchronized Method vs Synchronized Block

22 Synchronized Method vs Synchronized Block


22.1 Difference Table
22.2 Example
1 class Demo {
2 synchronized void show () { // synchronized method
3 System . out . println ( " Method is locked " ) ;
4 }
5

6 void display () {
7 synchronized ( this ) { // synchronized block
8 System . out . println ( " Only this block is locked " ) ;
9 }
10 }
11 }

23 Display Current Date and Time


23.1 Program
1 import java . time .*;
2

3 class CurrentDateTime {
4 public static void main ( String [] args ) {
5 LocalDateTime now = LocalDateTime . now () ;
6 System . out . println ( " Current Date & Time : " + now ) ;
7 }
8 }

Page 27
CSE Department Java Programming - PYQ Solutions

24 Operator Precedence
24.1 Definition
Operator precedence means which operator is evaluated first when an expression has
multiple operators.

24.2 Example
1 int result = 10 + 20 * 3;

Explanation:

• * has higher precedence than +

• So first: 20 * 3 = 60

• Then: 10 + 60 = 70

Output: 70

25 Variable Scope in Java


25.1 Theory
Variable scope means where a variable can be accessed in a program.

25.2 1. Local Variable


• Declared inside method/block

• Exists only inside that block

1 void show () {
2 int x = 10; // local variable
3 System . out . println ( x ) ;
4 }

25.3 2. Instance Variable


• Declared inside class but outside methods

• Different for every object

1 class Demo {
2 int age = 20; // instance variable
3 }

Page 28
CSE Department Java Programming - PYQ Solutions

25.4 3. Class Variable (Static)


• Shared by all objects

• Declared using static

1 class Demo {
2 static int count = 0; // class variable
3 }

26 Abstraction vs Polymorphism
26.1 Abstraction
• Hides internal details

• Shows only necessary features

• Achieved by abstract class and interface

Example:
1 abstract class Animal {
2 abstract void sound () ;
3 }

26.2 Polymorphism
• Many forms of the same method

• Achieved by method overloading and overriding

Example:
1 class Shape {
2 void draw () { System . out . println ( " Drawing shape " ) ; }
3 }
4

5 class Circle extends Shape {


6 void draw () { System . out . println ( " Drawing circle " ) ; } //
overriding
7 }

27 I/O System in Java


27.1 Theory
Java I/O system handles:
• Reading data from input sources

Page 29
CSE Department Java Programming - PYQ Solutions

• Writing data to files/output devices


Packages used:
• [Link].*
• [Link].*

28 Byte Stream vs Character Stream


28.1 Comparison Table

Byte Stream Character Stream


Reads/writes 8-bit bytes Reads/writes 16-bit characters
Used for images, videos, binary Used for text files
data
Classes: FileInputStream, File- Classes: FileReader, FileWriter
OutputStream

Table 7: Byte Stream vs Character Stream

28.2 Example: Writing & Reading a File (Character Stream)


28.2.1 Write:

1 import java . io .*;


2

3 class WriteFile {
4 public static void main ( String [] args ) throws Exception {
5 FileWriter fw = new FileWriter ( " data . txt " ) ;
6 fw . write ( " Hello Java ! " ) ;
7 fw . close () ;
8 }
9 }

28.2.2 Read:

1 import java . io .*;


2

3 class ReadFile {
4 public static void main ( String [] args ) throws Exception {
5 FileReader fr = new FileReader ( " data . txt " ) ;
6 int ch ;
7 while (( ch = fr . read () ) != -1) {
8 System . out . print (( char ) ch ) ;
9 }
10 fr . close () ;
11 }
12 }

Page 30
CSE Department Java Programming - PYQ Solutions

28.3 Example: Byte Stream


1 FileInputStream fin = new FileInputStream ( " pic . jpg " ) ;
2 FileOutputStream fout = new FileOutputStream ( " copy . jpg " ) ;
3

4 int i ;
5 while (( i = fin . read () ) != -1) {
6 fout . write ( i ) ;
7 }
8 fin . close () ;
9 fout . close () ;

29 Operators in Java
29.1 1. Arithmetic Operators
+ - * / %

29.2 2. Relational Operators


< > <= >= == !=

29.3 3. Logical Operators


&& || !

29.4 4. Assignment Operators


= += -= *= /=

29.5 5. Increment/Decrement Operators


++ --

29.6 6. Bitwise Operators


& | ^ ~ << >> >>>

29.7 7. Ternary Operator


condition ? true : false

29.8 8. Instanceof Operator


Checks object type:
1 obj instanceof ClassName

Page 31
CSE Department Java Programming - PYQ Solutions

30 Java Classes: Inner Classes, Singleton, Sub-Class


30.1 (a) Static Nested Classes and Inner Classes
30.1.1 Theory
Nested Class: A class declared inside another class.
Static Nested Class:
• Declared static inside outer class
• Can access static members of outer class only
• Doesn’t need outer class object to instantiate
Inner Class (Non-static):
• Can access both static and non-static members of outer class
• Needs outer class object to create instance

30.1.2 Example

1 class Outer {
2 static int x = 10;
3 int y = 20;
4

5 // Static Nested Class


6 static class StaticNested {
7 void display () {
8 System . out . println ( " Static x = " + x ) ;
9 }
10 }
11

12 // Inner Class
13 class Inner {
14 void display () {
15 System . out . println ( " x = " + x + " , y = " + y ) ;
16 }
17 }
18 }
19

20 public class TestNested {


21 public static void main ( String [] args ) {
22 // Static Nested Class
23 Outer . StaticNested sn = new Outer . StaticNested () ;
24 sn . display () ;
25

26 // Inner Class
27 Outer o = new Outer () ;
28 Outer . Inner in = o . new Inner () ;
29 in . display () ;
30 }
31 }

Page 32
CSE Department Java Programming - PYQ Solutions

30.2 (b) Singleton Class


30.2.1 Theory
• Singleton class allows only one object of that class

• Used when global control of resource is required (e.g., DB connection)

30.2.2 Example

1 class Singleton {
2 private static Singleton instance ;
3

4 private Singleton () {} // private constructor


5

6 public static Singleton getInstance () {


7 if ( instance == null ) {
8 instance = new Singleton () ;
9 }
10 return instance ;
11 }
12

13 void show () {
14 System . out . println ( " Singleton instance " ) ;
15 }
16 }
17

18 public class TestSingleton {


19 public static void main ( String [] args ) {
20 Singleton s1 = Singleton . getInstance () ;
21 Singleton s2 = Singleton . getInstance () ;
22

23 s1 . show () ;
24 System . out . println ( s1 == s2 ) ; // true
25 }
26 }

30.3 (c) Sub-Class


30.3.1 Theory
• A class that inherits from another class is called a subclass

• Supports code reusability

• Uses keyword extends

30.3.2 Example

1 class Parent {
2 void message () { System . out . println ( " Parent class " ) ; }

Page 33
CSE Department Java Programming - PYQ Solutions

3 }
4

5 class Child extends Parent {


6 void message () { System . out . println ( " Child class " ) ; }
7 }
8

9 public class TestSub {


10 public static void main ( String [] args ) {
11 Child c = new Child () ;
12 c . message () ; // Child class
13 }
14 }

31 String to List Conversion


31.1 Theory
• Strings are immutable

• Convert String → List using ArrayList and loop

• Handle exceptions using try-catch

31.2 Program
1 import java . util .*;
2

3 class StringToList {
4 public static void main ( String [] args ) {
5 String str = " JavaProgramming " ;
6 List < Character > list = new ArrayList < >() ;
7

8 try {
9 for ( int i = 0; i < str . length () ; i ++) {
10 list . add ( str . charAt ( i ) ) ;
11 }
12 } catch ( Exception e ) {
13 System . out . println ( " Exception occurred : " + e ) ;
14 }
15

16 System . out . println ( " List of characters : " + list ) ;


17 }
18 }

Output:

[J, a, v, a, P, r, o, g, r, a, m, m, i, n, g]

Page 34
CSE Department Java Programming - PYQ Solutions

32 Thread Join Example


32.1 Theory
• join() allows one thread to wait until another finishes
• Used in multi-threading for proper sequencing

32.2 Program
1 class MyThread extends Thread {
2 String name ;
3 MyThread ( String name ) { this . name = name ; }
4

5 public void run () {


6 for ( int i =1; i <=5; i ++) {
7 System . out . println ( name + " running : " + i ) ;
8 try { Thread . sleep (500) ; } catch ( Exception e ) {}
9 }
10 }
11 }
12

13 public class Thr eadJo inExam ple {


14 public static void main ( String [] args ) {
15 MyThread t1 = new MyThread ( " Thread -1 " ) ;
16 MyThread t2 = new MyThread ( " Thread -2 " ) ;
17

18 t1 . start () ;
19 try { t1 . join () ; } catch ( Exception e ) {} // main
waits for t1
20

21 t2 . start () ;
22 try { t2 . join () ; } catch ( Exception e ) {} // main
waits for t2
23

24 System . out . println ( " All threads finished " ) ;


25 }
26 }

Output:
Thread-1 running: 1
Thread-1 running: 2
...
Thread-2 running: 1
...
All threads finished

33 Exam Tips
1. Write theory first, then short code snippet

Page 35
CSE Department Java Programming - PYQ Solutions

2. Use try-catch wherever exception might occur

3. For threads, always explain join()

4. Static nested vs inner class → always mention static member access

5. Singleton → explain private constructor + static instance

6. String → List → ArrayList + charAt()

Page 36

You might also like