Oop Solution
Oop Solution
programming
1. What is bytecode ? Extension of bytecode. (3 Marks)
Bytecode:
It is not human-readable.
Acts as a bridge between the source code and the machine code.
Extension of Bytecode:
.class
Each class written in Java is compiled into a separate .class file containing the
corresponding bytecode.
These errors occur when the code violates the grammar rules of the
programming language.
Example:
2. Logical Errors:
These errors occur when the program runs without crashing, but produces
incorrect results.
Caused by flaws in the algorithm or incorrect logic used by the programmer.
Not detected by the compiler or JVM.
Example:
3. Runtime Errors:
These errors occur while the program is running, even though it compiled
successfully.
Java is considered platform independent because the Java compiler does not
produce machine code specific to any one platform. Instead, it compiles the source
code (.java) into bytecode (.class file), which is a platform-neutral intermediate code.
This bytecode can run on any operating system or hardware that has a Java
Virtual Machine (JVM) installed.
Summary:
Java is platform independent because of its use of bytecode and the JVM, which
allows the same program to run on different platforms without modification.
Chapter 2 : Selections , Mathematical functions and loops
1. Difference : Nested If - Multiway If or While-Do While. (3/4 Marks)
Can become complex and harder More organized and readable for
Readability
to read. multiple conditions.
while(condition) { ...
Syntax do { ... } while(condition);
}
Use When you want to test before When you want to ensure at least one
Case execution. execution.
2. Describe Keywords With Examples of Its Use : Break & Continue. (IMP - 3/4
Marks)
1. break Keyword:
Purpose:
The break statement is used to terminate a loop or switch statement
immediately.
Usage:
Often used when a certain condition is met and no further iteration is needed.
Example:
if (i == 3) {
}
System.out.println(i);
// Output: 1 2
2. continue Keyword:
Purpose:
The continue statement is used to skip the current iteration of a loop and
proceed to the next iteration.
Usage:
Useful when certain values should be ignored or skipped in a loop.
Example:
if (i == 3) {
}
System.out.println(i);
}
// Output: 1 2 4 5
Aspect Explanation
Class as a The class defines what kind of data and what actions (methods)
Template an object will have.
Object as an The object is a specific copy created from the class, with actual
Instance values stored in memory.
Multiple objects can be created from a single class, each with its
Multiple Objects
own state.
Example:
class Car {
String color;
void drive() {
System.out.println("Car is driving");
}
}
myCar.color = "Red";
myCar.drive(); // Calling method of the class
}
myCar has access to all the methods and variables defined in the Car class.
Use Case: When you want the class/member to be completely open to other
classes.
Example:
System.out.println("Public Method");
Same class ✅
Same package ✅
Subclass ✅
Outside package ✅
🔒 2. private Access Modifier
System.out.println("Private Method");
Same class ✅
❌ Not accessible from:
Other classes ❌
Subclasses ❌
Outside package ❌
o Same class
o Same package
Example:
class MyClass {
System.out.println("Protected Method");
}
}
✅ Can be accessed from:
Same package ✅
Example:
class MyClass {
void display () {
Same class ✅
Same package ✅
❌ Not accessible from:
Different package ❌
3. Define & Explain Constructors & its Types. (IMP - 4/7 Marks)
✅ Definition of Constructor:
✅ Key Features:
Has the same name as the class.
🧱 Syntax Example:
class Car {
String model;
// Constructor
Car(String m) {
model = m;
}
java
CopyEdit
1. Default Constructor
Example:
class Bike {
Bike() {
System.out.println("Default Constructor Called");
2. Parameterized Constructor
A constructor that accepts parameters to initialize fields with specific values.
Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
3. Copy Constructor (Not built-in like C++, but can be defined manually)
Initializes a new object by copying values from another object of the same
class.
Example:
class Person {
String name;
Person(String n) {
name = n;
}
// Copy constructor
Person(Person p) {
name = p.name;
}
(Other Concepts of This Chapters Are Used in Programs Only
1. Abstraction
Definition:
Abstraction is the process of hiding the internal implementation details and showing
only the relevant information to the user. It helps in reducing complexity by focusing
only on what an object does instead of how it does it.
Purpose:
To hide complexity and allow the programmer to focus on interactions at a higher
level.
How to Achieve in Java:
Using interfaces
Example:
void start() {
In the above example, the user doesn’t need to know how start() works internally;
they.
just call it
2. Encapsulation
Definition:
Encapsulation is the technique of bundling the data (variables) and methods that
operate on that data into a single unit, i.e., a class. It also involves restricting access
to some of the object’s components, which is a way of achieving data hiding.
Purpose:
Provide public getter and setter methods to access and update private data.
Example:
class Student {
marks = m;
return marks;
In this case, direct access to marks is not allowed. It must go through the get and set
methods, allowing control and validation.
3. Inheritance
Definition:
Inheritance is a mechanism where a child class (subclass) can inherit properties and
behaviors (fields and methods) from a parent class (superclass). It promotes code
reuse, and allows one class to build upon another.
Purpose:
To avoid code duplication and establish a relationship between classes.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
(Note: Java does not support multiple inheritance through classes directly to
avoid ambiguity, but interfaces can be used.)
Example:
class Animal {
void eat() {
void bark() {
}
}
4. Polymorphism
Definition:
Polymorphism means “many forms”. It allows the same method or behavior to act
differently based on the object or the context. It increases flexibility and reusability of
code.
Example:
class Calculator {
return a + b;
return a + b;
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
void sound() {
System.out.println("Cat meows");
}
Here, the method sound() behaves differently based on the object that calls it.
2. Describe Keywords With Examples of Its Use : This & Super (IMP - 3/4
Marks)
1. this Keyword
Purpose:
Refers to the current instance of the class where it is used.
Common Uses:
Example:
class Student {
int id;
String name;
this.name = name;
void display() {
2. super Keyword
Purpose:
Refers to the immediate parent class of the current object.
Common Uses:
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
void sound() {
Dog() {
super.sound() calls the parent class’s sound() method before executing the
subclass’s own code.
1. Method Overloading
Definition:
Method Overloading occurs when multiple methods in the same class have the same
name but different parameter lists (different type, number, or order of parameters). It
is a form of compile-time polymorphism.
Purpose:
To increase the readability of the program by allowing the same method name to
perform different tasks based on parameters.
Key Points:
Same or different return types (return type alone can’t differentiate methods)
Example:
class Calculator {
return a + b;
return a + b + c;
}
return a + b;
}
}
2. Method Overriding
Definition:
Method Overriding happens when a subclass provides a specific implementation of a
method that is already defined in its superclass. It is a form of run-time
polymorphism.
Purpose:
To allow a subclass to modify or extend the behavior of a superclass method.
Key Points:
Same method name
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
@Override
void sound() {
System.out.println("Dog barks");
}
}
At runtime, the JVM calls the overridden method in Dog because the object is
of type Dog.
4. Describe : Wrapper Class Data Types With Example. (IMP - 3/4 Marks)
byte Byte
short Short
int Integer
Primitive Type Wrapper Class
long Long
float Float
double Double
char Character
boolean Boolean
}
}
Occurs when multiple methods have the same name but different parameters
(different type, number, or order) in the same class.
The method to call is decided at compile time based on the method signature.
Example:
class MathOperation {
return a + b;
return a + b;
Here, the compiler decides which add() method to call based on argument types.
The method to call is decided at run time depending on the object type (not
reference type).
Example:
java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal makes sound");
void sound() {
System.out.println("Dog barks");
}
}
}
}
What is an Exception?
An exception is an unexpected event or error that occurs during the execution of a
program, disrupting the normal flow of instructions. It can happen due to:
Division by zero
Network failure
Exception handling is the mechanism to handle runtime errors so that the program
continues to run smoothly without crashing. Java provides a robust framework to
detect, catch, and handle exceptions using special blocks of code.
1. try block
Contains the code that might throw an exception.
2. catch block
Handles the exception thrown in the try block.
3. finally block (optional)
Executes code after try-catch regardless of exception occurrence (used for
cleanup).
4. throw statement
Used to explicitly throw an exception.
5. throws clause
Declares exceptions that a method can throw.
// risky code
} catch (ExceptionType e) {
// handle exception
} finally {
Example:
try {
int a = 10, b = 0;
} finally {
Output:
Explanation:
throw new
Example void method() throws IOException
ArithmeticException();
Checked
At compile time At runtime
When?
NullPointerException,
Examples IOException, SQLException
ArithmeticException
Can have both normal and Only abstract methods (till Java 7),
Methods
abstract default/static allowed from Java 8
🔸 What is Try-Catch?
🔸 Basic Structure:
try {
} catch (ExceptionType e) {
try {
int a = 10;
int b = 0;
} catch (ArithmeticException e) {
try {
int[] arr = {1, 2, 3};
} catch (ArrayIndexOutOfBoundsException e) {
try {
String s = "abc";
}
4. Describe Keywords : Throw, Throws, Final, Finally, Finalize. (IMP - 3/4
Marks). (IMP - 7 Marks)
🔸 1. throw keyword
✅ Syntax:
🔸 2. throws keyword
Used in method declaration to tell the caller that this method might throw an
exception.
✅ Syntax:
🔸 3. final keyword
✅ Usage:
✅ Example:
🔸 4. finally block
✅ Syntax:
// cleanup code
5. What is Abstract class? Describe usage of Abstract class with one example.
(IMP - 7 Marks)
An abstract class is a class that cannot be instantiated (you can't create its
object).
It can have:
When you want to define a common structure or behavior for all child
classes.
🔸 Syntax:
void method2() {
// normal method
}
🔸 Example:
// Abstract class
void eat() {
}
}
// Subclass
void sound() {
System.out.println("Dog barks");
}
}
// Main class
}
🔸 Explanation:
Abstract class helps in providing a common design for all animal types.
Abstract Window
Full Form - -
Toolkit
🔸 What is JavaFX?
JavaFX is a modern Java library for building Graphical User Interface (GUI)
applications.
It supports rich features like animations, charts, and media.
To create a JavaFX application, you must extend the Application class and override
the start() method.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
@Override
// Create a label
root.getChildren().add(label);
primaryStage.setScene(scene);
Part Description
Application class Main class for JavaFX apps; you must extend it
start() method Entry point of the JavaFX GUI code (like main() in console)
✅ Output:
Layout panes are used to arrange UI elements (buttons, labels, etc.) in JavaFX.
HBox
Arranges elements horizontally (in a row)
n
🔹 Benefits of JavaFX:
1. ✅ Modern UI Design:
JavaFX supports CSS styling, animations, 3D graphics, and rich media.
3. ✅ Cross-Platform:
JavaFX applications run on Windows, macOS, and Linux.
4. ✅ FXML Support:
Separate UI design from business logic using XML-based FXML files.
5. ✅ Multimedia Support:
Built-in support for audio, video, and charts.
6. ✅ Hardware Acceleration:
Uses GPU rendering, so it's fast and efficient.
4. What do you understand by event source and event object? Explain how to
register an event handler object and how to implement a handler interface?
(IMP -7 Marks)
Clicking a button
Pressing a key
Moving a mouse
🔸 1. Event Source:
✅ Example:
java
CopyEdit
🔸 2. Event Object:
When an event occurs, JavaFX creates an event object that contains details
about the event.
✅ Example:
java
CopyEdit
🔸 3. Event Handler:
An EventHandler is an interface used to handle events.
✅ Syntax:
java
CopyEdit
@Override
};
You must register the event handler to the event source using the setOnAction()
method.
✅ Example:
java
CopyEdit
java
CopyEdit
btn.setOnAction(e -> {
System.out.println("Button clicked!");
});
java
CopyEdit
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Click Me");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
});
root.getChildren().add(btn);
primaryStage.setScene(scene);
primaryStage.show();
}
launch(args);
}
Control Description
Layout panes are used to arrange nodes (like buttons, labels) in a window.
Pane Description
java
CopyEdit
Byte-
Character-Oriented
Aspect Oriented
Stream
Stream
Used for handling binary data Used for handling text data
Use
(images, audio, video) (characters, strings)
2. Explain binary I/O classes. Demonstrate java file I/O with any I/O class to
read a text file. or Explain text I/O classes. Demonstrate java file I/O with any
I/O class to read a text file. (IMP - 7 Marks)
Java provides Reader and Writer classes for character-based input and
output.
These classes handle text data and use Unicode encoding automatically.
Common classes for reading text files:
o FileReader
o BufferedReader
Common classes for writing text files:
o FileWriter
o BufferedWriter
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try {
String line;
} catch (IOException e) {
🔹 Explanation:
3.What are the differences between text I/O and binary I/O ? (IMP - 3/4 Marks)
Reads/Writes characters or
Data Type Reads/Writes raw bytes or binary data
text data
Used for text files (e.g., .txt, Used for binary files (e.g., images,
Usage
.csv) videos)
They provide methods to read and write primitive data types (int, float, double,
boolean, etc.) in a machine-independent way.
🔸 DataOutputStream:
🔸 DataInputStream:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
} catch (IOException e) {
} catch (IOException e) {
System.out.println("Read Error: " + e.getMessage());
The Iterator interface provides a way to access elements one by one from a
collection (like ArrayList, LinkedList) without exposing its internal structure.
Examples: ArrayList,
Implementation Examples: HashSet, TreeSet
LinkedList
Elements accessed by
Access No index-based access
index
Chapter 12 : Concurrency
1. Explain thread life cycle. (3 Marks)
A thread in Java goes through five main states during its life cycle:
2. Runnable State
o After calling start(), the thread is ready to run and waiting for CPU time.
3. Running State
Summary in brief:
State Description
What is a Package?
javac package_name/FileName.java
4.Run the Java Program:
Use command:
java package_name.FileName
Example:
package mypackage;
Summary:
Step Description
Save inside
2. Save file in folder
mypackage folder
javac
3. Compile
mypackage/Hello.java
Override the run() method with the code you want the thread to execute.
Create an object of your class and call start() to run the thread.
Example:
}
}
public class TestThread1 {
Create a Thread object by passing an instance of your class, then call start().
Example:
class MyRunnable implements Runnable {
Summary:
Example Class to
Method How It Works
Extend/Implement