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

OOP Java Complete Solutions

Uploaded by

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

OOP Java Complete Solutions

Uploaded by

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

GIDC DEGREE ENGINEERING COLLEGE

Subject: BE04000231 – Object Oriented Programming (Java)


Complete Solutions to Most Repeated Questions
All Units Covered | Exam-Oriented Answers | Easy Language
UNIT 1: Basics of Java

Q1. Explain JRE, JDK and JIT. 3 Marks

JDK – Java Development Kit


JDK is a software package used to develop Java programs. It includes tools like Java compiler (javac),
debugger, and other development tools. It also includes JRE inside it.
Example: When you write a Java program and compile it using javac, you are using JDK.

JRE – Java Runtime Environment


JRE is used to RUN Java programs. It includes JVM (Java Virtual Machine) and class libraries needed
to execute a Java program. JRE does NOT include development tools like compiler.
Example: When you run java HelloWorld, JRE is used to execute it.

JIT – Just In Time Compiler


JIT is a part of JVM. When a Java program runs, JVM converts bytecode to machine code. JIT speeds
up this process by compiling frequently used bytecode to native machine code so it runs faster next
time.

Feature Description
JDK For developing Java programs (includes
compiler + JRE)
JRE For running Java programs (includes JVM +
libraries)
JIT Speeds up execution by compiling bytecode
to machine code at runtime

Q2. Compare Object-Oriented Programming with Procedural/Sequential


3 Marks
Programming

OOP (Object Oriented) Procedural / Sequential


Focuses on objects and classes Focuses on functions/procedures
Data and functions are together in a class Data and functions are separate
Uses concepts like inheritance, No such concepts
polymorphism
Better for large, complex programs Good for small, simple programs
Example: Java, C++, Python Example: C, Pascal, FORTRAN
Supports data hiding (encapsulation) No data hiding concept
Code is reusable via inheritance Code reuse is limited

Q3. Method main is a public static method. Justify 4 Marks

Why 'public'?
The main() method must be public because it is called by the JVM (Java Virtual Machine) from outside
the class. If it were private or protected, JVM would not be able to access it and the program would not
start.

Why 'static'?
The main() method is static because JVM calls it WITHOUT creating an object of the class. If main()
were not static, JVM would need to create an object first, but it doesn't know how to do that without a
starting point.

Why 'void'?
main() returns void because it does not need to return any value to JVM after execution.

Full Signature:
public static void main(String[] args)
String[] args – allows command line arguments to be passed to the program.

Simple Example:
public class Hello {
public static void main(String[] args) {
[Link]("Hello World");
}
}

Q4. Explain type-conversion in Java 4 Marks

Type conversion means converting a value from one data type to another. In Java, there are two types:

1. Widening Conversion (Automatic / Implicit)


Converting a smaller data type to a larger data type. This is done automatically by Java because there
is no data loss.
Order: byte → short → int → long → float → double
int a = 10;
double b = a; // automatic, no error
[Link](b); // Output: 10.0

2. Narrowing Conversion (Manual / Explicit)


Converting a larger data type to a smaller data type. This must be done manually using casting
because data may be lost.
double x = 9.99;
int y = (int) x; // manual casting
[Link](y); // Output: 9 (decimal part lost)

Q5. What are the data-types and operators available in Java? 7 Marks

DATA TYPES IN JAVA

A) Primitive Data Types (8 types):


Data Type Size & Description
byte 1 byte – Range: -128 to 127
short 2 bytes – Range: -32,768 to 32,767
int 4 bytes – Most commonly used integer type
long 8 bytes – For very large integers, end with L
e.g. 100L
float 4 bytes – Decimal numbers, end with f e.g.
3.14f
double 8 bytes – More precise decimal numbers
char 2 bytes – Single character e.g. 'A'
boolean 1 bit – Only true or false

B) Non-Primitive (Reference) Types: String, Array, Class, Interface

OPERATORS IN JAVA

1. Arithmetic Operators: +, -, *, /, %
int a=10, b=3; a+b=13, a-b=7, a*b=30, a/b=3, a%b=1
2. Relational (Comparison) Operators: ==, !=, >, <, >=, <=
a > b → true, a == b → false
3. Logical Operators: && (AND), || (OR), ! (NOT)
(a>5 && b<5) → true
4. Assignment Operators: =, +=, -=, *=, /=
a += 5 means a = a + 5
5. Unary Operators: ++, --
a++ (post-increment), ++a (pre-increment)
6. Bitwise Operators: &, |, ^, ~, <<, >>
7. Ternary Operator: condition ? value1 : value2
int max = (a > b) ? a : b;
Q6. Define Object Oriented Concepts 3 Marks

1. Class:
A blueprint or template for creating objects. It defines attributes (fields) and behaviors (methods).
2. Object:
An instance of a class. It has its own state (data) and behavior (methods).
3. Encapsulation:
Wrapping data and methods together in a class and hiding data using private access modifier.
4. Inheritance:
A class (child) can inherit properties and methods from another class (parent).
5. Polymorphism:
Same method name behaves differently in different situations (overloading & overriding).
6. Abstraction:
Hiding internal implementation details and showing only the necessary features.

Q7. What are Syntax errors, Runtime errors, and Logic errors? 3 Marks

1. Syntax Error (Compile Error):


Errors in the grammar/rules of Java code. Detected by the compiler before the program runs.
int a = ; // Missing value – Syntax Error

2. Runtime Error:
Errors that occur while the program is running. The program compiles successfully but crashes during
execution.
int a = 5 / 0; // Division by zero – Runtime Error

3. Logic Error:
The program runs without crashing but gives wrong output. These are hardest to find because there is
no error message.
// To find max, but wrong logic:
int max = (a < b) ? a : b; // Logic Error – should be >

Q8. What is Type Casting? Explain Widening and Narrowing type casting 4 Marks

Type casting means converting a variable from one data type to another.

Widening Type Casting (Automatic):


Converting smaller → larger type. Done automatically. No data loss.
int a = 100;
long b = a; // widening – int to long
double c = b; // widening – long to double
Narrowing Type Casting (Manual / Explicit):
Converting larger → smaller type. Must use (dataType) syntax. May lose data.
double x = 3.99;
int y = (int) x; // narrowing – output: 3 (decimal lost)

Casting Order (Widening):


byte → short → int → long → float → double

Q9. Explain Data Types in detail with example 7 Marks

Java has two categories of data types: Primitive and Non-Primitive.

1. PRIMITIVE DATA TYPES:


Type Size | Range | Example
byte 1 byte | -128 to 127 | byte b = 100;
short 2 bytes | -32768 to 32767 | short s = 5000;
int 4 bytes | -2^31 to 2^31-1 | int i = 100000;
long 8 bytes | Very large numbers | long l =
9999999L;
float 4 bytes | Decimal, 6-7 digits | float f = 3.14f;
double 8 bytes | Decimal, 15-16 digits | double d =
3.14159;
char 2 bytes | Single Unicode char | char c = 'A';
boolean 1 bit | true or false | boolean b = true;

2. NON-PRIMITIVE DATA TYPES:


• String: stores sequence of characters → String s = "Hello";
• Array: stores multiple values of same type → int[] arr = {1,2,3};
• Class: user-defined blueprint
• Interface: defines abstract methods

Example Program:
public class DataTypeDemo {
public static void main(String[] args) {
int age = 20;
double salary = 25000.50;
char grade = 'A';
boolean isPassed = true;
String name = "Rahul";
[Link](name + " Age:" + age);
}
}
Q10. List out features of Java. Explain any two features 3 Marks

Features of Java:
• Simple
• Object Oriented
• Platform Independent (Write Once Run Anywhere)
• Secure
• Robust
• Multithreaded
• Distributed
• Dynamic

1. Platform Independent:
Java code is compiled into bytecode (.class file) by the Java compiler. This bytecode runs on any OS
that has JVM installed. So Java programs written on Windows can run on Linux or Mac without
changes.

2. Object Oriented:
Java is based on OOP concepts: class, object, inheritance, encapsulation, polymorphism, and
abstraction. Everything in Java is an object (except primitive types).

Q11. Discuss significance of bytecode 3 Marks

Bytecode is the intermediate code generated by the Java compiler when you compile a .java file. The
output is a .class file containing bytecode — not machine code.

