OOP Java Complete Solutions
OOP Java Complete Solutions
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
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");
}
}
Type conversion means converting a value from one data type to another. In Java, there are two types:
Q5. What are the data-types and operators available in Java? 7 Marks
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
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.
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).
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.
Flow:
Source Code (.java) → Java Compiler (javac) → Bytecode (.class) → JVM → Machine Code → Output
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);
}
}
}
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
Output: 1 2 3 4 6 7
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
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
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
}
}
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
(See Q1 and Q4 of this unit for complete explanation with examples. Combined answer below:)
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
}
}
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]();
}
}
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:
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.
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.
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
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
}
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.
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()
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
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
Q20. Explain all access modifiers and their visibility as class members 7 Marks
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.
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
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
}
}
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
}
}
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
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.
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
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
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.
Q10. Explain Primitive data types and Wrapper class data types 4 Marks
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
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
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
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
Dynamic Binding (Late Binding) means the method call is resolved at RUNTIME rather than compile
time, based on the actual type of the object.
The JVM checks the actual object type at runtime and calls the correct overridden method.
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: 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
}
}
Polymorphism:
'Many forms' – the same method/interface works differently based on the object. Two types: Compile-
time (overloading) and Runtime (overriding).
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); } }
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
Output:
Exception caught: / by zero
Program continues...
Q4. Write method for computing x^y with command line arguments and
7 Marks
handle exceptions
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
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)
}
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");
}
}
}
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]();
}
}
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]());
}
}
}
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]
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
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 { }
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
6. Custom Exception:
class MyException extends Exception { MyException(String msg){super(msg);} }
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
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");
}
}
Thread:
A thread is a lightweight unit of execution within a program. Java supports multithreading – running
multiple threads simultaneously for better performance.
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++;
}
}
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]();
}
}
Step 1: Create a class that extends Thread. Step 2: Override run() method. Step 3: Create object and
call start().
Step 1: Create a class implementing Runnable. Step 2: Override run(). Step 3: Pass to Thread object
and call start().
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.
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
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); }
}
Q6. Explain Color class, Font class, Image and ImageView class in
3 Marks
JavaFX
Q7. Explain concept of inner classes and types with example program 7 Marks
Types:
1. Member Inner Class:
class Outer {
class Inner { void show(){[Link]("Inner class");} }
}
// [Link] obj = new Outer().new Inner();
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.
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]
}
}
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);
}
}
}
Collection Framework:
A set of classes and interfaces in Java for storing and manipulating groups of objects ([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
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]
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()
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
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
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
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.
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