Why is Bytecode Important?


• Platform Independence: Bytecode is not machine-specific. Any machine with JVM can run it.
• Security: JVM checks the bytecode before running, preventing harmful code.
• Portability: Write Once, Run Anywhere (WORA).
• Optimization: JIT compiler converts bytecode to machine code at runtime for faster execution.

Flow:
Source Code (.java) → Java Compiler (javac) → Bytecode (.class) → JVM → Machine Code → Output

Q12. Explain Java garbage collection mechanism 4 Marks

Garbage Collection (GC) is an automatic memory management feature in Java. It automatically frees
memory occupied by objects that are no longer referenced/used by the program.

How it Works:
• When an object is created using 'new', memory is allocated on the Heap.
• When an object has no reference pointing to it, it becomes eligible for garbage collection.
• JVM runs the Garbage Collector to automatically delete those unused objects.
• The programmer does NOT need to manually free memory (unlike C/C++ using free()).

Example:
MyClass obj = new MyClass(); // object created
obj = null; // obj no longer references the object
// Now the old MyClass object is eligible for GC

[Link]() Method:
You can request JVM to run garbage collection using [Link](), but it is not guaranteed to run
immediately.

Q13. List OOP characteristics and describe inheritance with examples 7 Marks

OOP Characteristics:
• Encapsulation – Binding data and methods together; hiding data with private.
• Inheritance – Child class inherits properties from parent class.
• Polymorphism – Same method behaves differently (overloading / overriding).
• Abstraction – Hiding implementation, showing only functionality.

INHERITANCE IN DETAIL:
Inheritance allows one class (child/subclass) to acquire the properties and methods of another class
(parent/superclass). It promotes code reusability.

Syntax:
class Parent {
// parent members
}
class Child extends Parent {
// child gets all parent members
}

Example:
class Animal {
String name = "Dog";
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited from Animal
[Link](); // own method
}
}

Types of Inheritance:
• Single: One parent, one child
• Multilevel: A → B → C
• Hierarchical: One parent, multiple children
• Multiple: Through interfaces (Java does NOT support multiple via classes)
UNIT 2: Conditional and Looping Statements

Q1. Write a program to take string input as command line argument and
7 Marks
count occurrence of each character

Concept:
Command line arguments are passed to main(String[] args). args[0] gives the first argument.

Program:
public class CharCount {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a string");
return;
}
String str = args[0];
[Link]("String: " + str);
for (char ch = 'a'; ch <= 'z'; ch++) {
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == ch || [Link](i) == (char)(ch-32))
count++;
}
if (count > 0)
[Link](ch + " : " + count);
}
}
}

Run: javac [Link] → java CharCount hello


Output: h:1 e:1 l:2 o:1

Q2. Difference between Nested if and Multi-way if (if-else-if) statements 3 Marks

Nested if Multi-way if (if-else-if)


if inside another if Series of if-else-if conditions
Used to check multiple conditions together Used to select one from many options
Can get complex/difficult to read Easier to read and manage
Checks inner condition only if outer is true Checks each condition in sequence

Nested if Example:
if (a > 0) {
if (b > 0) {
[Link]("Both positive");
}
}

Multi-way if Example:
if (marks >= 90) [Link]("A");
else if (marks >= 70) [Link]("B");
else [Link]("C");

Q3. Write a program demonstrating: import, new, this, break, continue 4 Marks

import [Link]; // import keyword

public class KeywordDemo {


int num;
KeywordDemo(int num) {
[Link] = num; // 'this' refers to current object
}
public static void main(String[] args) {
KeywordDemo obj = new KeywordDemo(10); // 'new' creates object
[Link]("Num: " + [Link]);
for (int i = 1; i <= 10; i++) {
if (i == 5) continue; // skip 5
if (i == 8) break; // stop at 8
[Link](i + " ");
}
}
}

Output: 1 2 3 4 6 7

To compile and run:


javac [Link]
java KeywordDemo
UNIT 3: Basics of Object Oriented Programming

Q1. Write a program showing function overloading. Also differentiate


7 Marks
function overloading and overriding

Function Overloading Program:


public class MathOps {
// Same method name, different parameters
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
public static void main(String[] args) {
MathOps m = new MathOps();
[Link]([Link](2, 3)); // 5
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link](1, 2, 3)); // 6
}
}

Method Overloading Method Overriding


Same method name, different parameters Same method name AND same parameters
Happens in same class Happens in parent-child classes
Compile-time polymorphism Runtime polymorphism
Return type can be different Return type must be same
No inheritance needed Inheritance is required

Q2. Explain about Arrays, Types of Arrays and Array Methods 3 Marks

Array:
An array is a collection of elements of the same data type stored in consecutive memory locations.

Types of Arrays:
1. Single-Dimensional Array:
int[] arr = {10, 20, 30, 40};
[Link](arr[0]); // Output: 10

2. Multi-Dimensional Array (2D):


int[][] matrix = {{1,2},{3,4}};
[Link](matrix[0][1]); // Output: 2

Array Methods/Properties:
• [Link] – returns the size of the array
• [Link](arr) – sorts the array
• [Link](arr) – converts array to string for printing
• [Link](arr, n) – copies n elements

Q3. Explain 'Passing argument by values' with example 4 Marks

In Java, when primitive types (int, float, etc.) are passed to a method, a COPY of the value is passed.
Any changes made inside the method do NOT affect the original variable. This is called Pass by Value.

Example:
public class PassByValue {
static void change(int x) {
x = 100; // changes only local copy
[Link]("Inside method: " + x); // 100
}
public static void main(String[] args) {
int a = 10;
change(a);
[Link]("After method: " + a); // Still 10
}
}

Output: Inside method: 100 | After method: 10


Explanation: The original variable 'a' is not changed because only a copy was sent to the method.

Q4. Explain Method Overloading and Overriding 4 Marks

Method Overloading (Compile-time Polymorphism):


Multiple methods with the same name but different parameters in the SAME class.
class Demo {
void show(int a) { [Link]("int: " + a); }
void show(String s) { [Link]("String: " + s); }
}

Method Overriding (Runtime Polymorphism):


Child class provides its own implementation of a method already defined in the parent class. Same
name, same parameters.
class Animal { void sound() { [Link]("Generic sound"); } }
class Dog extends Animal {
@Override
void sound() { [Link]("Woof!"); }
}
// Dog d = new Dog(); [Link](); → Output: Woof!

Q5. Explain Arguments & Parameters, Pass by Value and Pass by 4 Marks
Reference

Parameters vs Arguments:
• Parameter: Variable defined in the method signature → void add(int a, int b) – here a, b are
parameters
• Argument: Actual value passed when calling the method → add(5, 10) – here 5, 10 are arguments

Pass by Value (Primitive types):


A copy of the value is passed. Original variable is NOT changed.
void change(int x) { x = 50; } // original not affected

Pass by Reference (Objects):


In Java, objects are passed by reference. The method gets the reference (address) of the object, so
changes DO affect the original object.
void modify(int[] arr) { arr[0] = 99; }
int[] a = {1,2,3};
modify(a);
[Link](a[0]); // Output: 99 (original changed)

Q6. Explain Overloading and Overriding with example 7 Marks

(See Q1 and Q4 of this unit for complete explanation with examples. Combined answer below:)

Overloading Example – Calculator:


class Calculator {
int multiply(int a, int b) { return a * b; }
double multiply(double a, double b) { return a * b; }
int multiply(int a, int b, int c) { return a * b * c; }
}

Overriding Example – Shapes:


class Shape { void draw() { [Link]("Drawing shape"); } }
class Circle extends Shape {
@Override
void draw() { [Link]("Drawing Circle"); }
}
class Square extends Shape {
@Override
void draw() { [Link]("Drawing Square"); }
}

Q7. Explain static keyword with example 4 Marks

The 'static' keyword in Java means the member belongs to the CLASS itself, not to any specific object.
Static members are shared by all objects of the class.
Uses of static:
• static variable – shared among all objects
• static method – can be called without creating an object
• static block – runs once when class is loaded

Example:
class Counter {
static int count = 0; // shared by all objects
Counter() { count++; }
static void showCount() {
[Link]("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter(); new Counter(); new Counter();
[Link](); // Output: Count: 3
}
}

Q8. Explain class and object with respect to Java 7 Marks

CLASS:
A class is a blueprint/template that defines the structure and behavior for objects. It contains fields
(data) and methods (functions).

OBJECT:
An object is a real-world instance of a class. When you use 'new', an object is created in heap memory.

Example:
class Student {
// Fields (attributes)
String name;
int age;
// Method (behavior)
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // object created
[Link] = "Rahul";
[Link] = 20;
[Link](); // Output: Name: Rahul, Age: 20
Student s2 = new Student(); // another object
[Link] = "Priya";
[Link] = 21;
[Link]();
}
}

Q9. What is Constructor Overloading? 4 Marks

Constructor Overloading means having multiple constructors in a class with different parameter lists.
Java calls the right constructor based on the arguments provided.

Example:
class Box {
int length, width;
Box() { // default
length = 1; width = 1;
}
Box(int l) { // one parameter
length = l; width = l;
}
Box(int l, int w) { // two parameters
length = l; width = w;
}
void show() {
[Link](length + "x" + width);
}
}
// new Box() → 1x1
// new Box(5) → 5x5
// new Box(4, 6) → 4x6

Q10. List and explain available types of constructors in Java with example 4 Marks

Types of Constructors:

1. Default Constructor (No-argument):


Created automatically by Java if no constructor is defined. Has no parameters.
class Car { Car() { [Link]("Car created"); } }

2. Parameterized Constructor:
Takes arguments to initialize fields with specific values.
class Car { String model; Car(String m) { model = m; } }

3. Copy Constructor:
Creates a new object by copying values from an existing object.
class Car {
String model;
Car(String m) { model = m; }
Car(Car c) { model = [Link]; } // copy constructor
}
Q11. How to access object via reference variable? Explain with example 4 Marks

A reference variable stores the address (reference) of an object in memory. You use the dot (.) operator
to access the object's fields and methods.

Example:
class Student {
String name;
void greet() { [Link]("Hello " + name); }
}
public class Main {
public static void main(String[] args) {
Student s; // reference variable (no object yet)
s = new Student(); // object created, s holds reference
[Link] = "Aakash"; // accessing field via reference
[Link](); // accessing method via reference
}
}

Multiple references can point to the same object. Changing via one reference affects all references.

Q12. Define constructor. How objects are constructed? Explain


7 Marks
constructor overloading with example

Constructor:
A constructor is a special method used to initialize an object when it is created. It has the SAME NAME
as the class and NO return type.

How Objects are Constructed:


• Step 1: JVM allocates memory on the heap for the new object
• Step 2: Instance variables are set to default values
• Step 3: The constructor is called to initialize the object
• Step 4: Reference to the object is returned

Constructor Overloading Example:


class Employee {
String name; int id; double salary;
// Default
Employee() { name="Unknown"; id=0; salary=0; }
// Parameterized
Employee(String n, int i, double s) { name=n; id=i; salary=s; }
// Copy
Employee(Employee e) { name=[Link]; id=[Link]; salary=[Link]; }
void show() {
[Link](id+" "+name+" Rs."+salary);
}
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee("Raj", 101, 50000);
Employee e3 = new Employee(e2); // copy
[Link](); [Link](); [Link]();
}
}

Q13. What is a Package? Benefits? Steps to create and use 4 Marks

Package:
A package is a folder/namespace that groups related Java classes and interfaces together.

Benefits:
• Avoids naming conflicts
• Organized code structure
• Access control (visibility)
• Easy to maintain and reuse

Steps to Create and Use a Package:


Step 1: Create the package
// File: mypack/[Link]
package mypack;
public class Hello {
public void greet() { [Link]("Hello from mypack!"); }
}
Step 2: Compile
javac -d . [Link]
Step 3: Use in another class
import [Link];
public class Main {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
}
}

Q14. Explain access modifiers with Example 4 Marks

Modifier Class | Package | Subclass | World


private Yes | No | No | No
default (no keyword) Yes | Yes | No | No
protected Yes | Yes | Yes | No
public Yes | Yes | Yes | Yes

Example:
class Demo {
private int a = 1; // only within this class
int b = 2; // within same package
protected int c = 3; // package + subclasses
public int d = 4; // accessible everywhere
}

Q15. Explain visibility modifiers 3 Marks

Visibility modifiers (access specifiers) control where a class member can be accessed from. Java has
4: private, default, protected, public. See Q14 table above for details.

Q16. What is Constructor? Explain constructor overloading 4 Marks

See Q12 above for full explanation. Key points: Constructor has same name as class, no return type,
called automatically on object creation. Overloading = multiple constructors with different parameters.

Q17. Which statement will cause compilation error? A a=new A(), A a=new
4 Marks
B(), B b=new A(), B b=new B()

Given: class A is parent, class B extends A (child).

Analysis:
• A a = new A(); → VALID – Parent reference, parent object
• A a = new B(); → VALID – Parent reference can hold child object (upcasting)
• B b = new A(); → COMPILATION ERROR – Child reference CANNOT hold parent object
• B b = new B(); → VALID – Child reference, child object

Answer: Statement iii) B b = new A(); will cause compilation error.


Reason: In Java, a parent class reference can refer to a child object (polymorphism), but a child class
reference CANNOT refer to a parent object without explicit casting.

Q18. Explain Default, Parameterized, Shallow copy and Deep copy


4 Marks
constructor

Default Constructor:
No parameters. Java creates one automatically if you don't write any.
Box() { length = 0; width = 0; }

Parameterized Constructor:
Accepts parameters to set values at creation time.
Box(int l, int w) { length = l; width = w; }
Shallow Copy Constructor:
Copies the reference of objects — both original and copy point to the SAME data in memory.
// Changing copy ALSO changes original for objects

Deep Copy Constructor:


Creates a completely new copy of the object — original and copy are INDEPENDENT.
class Student {
String name; int[] marks;
// Deep copy
Student(Student s) {
name = [Link];
marks = [Link](); // new copy of array
}
}

Q19. Explain constructor with the help of an example 3 Marks

Constructor = Special method to initialize objects.


Rules: Same name as class, no return type, called automatically when object is created.
class Circle {
double radius;
Circle(double r) { // constructor
radius = r;
}
double area() { return 3.14 * radius * radius; }
public static void main(String[] args) {
Circle c = new Circle(5); // constructor called
[Link]("Area: " + [Link]()); // 78.5
}
}

Q20. Explain all access modifiers and their visibility as class members 7 Marks

Java provides four access modifiers to control visibility:

Access Modifier Accessible From


private Only within the SAME class
default (no modifier) Within the same package only
protected Same package + subclasses (even different
package)
public Everywhere – any class, any package

Detailed Example:
package pack1;
public class A {
private int x = 1; // only inside A
int y = 2; // default – pack1 only
protected int z = 3; // pack1 + subclasses
public int w = 4; // everywhere
}

Best Practice: Keep fields private and provide public getter/setter methods (encapsulation).
UNIT 4: Inheritance, Polymorphism and Wrapper Classes

Q1. Explain inheritance with its types and give suitable example 7 Marks

Inheritance allows a child class to inherit fields and methods from a parent class, enabling code reuse.

Syntax: class Child extends Parent { }

Types of Inheritance:
1. Single Inheritance:
class A { } class B extends A { }
2. Multilevel Inheritance:
class A { } class B extends A { } class C extends B { }
3. Hierarchical Inheritance:
class A { } class B extends A { } class C extends A { }
4. Multiple Inheritance (via interfaces only):
interface I1 { } interface I2 { } class A implements I1, I2 { }

Example:
class Vehicle { String brand="Toyota"; void honk(){[Link]("Beep!");} }
class Car extends Vehicle {
int doors = 4;
void show() { [Link](brand + " has " + doors + " doors"); }
}
// Car c = new Car(); [Link](); [Link]();

Q2. Write difference between String class and StringBuffer class 3 Marks

String StringBuffer
Immutable (cannot be changed) Mutable (can be changed)
Stored in String pool Stored in heap memory
Slower for many modifications Faster for many modifications
Thread-safe (immutable) Thread-safe (synchronized)
String s = "Hello"; StringBuffer sb = new StringBuffer("Hello");
[Link]("World") creates new string [Link]("World") modifies same object

Q3. Explain super keyword with example 4 Marks


'super' is a reference variable used to refer to the parent class. It has three uses:

1. Access parent class fields:


[Link]
2. Call parent class method:
[Link]()
3. Call parent class constructor:
super(arguments) // must be first line in child constructor

Example:
class Animal {
String name = "Animal";
void sound() { [Link]("Some sound"); }
}
class Dog extends Animal {
String name = "Dog";
void show() {
[Link](name); // Dog
[Link]([Link]); // Animal
[Link](); // Some sound
}
}

Q4. Describe abstract class Shape with subclasses Triangle, Rectangle,


7 Marks
Circle and override area()

Program:
abstract class Shape {
abstract double area(); // abstract method
}
class Triangle extends Shape {
double base, height;
Triangle(double b, double h) { base=b; height=h; }
public double area() { return 0.5 * base * height; }
}
class Rectangle extends Shape {
double length, width;
Rectangle(double l, double w) { length=l; width=w; }
public double area() { return length * width; }
}
class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
public double area() { return 3.14 * radius * radius; }
}
public class Main {
public static void main(String[] args) {
Shape t = new Triangle(6, 4);
Shape r = new Rectangle(5, 3);
Shape c = new Circle(7);
[Link]("Triangle area: " + [Link]()); // 12.0
[Link]("Rectangle area: " + [Link]()); // 15.0
[Link]("Circle area: " + [Link]()); // 153.86
}
}

Q5. How can we protect subclass from overriding the method of


3 Marks
superclass? Explain

We use the 'final' keyword to prevent a method from being overridden in the child class.

class Parent {
final void show() { // final method
[Link]("Cannot override this!");
}
}
class Child extends Parent {
// void show() { } // COMPILE ERROR if uncommented
}

Similarly, if we declare the entire class as 'final', no class can extend it.
final class Parent { }
// class Child extends Parent { } // COMPILE ERROR

Q6. What is runtime polymorphism? Write a program to demonstrate it 7 Marks

Runtime Polymorphism (Dynamic Method Dispatch):


When a method call is resolved at RUNTIME (not compile time) based on the actual object type, not the
reference type. This is achieved through method overriding.

Program:
class Animal {
void sound() { [Link]("Animal makes a sound"); }
}
class Dog extends Animal {
public void sound() { [Link]("Dog barks: Woof!"); }
}
class Cat extends Animal {
public void sound() { [Link]("Cat meows: Meow!"); }
}
public class Main {
public static void main(String[] args) {
Animal a; // Parent reference
a = new Animal();
[Link](); // Animal makes a sound
a = new Dog(); // Parent ref → Dog object
[Link](); // Dog barks: Woof!
a = new Cat(); // Parent ref → Cat object
[Link](); // Cat meows: Meow!
}
}
The method call [Link]() is decided at RUNTIME based on which object 'a' is holding.

Q7. Explain keywords: super, static, final, this 7 Marks

1. this keyword:
Refers to the current class object. Used to avoid ambiguity between fields and parameters.
class A { int x; A(int x) { this.x = x; } }

2. super keyword:
Refers to the parent class. Used to access parent fields, methods, and constructors.
class B extends A { void show() { [Link](); } }

3. static keyword:
Member belongs to class, not object. Can be accessed without creating an object.
class C { static int count=0; static void show(){...} }
[Link](); // no object needed

4. final keyword:
final variable = constant (cannot change), final method = cannot override, final class = cannot extend.
final int MAX = 100; // cannot change MAX

Q8. Differentiate between final, finally and finalize 7 Marks

final finally
Keyword Block (used with try-catch)
Prevents change/override/extend Always executes after try-catch
final int x=5; final class; final method try{...}catch{...}finally{...}
Applied to variable, method, class Applied to block of code

What happens if class/method is final?


• final class: Cannot be inherited. E.g., String class is final.
• final method: Cannot be overridden in child class.

Q9. Explain abstract class with example 3 Marks

An abstract class is a class that cannot be instantiated (cannot create objects). It can contain abstract
methods (without body) that must be implemented by subclasses.

abstract class Vehicle {


abstract void start(); // no body
void stop() { [Link]("Stopped"); } // concrete method
}
class Bike extends Vehicle {
public void start() { [Link]("Bike started"); }
}
// Vehicle v = new Vehicle(); // ERROR
// Bike b = new Bike(); [Link](); [Link](); // OK

Q10. Explain Primitive data types and Wrapper class data types 4 Marks

Primitive Data Types:


Basic built-in types: int, float, double, char, boolean, byte, short, long. They store values directly in
memory.

Wrapper Classes:
Java provides a Wrapper class for each primitive type to treat it as an object. Useful for collections and
utility methods.
Primitive Wrapper Class
int Integer
float Float
double Double
char Character
boolean Boolean
byte Byte
long Long

Autoboxing & Unboxing:


int a = 5;
Integer obj = a; // autoboxing (primitive → object)
int b = obj; // unboxing (object → primitive)
[Link]("123"); // convert String to int

Q11. Explain about Encapsulation and Abstraction 4 Marks

Encapsulation:
Wrapping data (fields) and methods together in a class, and restricting access using private. Data is
only accessed via public getters/setters.
class BankAccount {
private double balance; // hidden
public void deposit(double amt) { balance += amt; }
public double getBalance() { return balance; }
}
Abstraction:
Hiding internal implementation and showing only what is necessary. Achieved using abstract classes
and interfaces.
abstract class ATM {
abstract void withdraw(double amt); // user just calls this
// internal logic is hidden
}

Q12. State design hints for class and inheritance. Discuss static modifier 7 Marks

Design Hints for Classes:


• Always keep data private (encapsulation)
• Provide public getter/setter methods
• Group related data and behavior in one class
• Use meaningful class and method names

Design Hints for Inheritance:


• Use inheritance only when there is a true 'IS-A' relationship (Dog IS-A Animal)
• Prefer composition over inheritance when possible
• Don't override methods unless needed
• Use super() to initialize parent properties

Static Modifier:
Static means the member belongs to the class, not to instances. Static variables are shared across all
objects.
class MathUtil {
static final double PI = 3.14159;
static double circleArea(double r) { return PI * r * r; }
}
// Usage: [Link](5); // no object needed

Q13. Explain about different types of String methods 7 Marks

Method Description & Example


length() Returns length of string → "Hello".length() =
5
charAt(i) Returns char at index → "Hello".charAt(1) =
'e'
indexOf(s) Returns index of substring →
"Hello".indexOf("ll") = 2
substring(i,j) Returns substring → "Hello".substring(1,3)
= "el"
toUpperCase() Converts to uppercase →
"hello".toUpperCase() = "HELLO"
toLowerCase() Converts to lowercase →
"HELLO".toLowerCase() = "hello"
trim() Removes leading/trailing spaces
replace(a,b) Replaces characters → "Hello".replace('l','r')
= "Herro"
equals(s) Compares strings (case-sensitive) →
returns true/false
contains(s) Checks if string contains substring →
returns boolean
split(regex) Splits string into array → "a,b,c".split(",") =
[a,b,c]
concat(s) Joins strings → "Hello".concat(" World")

Q14. Explain about Final class, Fields and Methods 3 Marks

final variable:
Cannot be changed after initialization. Acts as a constant.
final int MAX = 100; // cannot do MAX = 200 later

final method:
Cannot be overridden by subclasses.
class Parent { final void show() {...} }

final class:
Cannot be extended (inherited). Example: String, Integer classes in Java are final.
final class MyClass { }
// class Child extends MyClass { } // COMPILE ERROR

Q15. What is Dynamic Binding? Show how it works 3 Marks

Dynamic Binding (Late Binding) means the method call is resolved at RUNTIME rather than compile
time, based on the actual type of the object.

class Shape { void draw() { [Link]("Drawing Shape"); } }


class Rect extends Shape { public void draw() { [Link]("Drawing Rectangle"); }
}
Shape s = new Rect(); // parent reference, child object
[Link](); // Decided at RUNTIME → Output: Drawing Rectangle

The JVM checks the actual object type at runtime and calls the correct overridden method.

Q16. Explain the concept of finalization 3 Marks


Finalization is the process by which an object performs cleanup operations before it is removed from
memory by the garbage collector.

The finalize() method is called by the JVM garbage collector before destroying an object. You can
override it to release resources (close files, database connections).
class Resource {
protected void finalize() throws Throwable {
[Link]("Resource cleaned up");
[Link]();
}
}

Note: In modern Java, it's better to use try-with-resources for cleanup.

Q17. Write a Java program to implement multiple inheritance for


7 Marks
calculating area of circle and square

Note: Java does not support multiple inheritance through classes. We use INTERFACES.
interface CircleArea {
default double areaOfCircle(double r) { return 3.14 * r * r; }
}
interface SquareArea {
default double areaOfSquare(double s) { return s * s; }
}
class Shapes implements CircleArea, SquareArea {
public static void main(String[] args) {
Shapes obj = new Shapes();
[Link]("Circle Area: " + [Link](5)); // 78.5
[Link]("Square Area: " + [Link](4)); // 16.0
}
}

Q18. What is polymorphism? Explain dynamic binding with example 7 Marks

Polymorphism:
'Many forms' – the same method/interface works differently based on the object. Two types: Compile-
time (overloading) and Runtime (overriding).

Dynamic Binding (Runtime Polymorphism) Example:


class Employee {
void work() { [Link]("Employee is working"); }
}
class Developer extends Employee {
public void work() { [Link]("Developer is coding"); }
}
class Manager extends Employee {
public void work() { [Link]("Manager is planning"); }
}
public class Main {
public static void main(String[] args) {
Employee e;
e = new Developer(); [Link](); // Developer is coding
e = new Manager(); [Link](); // Manager is planning
}
}

Q19. Explain keywords: super and this 4 Marks

this keyword:
• Refers to the current class instance
• Differentiates instance variable from parameter
• Can call another constructor: this()
class A { int x; A(int x) { this.x = x; } }

super keyword:
• Refers to the parent class
• Access parent fields and methods
• Call parent constructor: super() (must be first line)
class B extends A { B(int x) { super(x); } }

Q20. Define types of polymorphism 3 Marks

1. Compile-time Polymorphism (Static Binding):


Resolved at compile time. Achieved through METHOD OVERLOADING. The compiler decides which
method to call based on the arguments.
void add(int a, int b) { ... }
void add(double a, double b) { ... }

2. Runtime Polymorphism (Dynamic Binding):


Resolved at runtime. Achieved through METHOD OVERRIDING. JVM decides which method to call
based on the object type.
Animal a = new Dog(); [Link](); // Dog's method called at runtime

Q21. Differentiate between Abstract class and Interfaces 3 Marks

Abstract Class Interface


Can have abstract + concrete methods All methods abstract (before Java 8)
Can have instance variables Only public static final variables
A class can extend only ONE abstract class A class can implement MULTIPLE interfaces
Use: extends Use: implements
Can have constructors No constructors
Supports partial implementation Defines a contract (fully abstract)

Q22. Compare String with StringBuffer. Write a program to count


7 Marks
occurrence of a character

See Q2 of this unit for comparison table. Program below:

public class CharOccurrence {


public static void main(String[] args) {
String str = "programming";
char target = 'g';
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == target) count++;
}
[Link]("'" + target + "' appears " + count + " times");
// Output: 'g' appears 2 times
}
}

Q23. Discuss BufferedInputStream and BufferedOutputStream classes 7 Marks

BufferedInputStream:
Reads data from an input stream with an internal buffer. This makes reading faster because fewer
actual disk reads occur.

BufferedOutputStream:
Writes data to an output stream with an internal buffer. Data is written to the buffer first, then flushed to
the actual output.

Example:
import [Link].*;
public class BufferedDemo {
public static void main(String[] args) throws Exception {
// Writing
FileOutputStream fos = new FileOutputStream("[Link]");
BufferedOutputStream bos = new BufferedOutputStream(fos);
String msg = "Hello Buffered World!";
[Link]([Link]());
[Link]();
[Link]();
// Reading
FileInputStream fis = new FileInputStream("[Link]");
BufferedInputStream bis = new BufferedInputStream(fis);
int ch;
while ((ch = [Link]()) != -1)
[Link]((char)ch);
[Link]();
}
}
UNIT 5: Interface, Abstract Class and Exception Handling

Q1. Define Interface and explain how it differs from class 4 Marks

Interface:
An interface is a completely abstract type that defines a contract — a set of methods that a class MUST
implement. It is declared with the 'interface' keyword.

interface Drawable {
void draw(); // abstract by default
}
class Circle implements Drawable {
public void draw() { [Link]("Drawing circle"); }
}

Interface Class
Only abstract methods (before Java 8) Can have concrete methods
Variables are public static final Variables can be any type
A class can implement many interfaces A class can extend only one class
No constructor Has constructors
keyword: interface keyword: class

Q2. What is an Exception? List built-in exceptions and explain any one 7 Marks

Exception:
An exception is an unexpected event that occurs during program execution and disrupts the normal
flow of the program. Java handles exceptions using try-catch-finally blocks.

Built-in Exceptions:
• ArithmeticException – division by zero
• ArrayIndexOutOfBoundsException – invalid array index
• NullPointerException – using null reference
• NumberFormatException – invalid number format
• ClassCastException – invalid type casting
• StackOverflowException – infinite recursion
• FileNotFoundException – file not found
• IOException – general I/O error

Detailed: ArithmeticException
Occurs when an arithmetic operation fails, most commonly division by zero.
public class Demo {
public static void main(String[] args) {
try {
int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
}
}
}

Q3. Write a program to raise and handle divide by zero exception 7 Marks

public class DivideByZero {


public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // throws exception
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("Program continues...");
}
}
}

Output:
Exception caught: / by zero
Program continues...

Q4. Write method for computing x^y with command line arguments and
7 Marks
handle exceptions

public class Power {


static long power(int x, int y) {
if (y < 0) throw new IllegalArgumentException("y must be >= 0");
long result = 1;
for (int i = 0; i < y; i++) result *= x;
return result;
}
public static void main(String[] args) {
try {
if ([Link] < 2) throw new IllegalArgumentException("Need 2 args");
int x = [Link](args[0]);
int y = [Link](args[1]);
[Link](x + "^" + y + " = " + power(x, y));
} catch (NumberFormatException e) {
[Link]("Invalid number format: " + [Link]());
} catch (IllegalArgumentException e) {
[Link]("Invalid input: " + [Link]());
}
}
}
Run: java Power 2 10 → Output: 2^10 = 1024

Q5. What is Exception? Demonstrate handling different types of


4 Marks
exceptions

public class MultiException {


public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // ArrayIndexOutOfBoundsException
int x = 5 / 0; // ArithmeticException
String s = null;
[Link](); // NullPointerException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Error: " + [Link]());
} catch (ArithmeticException e) {
[Link]("Math Error: " + [Link]());
} catch (NullPointerException e) {
[Link]("Null Error: " + [Link]());
} finally {
[Link]("Done");
}
}
}

Q6. Explain Comparable and Cloneable interface 7 Marks

Comparable Interface:
Used to define the natural ordering of objects. Contains one method: compareTo(). Used by
[Link]().
import [Link].*;
class Student implements Comparable<Student> {
String name; int marks;
Student(String n, int m) { name=n; marks=m; }
public int compareTo(Student s) { return [Link] - [Link]; }
}
// [Link](list); // sorts by marks automatically

Cloneable Interface:
Marks an object as cloneable. The clone() method creates an exact copy of the object.
class Box implements Cloneable {
int length;
Box(int l) { length = l; }
public Object clone() throws CloneNotSupportedException {
return [Link]();
}
}
Box b1 = new Box(10);
Box b2 = (Box) [Link](); // exact copy

Q7. What is Exception? Explain exception hierarchy and


7 Marks
throw/catch/handle

Exception Hierarchy:
Throwable (root) → Error (serious, don't catch) | Exception → RuntimeException | CheckedException

try-catch-finally:
try {
// code that may throw exception
} catch (ExceptionType e) {
// handle the exception
} finally {
// always runs (cleanup code)
}

throw (manually throw exception):


throw new ArithmeticException("Custom error");

throws (declare that method may throw):


void readFile() throws IOException { ... }

Complete Example:
public class ExDemo {
static void validate(int age) {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}
public static void main(String[] args) {
try {
validate(-5);
} catch (IllegalArgumentException e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Validation done");
}
}
}

Q8. Explain the interface with an example program 7 Marks

interface Animal {
String name = "Animal"; // public static final by default
void sound(); // public abstract by default
default void breathe() { [Link]("Breathing..."); }
}
class Dog implements Animal {
public void sound() { [Link]("Woof!"); }
}
class Cat implements Animal {
public void sound() { [Link]("Meow!"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); [Link](); [Link]();
a = new Cat(); [Link]();
}
}

Q9. Explain File class with its methods 7 Marks

File class ([Link]):


The File class represents a file or directory path on the filesystem. It provides methods to check, create,
delete files/directories.

Method Description
exists() Returns true if file/dir exists
getName() Returns the file name
getPath() Returns the file path
length() Returns size of file in bytes
createNewFile() Creates a new empty file
delete() Deletes the file
isFile() Returns true if it is a file
isDirectory() Returns true if it is a directory
mkdir() Creates a directory
list() Returns array of files in directory

Example:
import [Link].*;
public class FileDemo {
public static void main(String[] args) throws Exception {
File f = new File("[Link]");
[Link]();
[Link]("Name: " + [Link]());
[Link]("Exists: " + [Link]());
[Link]("Size: " + [Link]() + " bytes");
}
}

Q10. Write a Java program to read [Link] file and display content 4 Marks

import [Link].*;
public class ReadFile {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String line;
[Link]("File Content:");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("File not found!");
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
}
}

Q11. Explain usage of FileInputStream and FileOutputStream with


4 Marks
example

FileInputStream: reads bytes from a file


FileOutputStream: writes bytes to a file

import [Link].*;
public class ByteStream {
public static void main(String[] args) throws Exception {
// Writing to file
FileOutputStream fos = new FileOutputStream("[Link]");
String msg = "Hello Java!";
[Link]([Link]());
[Link]();
[Link]("File written.");
// Reading from file
FileInputStream fis = new FileInputStream("[Link]");
int ch;
[Link]("File content: ");
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
}
}

Q12. Write a program that counts number of words in a text file 7 Marks

import [Link].*;
public class WordCount {
public static void main(String[] args) throws Exception {
if ([Link] == 0) {
[Link]("Usage: java WordCount filename");
return;
}
BufferedReader br = new BufferedReader(new FileReader(args[0]));
int wordCount = 0;
String line;
while ((line = [Link]()) != null) {
if (![Link]().isEmpty()) {
String[] words = [Link]().split("\\s+");
wordCount += [Link];
}
}
[Link]();
[Link]("Total words: " + wordCount);
}
}
Run: java WordCount [Link]

Q13. Write program that illustrates interface inheritance (P→P1,P2→P12,


7 Marks
class Q implements P12)

interface P {
int CONST_P = 1;
void methodP();
}
interface P1 extends P {
int CONST_P1 = 2;
void methodP1();
}
interface P2 extends P {
int CONST_P2 = 3;
void methodP2();
}
interface P12 extends P1, P2 {
int CONST_P12 = 4;
void methodP12();
}
class Q implements P12 {
public void methodP() { [Link]("CONST_P = " + CONST_P); }
public void methodP1() { [Link]("CONST_P1 = " + CONST_P1); }
public void methodP2() { [Link]("CONST_P2 = " + CONST_P2); }
public void methodP12() { [Link]("CONST_P12 = " + CONST_P12); }
public static void main(String[] args) {
Q obj = new Q();
[Link](); obj.methodP1(); obj.methodP2(); obj.methodP12();
}
}

Q14. What is Exception? Explain try, catch and finally with example 7 Marks

Exception: An abnormal condition that disrupts normal program flow.


try block:
Contains code that might throw an exception. If exception occurs, control jumps to catch.
catch block:
Catches and handles the specific exception. Multiple catch blocks allowed.
finally block:
Always executes regardless of exception. Used for cleanup (closing files, connections).

Example:
public class TryCatchDemo {
public static void main(String[] args) {
try {
[Link]("Start");
int[] a = new int[3];
a[10] = 5; // exception here
[Link]("This won't print");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Finally always runs");
}
}
}

Q15. What is throw used for? What is throws used for? 3 Marks

throw (lowercase):
Used to MANUALLY throw an exception from within a method.
throw new IllegalArgumentException("Invalid age");

throws (lowercase):
Used in method declaration to DECLARE that the method might throw certain checked exceptions, so
the caller must handle it.
void readFile(String name) throws IOException {
// may throw IOException
}

throw throws
Used to throw an exception Declares exceptions a method may throw
Followed by exception object Followed by exception class names
Inside method body In method signature
throw new Ex("msg"); void m() throws Ex { }

Q16. Explain Java keywords: throw, throws, finally 3 Marks


throw: Manually throw an exception
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");

throws: Declare checked exceptions in method signature


public void readData() throws IOException, FileNotFoundException { }

finally: Block that always runs after try-catch


try { ... } catch(Exception e) { ... } finally { [Link](); }

Q17. Explain file I/O using byte stream (FileInputStream,


7 Marks
FileOutputStream)

Byte streams handle I/O in units of 8-bit bytes. Used for binary files (images, audio) as well as text files.

import [Link].*;
public class ByteStreamDemo {
public static void main(String[] args) throws Exception {
// Write to file
FileOutputStream fos = new FileOutputStream("[Link]");
byte[] data = "Java Byte Stream Example".getBytes();
[Link](data);
[Link]();
[Link]("Written to file");
// Read from file
FileInputStream fis = new FileInputStream("[Link]");
byte[] buffer = new byte[[Link]()];
[Link](buffer);
[Link]();
[Link]("Read: " + new String(buffer));
}
}

Q18. Explain file I/O using character stream (FileReader, FileWriter) 4 Marks

Character streams handle I/O in 16-bit Unicode characters. Better suited for text files.
import [Link].*;
public class CharStreamDemo {
public static void main(String[] args) throws Exception {
// Write to file
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello from FileWriter!\n");
[Link]("Second line here.");
[Link]();
// Read from file
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) [Link]((char)ch);
[Link]();
}
}
Q19. Write exception handling mechanisms in Java 4 Marks

Java Exception Handling Mechanisms:

1. try-catch: Handle exception


try { int x = 10/0; } catch (ArithmeticException e) { [Link](e); }

2. finally: Cleanup code


finally { [Link](); }

3. throw: Manually raise exception


throw new RuntimeException("Custom error");

4. throws: Propagate exception to caller


void m() throws IOException { }

5. Multi-catch (Java 7+):


catch (IOException | SQLException e) { }

6. Custom Exception:
class MyException extends Exception { MyException(String msg){super(msg);} }

Q20. Create Student class. Write student manager program using


7 Marks
FileInputStream and FileOutputStream

import [Link].*;
class Student implements Serializable {
int id; String name; double gpa;
Student(int id, String name, double gpa) {
[Link]=id; [Link]=name; [Link]=gpa;
}
public String toString(){return id+" "+name+" GPA:"+gpa;}
}
public class StudentManager {
public static void main(String[] args) throws Exception {
// Write
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](new Student(1, "Rahul", 8.5));
[Link](new Student(2, "Priya", 9.0));
[Link]();
// Read
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
[Link]([Link]());
[Link]([Link]());
[Link]();
}
}
UNIT 6: Concurrency Control (Threads)

Q1. Explain Thread life cycle in detail. Write a program to create child
7 Marks
thread to print 1 to 10

Thread Life Cycle (5 States):


• 1. New: Thread object created but not started yet
• 2. Runnable: start() called, thread is ready to run, waiting for CPU
• 3. Running: Thread is actually executing (run() method executing)
• 4. Blocked/Waiting: Thread waiting for I/O or another thread
• 5. Terminated (Dead): run() method completed

Program:
class ChildThread extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("Child Thread: " + i);
try { [Link](500); } catch (InterruptedException e) {}
}
}
}
public class Main {
public static void main(String[] args) {
[Link]("Main thread started");
ChildThread t = new ChildThread();
[Link](); // starts new thread, calls run()
[Link]("Main thread ended");
}
}

Q2. What do you understand by thread? Describe the complete lifecycle


7 Marks
of thread

Thread:
A thread is a lightweight unit of execution within a program. Java supports multithreading – running
multiple threads simultaneously for better performance.

Ways to create threads:


• 1. Extending Thread class
• 2. Implementing Runnable interface

Complete Lifecycle:
State Description
New Thread object created (Thread t = new
Thread())
Runnable [Link]() called – thread ready for CPU
Running CPU allocated – run() executing
Blocked/Waiting sleep(), wait(), or I/O wait
Terminated run() completed or exception occurred

Q3. Explain thread state, thread properties and thread synchronization 4 Marks

Thread Properties:
• Thread Name: [Link]() / [Link]()
• Thread Priority: 1 (MIN) to 10 (MAX), default 5. Set with setPriority()
• Daemon Thread: Background thread. setDaemon(true)
• Thread ID: [Link]()

Thread Synchronization:
When multiple threads access shared data, they may cause data inconsistency. Synchronization
ensures only one thread accesses shared data at a time.
class Counter {
int count = 0;
synchronized void increment() { // only one thread at a time
count++;
}
}

Q4. Explain Thread Synchronization with example 7 Marks

Problem without Synchronization:


Multiple threads modifying the same variable can cause incorrect results (race condition).

Synchronized Example:
class BankAccount {
private int balance = 1000;
synchronized void withdraw(int amount) {
if (balance >= amount) {
[Link]([Link]().getName() + " withdrawing "+amount);
balance -= amount;
[Link]("Balance: " + balance);
} else {
[Link]("Insufficient balance");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
Thread t1 = new Thread(() -> [Link](600), "Thread-1");
Thread t2 = new Thread(() -> [Link](600), "Thread-2");
[Link](); [Link]();
}
}

Q5. Explain multithreading using Thread class 4 Marks

Step 1: Create a class that extends Thread. Step 2: Override run() method. Step 3: Create object and
call start().

class MyThread extends Thread {


String taskName;
MyThread(String name) { taskName = name; }
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](taskName + ": step " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread("Download");
MyThread t2 = new MyThread("Upload");
[Link](); // t1 and t2 run simultaneously
[Link]();
}
}

Q6. Explain multithreading using Runnable interface 4 Marks

Step 1: Create a class implementing Runnable. Step 2: Override run(). Step 3: Pass to Thread object
and call start().

class MyTask implements Runnable {


String name;
MyTask(String n) { name = n; }
public void run() {
for (int i = 1; i <= 3; i++)
[Link](name + ": " + i);
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyTask("Task A"));
Thread t2 = new Thread(new MyTask("Task B"));
[Link](); [Link]();
}
}
Runnable is preferred over extending Thread because a class can only extend ONE class, but
can implement multiple interfaces.

Q7. Explain how start() method invokes run() in Thread class 4 Marks

When you call start(), the JVM creates a new thread of execution and internally calls the run() method
on the new thread. You should NEVER call run() directly — that would execute it on the main thread,
not a new thread.

class Demo extends Thread {


public void run() {
[Link]("Running in: " + [Link]().getName());
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
[Link](); // Creates new thread → calls run() on it
// [Link](); // Wrong! Runs on main thread, not new thread
}
}
UNIT 7: I/O Management, JavaFX, and Collections

Q1. Explain Color class and its methods in JavaFX 3 Marks

The Color class in JavaFX ([Link]) is used to define colors for text, shapes, and
backgrounds.

Creating Colors:
Color c1 = [Link]; // named color
Color c2 = [Link](255, 128, 0); // RGB values
Color c3 = [Link]("#FF8000"); // hex string
Color c4 = [Link](1.0, 0.5, 0.0); // 0.0 to 1.0

Methods:
• getRed(), getGreen(), getBlue() – returns component (0.0–1.0)
• getOpacity() – returns transparency
• brighter() – returns brighter version
• darker() – returns darker version
• invert() – returns inverted color

Q2. Enlist various layout panes and explain any two in detail 7 Marks

JavaFX Layout Panes:


• HBox – arranges nodes horizontally
• VBox – arranges nodes vertically
• BorderPane – has top, bottom, left, right, center areas
• GridPane – arranges nodes in rows and columns
• FlowPane – wraps nodes to next row/column when space fills
• StackPane – stacks nodes on top of each other
• AnchorPane – anchor nodes to edges of the pane

1. HBox (Horizontal Box):


HBox hbox = new HBox(10); // 10px spacing
Button b1 = new Button("OK");
Button b2 = new Button("Cancel");
[Link]().addAll(b1, b2);

2. VBox (Vertical Box):


VBox vbox = new VBox(15);
Label lbl = new Label("Name:");
TextField tf = new TextField();
[Link]().addAll(lbl, tf);
Q3. Write importance of JavaFX compared to AWT and Swing 4 Marks

Feature JavaFX vs AWT/Swing


Design Modern UI with CSS styling support
Graphics Hardware-accelerated 2D and 3D graphics
Media Built-in support for audio and video
FXML UI can be designed separately with FXML
(like XML)
Scene Builder Drag-and-drop visual designer
Animation Rich animation API built-in
Rich Controls More advanced controls than Swing

Q4. How to create Scene object? Set scene in stage? Write program to
7 Marks
place red circle

JavaFX Architecture:
Stage → Scene → Layout Pane → Nodes (shapes, buttons, etc.)

import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
public class RedCircle extends Application {
public void start(Stage stage) {
Circle circle = new Circle(80);
[Link]([Link]);
StackPane root = new StackPane();
[Link]().add(circle);
Scene scene = new Scene(root, 300, 300); // create scene
[Link]("Red Circle");
[Link](scene); // set scene in stage
[Link]();
}
public static void main(String[] args) { launch(args); }
}

Yes, multiple scenes can be created. Use [Link](scene2) to switch.

Q5. Explain mouse and key event handler in JavaFX 3 Marks

Mouse Events: setOnMouseClicked, setOnMouseMoved, setOnMousePressed


[Link](e -> {
[Link]("Clicked at: " + [Link]() + ", " + [Link]());
});

Key Events: setOnKeyPressed, setOnKeyReleased, setOnKeyTyped


[Link](e -> {
[Link]("Key pressed: " + [Link]());
});

Q6. Explain Color class, Font class, Image and ImageView class in
3 Marks
JavaFX

Color class: (See Q1 above)

Font class ([Link]):


Font f = new Font("Arial", 24);
Font f2 = [Link]("Times New Roman", [Link], 18);

Image and ImageView:


Image img = new Image("file:[Link]");
ImageView iv = new ImageView(img);
[Link](200); [Link](true);

Q7. Explain concept of inner classes and types with example program 7 Marks

Inner Class: A class defined inside another class.

Types:
1. Member Inner Class:
class Outer {
class Inner { void show(){[Link]("Inner class");} }
}
// [Link] obj = new Outer().new Inner();

2. Static Nested Class:


class Outer {
static class Nested { void show(){[Link]("Static nested");} }
}
// [Link] obj = new [Link]();

3. Local Inner Class (inside a method):


void method() { class Local{void show(){}} new Local().show(); }

4. Anonymous Inner Class (no name):


Runnable r = new Runnable() {
public void run() { [Link]("Anonymous class"); }
};
Q8. Explain about adapter classes and mouse events with example 4 Marks

Adapter Class:
An adapter class provides default (empty) implementations of all methods of an interface. You only
override the methods you need, avoiding the need to implement all interface methods.

// Instead of implementing all MouseListener methods:


import [Link].*;
class MyListener extends MouseAdapter {
// Only override what you need
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at " + [Link]() + "," + [Link]());
}
}

Q9. Explain Inner class with example 4 Marks

See Q7 above. Simple combined example:


class University {
String name = "GIDC";
class Department {
String dept = "CSE";
void show() {
[Link](name + " - " + dept); // can access outer
}
}
public static void main(String[] args) {
University u = new University();
[Link] d = [Link] Department();
[Link](); // GIDC - CSE
}
}

UNIT 7 (continued): Collections Framework

Q1. Explain ArrayList class 4 Marks

ArrayList:
ArrayList is a resizable array implementation of the List interface. It stores elements in insertion order
and allows duplicates.

import [Link].*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Banana");
[Link]([Link](0)); // Apple
[Link]([Link]()); // 2
[Link](list); // [Apple, Cherry]
}
}

Common methods: add(), remove(), get(), size(), contains(), clear(), sort()

Q2. What method do you use to obtain an element from an iterator?


4 Marks
Explain

Iterator:
An iterator is used to traverse a collection one element at a time.

Methods:
• hasNext() – returns true if more elements exist
• next() – returns the next element (used to obtain element)
• remove() – removes the last element returned by next()

import [Link].*;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10); [Link](20); [Link](30);
Iterator<Integer> it = [Link]();
while ([Link]()) {
int elem = [Link](); // obtain element
[Link](elem);
}
}
}

Q3. What is Collection? Explain List, Stack, Queue classes 3 Marks

Collection Framework:
A set of classes and interfaces in Java for storing and manipulating groups of objects ([Link]
package).

List: Ordered collection, allows duplicates


List<String> list = new ArrayList<>();

Stack: LIFO (Last In First Out)


Stack<Integer> s = new Stack<>();
[Link](10); [Link](20);
[Link](); // returns 20

Queue: FIFO (First In First Out)


Queue<String> q = new LinkedList<>();
[Link]("A"); [Link]("B");
[Link](); // returns A

Q4. Write a short note on Java Collections 7 Marks

Java Collections Framework (JCF):


A unified architecture for representing and manipulating groups of objects. Located in [Link] package.

Main Interfaces:
• Collection – root interface
• List – ordered, allows duplicates (ArrayList, LinkedList, Vector)
• Set – no duplicates (HashSet, TreeSet, LinkedHashSet)
• Queue – FIFO order (LinkedList, PriorityQueue)
• Map – key-value pairs (HashMap, TreeMap, LinkedHashMap)

Key Classes:
Class Description
ArrayList Resizable array, fast access
LinkedList Doubly linked list, fast insert/delete
HashSet No duplicates, no order
TreeSet Sorted, no duplicates
HashMap Key-value pairs, no order
TreeMap Sorted key-value pairs
Stack LIFO stack
PriorityQueue Elements ordered by priority

Utility class: Collections provides sort(), reverse(), shuffle(), min(), max()

Q5. Write a program to add input elements in ArrayList, sort in


7 Marks
descending order

import [Link].*;
public class SortDesc {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Scanner sc = new Scanner([Link]);
[Link]("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
[Link]([Link]());
}
[Link]("Original: " + list);
[Link](list, [Link]());
[Link]("Sorted (Desc): " + list);
}
}

Output Example:
Enter 5 numbers: 5 2 8 1 9
Sorted (Desc): [9, 8, 5, 2, 1]

Q6. List out methods of Iterator and explain it 4 Marks

Method Description
hasNext() Returns true if there are more elements to
iterate
next() Returns the next element in the collection
remove() Removes the last element returned by next()

Example with all methods:


Iterator<String> it = [Link]();
while ([Link]()) { // check
String s = [Link](); // get element
if ([Link]("delete"))
[Link](); // safe removal
}

Q7. What is Vector class? 3 Marks

Vector is a dynamic array class (like ArrayList) but it is SYNCHRONIZED (thread-safe). It is a legacy
class from early Java (1.0) and is now replaced by ArrayList for single-threaded use.

import [Link].*;
Vector<Integer> v = new Vector<>();
[Link](10); [Link](20); [Link](30);
[Link]([Link](1)); // 20
[Link]([Link]()); // 3

Vector ArrayList
Synchronized (thread-safe) Not synchronized
Slower due to synchronization Faster
Legacy class Modern class
Grows by doubling size Grows by 50%
UNIT 8: Designing GUI Applications using JavaFX

Q1. Explain controls: TextArea, Scrollbar, Checkbox, ComboBox 4 Marks

1. TextArea:
A multi-line text input field. User can type multiple lines.
TextArea ta = new TextArea();
[Link]("Enter description...");
[Link](5);

2. ScrollBar:
Allows scrolling. Has min, max, and current value.
ScrollBar sb = new ScrollBar();
[Link](0); [Link](100);

3. CheckBox:
Allows true/false selection. Multiple can be selected.
CheckBox cb = new CheckBox("Accept Terms");
[Link](); // true if checked

4. ComboBox:
Drop-down list to select one option.
ComboBox<String> cb = new ComboBox<>();
[Link]().addAll("Java", "Python", "C++");
[Link](); // get selected item

Q2. Explain controls: Checkbox, Radio Button, TextField, Label 4 Marks

1. CheckBox: (see Q1 above)

2. RadioButton (with ToggleGroup – only one can be selected):


ToggleGroup group = new ToggleGroup();
RadioButton rb1 = new RadioButton("Male");
RadioButton rb2 = new RadioButton("Female");
[Link](group);
[Link](group);

3. TextField (single-line text input):


TextField tf = new TextField();
[Link]("Enter name");
String input = [Link]();

4. Label (display text):


Label lbl = new Label("Enter your name:");
[Link]("-fx-font-size: 16px;");

Q3. Develop a GUI based application using JavaFX controls 7 Marks

Simple Login Form:


import [Link];
import [Link].*; import [Link].*;
import [Link].*; import [Link];
public class LoginApp extends Application {
public void start(Stage stage) {
Label lblUser = new Label("Username:");
TextField tfUser = new TextField();
Label lblPass = new Label("Password:");
PasswordField pfPass = new PasswordField();
Button btnLogin = new Button("Login");
Label lblResult = new Label();
[Link](e -> {
if ([Link]().equals("admin") && [Link]().equals("1234"))
[Link]("Login Successful!");
else
[Link]("Invalid credentials!");
});
GridPane grid = new GridPane();
[Link](10); [Link](10);
[Link](lblUser,0,0); [Link](tfUser,1,0);
[Link](lblPass,0,1); [Link](pfPass,1,1);
[Link](btnLogin,1,2); [Link](lblResult,1,3);
[Link](new Scene(grid, 300, 200));
[Link]("Login"); [Link]();
}
public static void main(String[] args) { launch(args); }
}

Q4. List out JavaFX UI controls and explain any one in detail 3 Marks

JavaFX UI Controls:
• Label, Button, TextField, PasswordField, TextArea
• CheckBox, RadioButton, ToggleButton
• ComboBox, ChoiceBox, ListView, TreeView
• Slider, ScrollBar, ProgressBar, ProgressIndicator
• DatePicker, ColorPicker, Spinner

Button (in detail):


A clickable button control. Use setOnAction() to handle clicks.
Button btn = new Button("Click Me");
[Link]("-fx-background-color: blue; -fx-text-fill: white;");
[Link](e -> [Link]("Button clicked!"));
Q5. Demonstrate animation effect in JavaFX 4 Marks

Using TranslateTransition to move a shape:


import [Link].*;
import [Link];
import [Link];
// Inside start() method:
Circle circle = new Circle(30, [Link]);
TranslateTransition tt = new TranslateTransition([Link](2), circle);
[Link](0);
[Link](200);
[Link]([Link]);
[Link](true);
[Link]();

Other animations: FadeTransition (opacity), ScaleTransition (size), RotateTransition (rotation)

Q6. Explain the architecture of JavaFX 7 Marks

JavaFX Architecture Layers:

1. JavaFX Public API (Top layer):


The classes you write: Application, Stage, Scene, controls, shapes, animations, etc.

2. Scene Graph:
A hierarchical tree structure of nodes (like a DOM). Every visual element is a Node. Root → Parent
nodes → Leaf nodes.

3. Quantum Toolkit:
Connects the public API to the graphics engine below.

4. Prism (Graphics Engine):


Renders 2D/3D graphics. Uses hardware acceleration (DirectX/OpenGL) when available, falls back to
software rendering.

5. Glass Windowing Toolkit:


Handles windows, events (mouse, keyboard), timers at the OS level.

6. Media Engine:
Handles audio and video playback.

7. Web Engine:
Renders HTML5/CSS3/JavaScript content inside JavaFX.
Key Flow:
User Input → Glass → Quantum → Scene Graph → Prism → Screen
— END OF SOLUTIONS —
BE04000231 | Object Oriented Programming | GIDC Degree Engineering College

Faculty: Dr. Archana Nayak | Ms. Bhavisha Patel

You might also like