0% found this document useful (0 votes)
7 views49 pages

Oop Solution

The document provides an introduction to Java programming, covering concepts such as bytecode, error types (syntax, logical, runtime), and the platform independence of Java through the JVM. It explains control structures like nested if, multiway if, while, and do-while loops, as well as keywords like break and continue. Additionally, it discusses object-oriented principles including classes, objects, access modifiers, constructors, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism.

Uploaded by

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

Oop Solution

The document provides an introduction to Java programming, covering concepts such as bytecode, error types (syntax, logical, runtime), and the platform independence of Java through the JVM. It explains control structures like nested if, multiway if, while, and do-while loops, as well as keywords like break and continue. Additionally, it discusses object-oriented principles including classes, objects, access modifiers, constructors, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism.

Uploaded by

Raj Savaliya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 1 : Introduction to java and elementary

programming
1. What is bytecode ? Extension of bytecode. (3 Marks)

Bytecode:

Bytecode is an intermediate, platform-independent code generated by the Java


compiler after compiling a Java source file (.java). It is a set of instructions that can
be executed by the Java Virtual Machine (JVM). Bytecode allows Java programs to
be "write once, run anywhere", meaning the same bytecode can run on any device
that has a JVM.

 It is not human-readable.

 Acts as a bridge between the source code and the machine code.

 Ensures security and portability.

Extension of Bytecode:

The file extension for bytecode files in Java is:

.class
Each class written in Java is compiled into a separate .class file containing the
corresponding bytecode.

2. Describe Syntax errors (Compile), Logical errors, Runtime errors. (4 Marks)

1. Syntax Errors (Compile-Time Errors):

 These errors occur when the code violates the grammar rules of the
programming language.

 Detected during compilation.

 Common causes: missing semicolons, incorrect use of keywords, unmatched


brackets, etc.

 Example:

int x = 10 // missing semicolon

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:

int sum = a - b; // Intended to add but used subtraction

3. Runtime Errors:
 These errors occur while the program is running, even though it compiled
successfully.

 Caused by invalid operations like dividing by zero, accessing invalid array


index, or null references.

 Detected by JVM at runtime.


 Example:

int result = 10 / 0; // Division by zero

3. Why Java is Platform Independent ? Use of JVM ? (3 Marks)

Why Java is Platform Independent:

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.

 Hence, Java follows the principle:


“Write Once, Run Anywhere.”

Use of JVM (Java Virtual Machine):

 JVM is a virtual machine that executes Java bytecode.

 It provides an execution environment that abstracts away the underlying


hardware and OS.

 Converts bytecode into machine-specific code at runtime.

 Handles memory management, garbage collection, security, and exception


handling.

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)

Option A: Nested If vs Multiway If

Feature Nested If Multiway If (If-Else If)

If statements placed inside another Uses multiple else-if conditions in


Structure
if block. a single block.

Useful when conditions depend on Useful when checking multiple


Usage
previous conditions. unrelated conditions.

Can become complex and harder More organized and readable for
Readability
to read. multiple conditions.

Example if (a > 0) { if (b > 0) { ... } } if (a > 0) { ... } else if (b > 0) { ... }

Option B: While vs Do-While Loop

Feature While Loop Do-While Loop

Condition Condition is checked before loop Condition is checked after loop


Check body executes. body executes.

May not execute at all if condition is Executes the body at least


Execution
false. once.

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:

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

if (i == 3) {

break; // exits the loop when i is 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:

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

 if (i == 3) {

 continue; // skips printing when i is 3

 }
 System.out.println(i);

 }

 // Output: 1 2 4 5

(Other Concepts of This Chapters Are Used in Programs Only)

Chapter 3 : Methods and Arrays


(Concepts of This Chapters Are Used in Programs Only)

Chapter 4 : Objects and Classes


1. Describe the relationship between an object and its defining class. (IMP - 3
Marks)

Definition of Class and Object:

 A class is a blueprint or template that defines the properties (data/variables)


and behaviors (methods/functions) of objects.

 An object is a real instance of a class, created in memory during program


execution.

Relationship Between Object and Class:

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.

Objects use the class’s methods to perform actions and


Interaction
access/modify their own data.

Example:

class Car {

String color;

void drive() {

System.out.println("Car is driving");

}
}

public class Main {

public static void main(String[] args) {

Car myCar = new Car(); // myCar is an object of class Car

myCar.color = "Red";
myCar.drive(); // Calling method of the class
}

 Here, Car is the class, and myCar is the object.

 myCar has access to all the methods and variables defined in the Car class.

2. Discuss public, private, protected and default access modifiers with


examples. (IMP - 4/7 Marks)

Access modifiers in Java determine which classes or methods can access a


particular variable, method, or class. There are four main access modifiers:

🔓 1. public Access Modifier

 Access Level: Accessible from anywhere in the program.

 Use Case: When you want the class/member to be completely open to other
classes.

Example:

public class MyClass {

public int number = 10;

public void display() {

System.out.println("Public Method");

✅ Can be accessed from:

 Same class ✅

 Same package ✅

 Subclass ✅

 Outside package ✅
🔒 2. private Access Modifier

 Access Level: Accessible only within the same class.

 Use Case: Used for data hiding and encapsulation.


Example:

public class MyClass {

private int number = 10;

private void show () {

System.out.println("Private Method");

✅ Can be accessed from:

 Same class ✅
❌ Not accessible from:

 Other classes ❌

 Subclasses ❌

 Outside package ❌

🛡️ 3. protected Access Modifier

 Access Level: Accessible in:

o Same class
o Same package

o Subclasses (even if in different packages)

Example:

class MyClass {

protected void display() {

System.out.println("Protected Method");
}
}
✅ Can be accessed from:

 Same package ✅

 Subclass in different package ✅


❌ Not accessible from:

 Non-subclass outside package ❌

⚙️ 4. Default (No Modifier)

 Access Level: Accessible only within the same package.


 If no access modifier is specified, it's called package-private or default
access.

Example:
class MyClass {

void display () {

System.out.println("Default Access Method");

✅ Can be accessed from:

 Same class ✅

 Same package ✅
❌ Not accessible from:

 Different package ❌

 Subclasses in other packages ❌

3. Define & Explain Constructors & its Types. (IMP - 4/7 Marks)

✅ Definition of Constructor:

A constructor in Java is a special method used to initialize objects. It is called


automatically when an object is created.

✅ Key Features:
 Has the same name as the class.

 No return type, not even void.

 Can be overloaded (multiple constructors with different parameters).

🧱 Syntax Example:

class Car {

String model;

// Constructor

Car(String m) {

model = m;
}

java

CopyEdit

Car myCar = new Car("Honda"); // Constructor is called automatically

🔄 Types of Constructors in Java:

1. Default Constructor

 A constructor with no parameters.

 If not written explicitly, Java provides a default one automatically.

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

Chapter 5 : Object oriented thinking


1. Four Pillars of OOP : Abstraction, Encapsulation, Inheritence,
Polymorphism. (IMP - 3/4/7 Marks)

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 abstract classes

 Using interfaces

Example:

abstract class Vehicle {

abstract void start(); // only declares method, no implementation

class Car extends Vehicle {

void start() {

System.out.println("Car is starting with key...");

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:

 To protect data from outside interference.

 To implement security and controlled access.

How to Achieve in Java:

 Declare variables as private.

 Provide public getter and setter methods to access and update private data.

Example:
class Student {

private int marks; // data is hidden from outside

public void setMarks(int m) {

marks = m;

public int getMarks() {

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.

Types of Inheritance in Java:

 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() {

System.out.println("This animal eats food.");


}

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

}
}

Here, Dog inherits the eat() method from Animal.

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.

Types of Polymorphism in Java:

 Compile-Time Polymorphism (Method Overloading)

 Run-Time Polymorphism (Method Overriding)


a) Compile-Time Polymorphism (Method Overloading):
Same method name with different parameters in the same class.

Example:

class Calculator {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

b) Run-Time Polymorphism (Method Overriding):


Same method name and signature in parent and child classes, but the child provides
its own implementation.

Example:

class Animal {

void sound() {
System.out.println("Animal makes a sound");

class Cat extends Animal {

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:

o To refer to instance variables when they are shadowed by method


parameters or local variables.

o To call another constructor in the same class (constructor


chaining).

o To pass the current object as a parameter.

 Example:

class Student {

int id;
String name;

Student(int id, String name) {

this.id = id; // 'this.id' refers to instance variable

this.name = name;

void display() {

System.out.println("ID: " + this.id + ", Name: " + this.name);

 Here, this.id distinguishes the instance variable id from the parameter


id.

2. super Keyword

 Purpose:
Refers to the immediate parent class of the current object.
 Common Uses:

o To call the parent class constructor from the subclass.

o To access parent class methods or variables that are overridden or


hidden in the subclass.

 Example:

class Animal {

void sound() {
System.out.println("Animal makes a sound");

class Dog extends Animal {

void sound() {

super.sound(); // Calls parent class method


System.out.println("Dog barks");

Dog() {

super(); // Calls parent class constructor (optional, if parent has no-arg


constructor)

 super.sound() calls the parent class’s sound() method before executing the
subclass’s own code.

3. Define Concept of Method Overloading and Method Overriding with Examples.


(IMP - 4/7 Marks)

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 method name

 Different parameters (type or number)

 Same or different return types (return type alone can’t differentiate methods)

Example:

class Calculator {

// Add two integers


int add(int a, int b) {

return a + b;

// Add three integers

int add(int a, int b, int c) {

return a + b + c;
}

// Add two doubles

double add(double a, double b) {

return a + b;

public class Test {

public static void main(String[] args) {


Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Calls add(int, int)

System.out.println(calc.add(5, 10, 15)); // Calls add(int, int, int)

System.out.println(calc.add(5.5, 6.5)); // Calls add(double, double)

}
}

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

 Same parameter list (signature)

 Same return type (or subtype)

 Method in superclass must be inherited (non-private)

Example:

class Animal {

void sound() {
System.out.println("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

System.out.println("Dog barks");
}
}

public class Test {

public static void main(String[] args) {


Animal myAnimal = new Dog();

myAnimal.sound(); // Calls Dog's overridden method

 Here, Dog overrides the sound() method of Animal.

 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)

What is a Wrapper Class?


In Java, Wrapper Classes are used to wrap primitive data types (int, char, double,
etc.) into objects. This is important because Java’s collection classes (like ArrayList,
HashMap) work only with objects, not primitives.

Why Wrapper Classes?


 To convert primitive data types to objects.

 To use primitives in collections (e.g., ArrayList<Integer> instead of


ArrayList<int>).

 Provide utility methods to convert between types, parse strings, etc.

List of Primitive Types and Their Wrapper Classes

Primitive Type Wrapper Class

byte Byte

short Short

int Integer
Primitive Type Wrapper Class

long Long

float Float

double Double

char Character

boolean Boolean

Example: Using Wrapper Class


public class WrapperExample {

public static void main(String[] args) {

int num = 10; // primitive

Integer wrappedNum = Integer.valueOf(num); // boxing: primitive to object

// Auto-boxing (automatic conversion by Java)

Integer autoWrapped = num;

// Unboxing (object to primitive)

int primitiveNum = wrappedNum.intValue();

int autoUnboxed = autoWrapped;

System.out.println("Wrapped Integer: " + wrappedNum);


System.out.println("Primitive int after unboxing: " + primitiveNum);

}
}

Auto-boxing & Unboxing

 Auto-boxing: Automatic conversion of primitive to wrapper object.

 Unboxing: Automatic conversion of wrapper object to primitive.


5. Explain Types of Polymorphism. (IMP - 3/4 Marks)

Polymorphism means “many forms” — the ability of a method or object to take


multiple forms.

In Java, polymorphism is mainly of two types:

1. Compile-Time Polymorphism (Static Polymorphism)


 Also called Method Overloading.

 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 {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

Here, the compiler decides which add() method to call based on argument types.

2. Run-Time Polymorphism (Dynamic Polymorphism)


 Also called Method Overriding.

 Occurs when a subclass provides its own implementation of a method already


defined in its superclass.

 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");

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");
}
}

public class Test {

public static void main(String[] args) {

Animal a = new Dog();

a.sound(); // Calls Dog’s overridden method at runtime

}
}

Chapter 6 : Exception Handling, I/O, abstract classes and


interfaces
1. What is an Exception? Explain Exception handling in JAVA with the help of
example. (IMP - 7 Marks)

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:

 Invalid user input

 File not found

 Division by zero

 Network failure

 Accessing invalid array index, etc.


Example:
Trying to divide a number by zero causes an ArithmeticException.

Exception Handling in Java

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.

Key Components of Exception Handling:

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.

Exception Handling Flow


try {

// risky code
} catch (ExceptionType e) {
// handle exception

} finally {

// cleanup code (optional)

Example:

public class ExceptionExample {

public static void main(String[] args) {

try {

int a = 10, b = 0;

int result = a / b; // This will throw ArithmeticException


System.out.println("Result: " + result);
} catch (ArithmeticException e) {

System.out.println("Error: Division by zero is not allowed.");

} finally {

System.out.println("Execution of try-catch block finished.");

Output:

Error: Division by zero is not allowed.

Execution of try-catch block finished.

Explanation:

 The division a / b throws an ArithmeticException.


 The catch block catches this exception and handles it by printing an error
message.
 The finally block executes no matter what, useful for closing resources.
Benefits of Exception Handling:

 Prevents program crashes.

 Separates error-handling code from regular code.


 Provides a way to propagate errors up the call stack.

 Helps in debugging by providing detailed error information.

2. Difference : Throw - Throws or Checked - Unchecked Exceptions or Abstract


class - Interface. (Any One Fixed : 3/4 Marks)

✅ 1. Difference between throw and throws:

Point throw throws

Used To declare that a method might throw an


To actually throw an exception
For exception

Used In Inside method body In method declaration (signature)

Throws Only one exception at a time Can declare multiple exceptions

throw new
Example void method() throws IOException
ArithmeticException();

✅ 2. Difference between Checked and Unchecked Exceptions:

Point Checked Exception Unchecked Exception

Checked
At compile time At runtime
When?

Must Handle? Yes, using try-catch or throws No, optional to handle

NullPointerException,
Examples IOException, SQLException
ArithmeticException

External reasons (e.g., file not Programming mistakes (e.g., divide


Caused By
found) by 0)
✅ 3. Difference between Abstract Class and Interface:

Point Abstract Class Interface

Can have both normal and Only abstract methods (till Java 7),
Methods
abstract default/static allowed from Java 8

All variables are public static final


Variables Can have any variables
(constants)

Can be extended by one


Inheritance One class can implement many interfaces
class only

Constructors Can have constructors Cannot have constructors

When classes share


Use When? To define a contract for multiple classes
common behavior

3. Demonstrate Use of Try Catch Block by Catching given Exceptions. (IMP - 7


Marks)

🔸 What is Try-Catch?

 In Java, a try-catch block is used to handle errors (exceptions) that happen


during program execution.

 It prevents the program from crashing when something goes wrong.

🔸 Basic Structure:

try {

// Code that may cause an error

} catch (ExceptionType e) {

// Code to handle the error

🔸 Example 1: Divide by Zero (ArithmeticException)

public class Example1 {

public static void main(String[] args) {

try {
int a = 10;
int b = 0;

int c = a / b; // This will cause an error

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero!");


}

🔸 Example 2: Array Index Error (ArrayIndexOutOfBoundsException)

public class Example2 {

public static void main(String[] args) {

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

System.out.println(arr[5]); // Invalid index

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array index is wrong!");

🔸 Example 3: Wrong Number Format (NumberFormatException)

public class Example3 {

public static void main(String[] args) {

try {

String s = "abc";

int num = Integer.parseInt(s); // Not a number


} catch (NumberFormatException e) {

System.out.println("Not a valid number!");

}
4. Describe Keywords : Throw, Throws, Final, Finally, Finalize. (IMP - 3/4
Marks). (IMP - 7 Marks)

🔸 1. throw keyword

 Used to manually throw an exception in Java.

 It is written inside a method or block.

✅ Syntax:

throw new ExceptionType("Error Message");

🔸 2. throws keyword

 Used in method declaration to tell the caller that this method might throw an
exception.

 It is used with checked exceptions.

✅ Syntax:

void myMethod() throws IOException {


// code

🔸 3. final keyword

 Used to make something unchangeable.

 Can be used with variables, methods, or classes.

✅ Usage:

 Final variable → constant value (cannot be changed)

 Final method → cannot be overridden

 Final class → cannot be extended

✅ Example:

final int x = 10; // Constant


final class Animal {} // Can't be subclassed

🔸 4. finally block

 Used in exception handling.

 It always runs after try-catch, whether an exception occurs or not.


 Used for cleanup code like closing files or connections.
🔸 5. finalize() method

 A method that is called by the Garbage Collector before destroying an


object.

 It is used to clean up resources (like closing files, connections, etc.).

✅ Syntax:

protected void finalize() throws Throwable {

// cleanup code

5. What is Abstract class? Describe usage of Abstract class with one example.
(IMP - 7 Marks)

🔸 What is an Abstract Class in Java?

 An abstract class is a class that cannot be instantiated (you can't create its
object).

 It is used as a base class for other classes.

 It can have:

o Abstract methods (without body)


o Normal methods (with body)

 It is declared using the abstract keyword.

🔸 Why Use Abstract Class?

 When you want to define a common structure or behavior for all child
classes.

 Used when some methods should be implemented by child classes, but


some can be shared.

🔸 Syntax:

abstract class ClassName {

abstract void method1(); // abstract method

void method2() {
// normal method
}

🔸 Example:

// Abstract class

abstract class Animal {

abstract void sound(); // abstract method

void eat() {

System.out.println("Animals eat food.");

}
}

// Subclass

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

}
}

// Main class

public class Test {

public static void main(String[] args) {

Dog d = new Dog();

d.sound(); // Output: Dog barks


d.eat(); // Output: Animals eat food.

}
🔸 Explanation:

 Animal is an abstract class with:

o One abstract method: sound()


o One normal method: eat()

 Dog is a subclass that must override the abstract method sound().

 Abstract class helps in providing a common design for all animal types.

(One Program Fixed From Here)

Chapter 7 : JAVAFX basics and Event-driven programming


and animations
1. Compare JavaFX with Swing and AWT. (IMP - 3/4 Marks)

Feature AWT Swing JavaFX

Abstract Window
Full Form - -
Toolkit

Oldest GUI toolkit in Improved version of Modern GUI toolkit


API Level
Java AWT (since Java 8)

System-dependent Custom (uses Java's Modern, rich UI (CSS


Look & Feel
(OS style) look and feel) support)

Heavyweight (OS- Lightweight (Java- Lightweight with


Components
based) based) advanced controls

Basic UI, limited Rich UI: charts,


Graphics Better UI than AWT
graphics animations, media

Better layout Uses FXML & CSS for


Layout Manual, less flexible
managers layout

Multimedia Built-in support for


Very limited Limited
Support audio, video

Threading Basic Event Single-threaded Improved threading


Model Handling (EDT) (JavaFX thread)

Simplest and most


Ease of Use Difficult Easier than AWT
flexible
2. Illustrate basic structure of JavaFX program. (IMP - 4/7 Marks)

🔸 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.

🔸 Basic Structure of JavaFX Program:

To create a JavaFX application, you must extend the Application class and override
the start() method.

✅ Basic JavaFX Program Example:

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.layout.StackPane;

import javafx.stage.Stage;

public class HelloJavaFX extends Application {

// Main method (optional from Java 11+)

public static void main(String[] args) {

launch(args); // Launches the JavaFX app


}

// This method is called when the app starts

@Override

public void start(Stage primaryStage) {

// Create a label

Label label = new Label("Hello, JavaFX!");


// Add label to layout

StackPane root = new StackPane();

root.getChildren().add(label);

// Create a scene and set it to the stage

Scene scene = new Scene(root, 300, 200);

// Set stage (window) properties

primaryStage.setTitle("My First JavaFX App");

primaryStage.setScene(scene);

primaryStage.show(); // Show the window


}
}

🔸 Explanation of Main Parts:

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)

Stage The main window of the application

Scene The content area inside the window

StackPane A layout to place controls (like buttons, labels, etc.)

Label A simple control to display text

✅ Output:

A window opens showing:


"Hello, JavaFX!"

3. Enlist various Layout panes available in JavaFX? Discuss JavaFX benefits?


(IMP - 4 Marks)
🔹 Layout Panes in JavaFX:

Layout panes are used to arrange UI elements (buttons, labels, etc.) in JavaFX.

✅ Common JavaFX Layout Panes:

Layout Pane Description

HBox
Arranges elements horizontally (in a row)
n

VBox Arranges elements vertically (in a column)

BorderPane Divides screen into top, bottom, left, right, center

GridPane Arranges elements in a grid (rows and columns)

Places elements in a flowing style (left to right, top to


FlowPane
bottom)

StackPane Stacks elements on top of each other

AnchorPane Positions elements using anchors (top, bottom, etc.)

TilePane Like GridPane but cells are all same size

🔹 Benefits of JavaFX:

1. ✅ Modern UI Design:
JavaFX supports CSS styling, animations, 3D graphics, and rich media.

2. ✅ Scene Builder Support:


You can design GUIs visually using JavaFX Scene Builder (drag-and-drop
tool).

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)

🔹 What is Event Handling in JavaFX?

Event handling in JavaFX is the process of responding to user actions, like:

 Clicking a button

 Pressing a key

 Moving a mouse

🔸 1. Event Source:

 The component (control) that generates the event.

 Example: A Button is an event source when it is clicked.

✅ Example:

java
CopyEdit

Button btn = new Button("Click Me"); // btn is the event source

🔸 2. Event Object:

 When an event occurs, JavaFX creates an event object that contains details
about the event.

 Example: ActionEvent, MouseEvent, KeyEvent, etc.

✅ Example:

java

CopyEdit

public void handle(ActionEvent e) {

// 'e' is the event object

🔸 3. Event Handler:
An EventHandler is an interface used to handle events.

✅ Syntax:

java
CopyEdit

EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {

@Override

public void handle(ActionEvent e) {

// Action when event occurs

};

🔸 4. Registering Event Handler:

You must register the event handler to the event source using the setOnAction()
method.

✅ Example:

java

CopyEdit

btn.setOnAction(handler); // Registers the handler to the button


Or directly using a lambda:

java

CopyEdit

btn.setOnAction(e -> {

System.out.println("Button clicked!");

});

🔸 5. Implementing EventHandler Interface (Full Example):

✅ Complete JavaFX Program:

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;

public class MyEventExample extends Application {

@Override
public void start(Stage primaryStage) {
Button btn = new Button("Click Me");

// Event handler implementation

btn.setOnAction(new EventHandler<ActionEvent>() {

@Override

public void handle(ActionEvent e) {

System.out.println("Button was clicked!");


}

});

StackPane root = new StackPane();

root.getChildren().add(btn);

Scene scene = new Scene(root, 300, 200);


primaryStage.setTitle("Event Handling Example");

primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {

launch(args);
}

(One Program Fixed From Here)

Chapter 8 : JAVAFX UI controls and multimedia


1. List any four UI controls in JavaFX & List any two Panes for Containing and
Organizing Nodes. (IMP - 3/4 Marks)

🔹 Four Common UI Controls in JavaFX:

UI controls are used to interact with the user.

Control Description

Button A clickable button

Label Displays non-editable text

TextField Allows user to enter a single line of text

CheckBox Allows user to select/unselect an option

🔹 Two Layout Panes in JavaFX:

Layout panes are used to arrange nodes (like buttons, labels) in a window.

Pane Description

VBox Arranges nodes vertically (top to bottom)

HBox Arranges nodes horizontally (left to right)

✅ Example (Optional in exam):

java
CopyEdit

VBox layout = new VBox(); // Vertical layout

Button btn = new Button("Click"); // UI Control

layout.getChildren().add(btn); // Add button to layout

Chapter 9 : Binary I/O ,Recursion and Generics


1. Differentiate between a byte oriented and a characteroriented stream. (IMP -
3/4 Marks)

Byte-
Character-Oriented
Aspect Oriented
Stream
Stream

Reads/writes data in bytes (8 Reads/writes data in characters


Data Type
bits) (16 bits)

Used for handling binary data Used for handling text data
Use
(images, audio, video) (characters, strings)

Classes InputStream, OutputStream and their Reader, Writer and their


Example subclasses subclasses

Better for text data due to


Efficiency More efficient for binary data
automatic encoding support

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)

🔹 Text I/O Classes in Java

 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

🔹 Why Use BufferedReader?

 BufferedReader wraps around FileReader to read text efficiently, line by line.

 It reduces the number of I/O operations by buffering.

🔹 Example: Read a Text File Using BufferedReader

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ReadFileExample {

public static void main(String[] args) {

String filePath = "sample.txt"; // File to read

try {

// Create FileReader & BufferedReader objects


FileReader fr = new FileReader(filePath);

BufferedReader br = new BufferedReader(fr);

String line;

// Read file line by line until end of file

while ((line = br.readLine()) != null) {


System.out.println(line);

// Close the streams


br.close();
fr.close();

} catch (IOException e) {

System.out.println("Error reading file: " + e.getMessage());


}

🔹 Explanation:

 FileReader opens the file for reading.

 BufferedReader reads the file line by line.

 readLine() returns null when the end of the file is reached.


 The program prints each line on the console.

 Streams are closed to free resources.

3.What are the differences between text I/O and binary I/O ? (IMP - 3/4 Marks)

Aspect Text I/O Binary I/O

Reads/Writes characters or
Data Type Reads/Writes raw bytes or binary data
text data

InputStream / OutputStream classes


Classes Reader / Writer classes (e.g.,
(e.g., FileInputStream,
Used FileReader, BufferedReader)
BufferedOutputStream)

Uses character encoding (like


Encoding No encoding, deals directly with bytes
UTF-8, UTF-16) automatically

Used for text files (e.g., .txt, Used for binary files (e.g., images,
Usage
.csv) videos)

Data Handles human-readable


Handles non-text data like images, audio
Handling data
4. Explain DataInputStream and DataOutputStream Classes? Implement a java
program to demonstrate any one of them? (IMP - 7 Marks)

🔹 DataInputStream and DataOutputStream

 These classes are part of Java’s binary I/O system.

 They provide methods to read and write primitive data types (int, float, double,
boolean, etc.) in a machine-independent way.

 Both work with byte streams (InputStream and OutputStream).

🔸 DataOutputStream:

 Writes Java primitive data types to an output stream.

 Common methods: writeInt(), writeDouble(), writeUTF(), etc.

 Used to write binary data to a file or other stream.

🔸 DataInputStream:

 Reads Java primitive data types from an input stream.

 Common methods: readInt(), readDouble(), readUTF(), etc.

 Used to read binary data from a file or other stream.

🔹 Example: Write and Read Data Using DataOutputStream and DataInputStream

import java.io.DataInputStream;
import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class SimpleDataStream {

public static void main(String[] args) {


String file = "data.bin";
// Write an integer to file

try (DataOutputStream dos = new DataOutputStream(new


FileOutputStream(file))) {

dos.writeInt(100); // Write number 100

System.out.println("Number 100 written to file.");

} catch (IOException e) {

System.out.println("Write Error: " + e.getMessage());


}

// Read the integer from file

try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

int num = dis.readInt(); // Read number back

System.out.println("Number read from file: " + num);

} catch (IOException e) {
System.out.println("Read Error: " + e.getMessage());

What this program does:

 Writes the number 100 to a file named data.bin.

 Then reads the number back from the file.


 Prints both messages on the screen.

Chapter 10 : List, Stacks, Queues and Priority Queues


1. Difference : ArrayList - LinkedList. (IMP - 3/4 Marks)

Aspect ArrayList LinkedList

Data Structure Uses a dynamic array Uses a doubly linked list


Aspect ArrayList LinkedList

Fast random access (get by Slow random access (needs


Access Time
index) traversal)

Slow for middle elements (shifts Fast insertion/deletion


Insertion/Deletion
elements) anywhere

More memory used for storing


Memory Usage Less memory overhead
pointers

2. Characterize the role of Iterator interface. (IMP - 3/4 Marks)

 The Iterator interface provides a way to access elements one by one from a
collection (like ArrayList, LinkedList) without exposing its internal structure.

 It helps to traverse through the collection safely and efficiently.

 Main methods of Iterator:

o hasNext() — Returns true if there are more elements to read.

o next() — Returns the next element in the collection.

o remove() — Removes the last element returned by next() from the


collection.

Why use Iterator?

 It provides a uniform way to loop through different types of collections.

 Allows safe removal of elements during iteration.


 Avoids problems like ConcurrentModificationException if used properly.

(One Program Fixed From Here)

Chapter 11 : Sets and Maps


1. Compare List and Set. (3 Marks)

Feature List Set

Duplicates Allows duplicate elements Does not allow duplicates

No guaranteed order (except


Order Maintains insertion order
LinkedHashSet)
Feature List Set

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:

1. New (Created) State

o When a thread object is created but not yet started.

2. Runnable State

o After calling start(), the thread is ready to run and waiting for CPU time.

3. Running State

o When the thread is actually executing its task.


4. Blocked/Waiting State

o When the thread is waiting for a resource or waiting to be notified.

5. Terminated (Dead) State

o When the thread finishes execution or is stopped.

Summary in brief:

State Description

New Thread created but not started yet

Runnable Ready to run, waiting for CPU

Running Thread is executing

Blocked Waiting for resource or event

Terminated Execution finished or stopped


2. What is the package? Explain steps to create a package with example. (IMP
- 4/7 Marks)

What is a Package?

 A package in Java is a way to group related classes and interfaces together.

 It helps to organize code, avoid name conflicts, and control access.

 Think of it like a folder that stores related files.

Steps to Create a Package:


1. Declare Package in Java File:
At the top of your .java file, write:
package package_name;

2. Save the Java File in a Folder:


The folder name should be the same as the package name.
Example: If package name is mypackage, save the file inside folder mypackage.

3. Compile the Java File:


Use command:

javac package_name/FileName.java
4.Run the Java Program:
Use command:

java package_name.FileName

Example:

Create a package named mypackage with a class Hello.

package mypackage;

public class Hello {

public void show() {


System.out.println("Hello from mypackage!");

Using the Package (in another file):


import mypackage.Hello;
public class Test {

public static void main(String[] args) {

Hello h = new Hello();


h.show();

Summary:

Step Description

1. Declare package package mypackage;

Save inside
2. Save file in folder
mypackage folder

javac
3. Compile
mypackage/Hello.java

4. Run java mypackage.Hello

3. Characterize the two ways of implementing thread in Java? Illustrate each


method by example? (IMP - 4/7 Marks)

1. By Extending the Thread Class

 Create a new class that extends the Thread class.

 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:

class MyThread extends Thread {

public void run() {

System.out.println("Thread running by extending Thread class.");

}
}
public class TestThread1 {

public static void main(String[] args) {

MyThread t = new MyThread();


t.start(); // Start the thread

2. By Implementing the Runnable Interface

 Create a class that implements the Runnable interface.

 Implement the run() method.

 Create a Thread object by passing an instance of your class, then call start().
Example:
class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread running by implementing Runnable interface.");

public class TestThread2 {


public static void main(String[] args) {

MyRunnable r = new MyRunnable();

Thread t = new Thread(r);

t.start(); // Start the thread

Summary:
Example Class to
Method How It Works
Extend/Implement

Subclass Thread and


Extend Thread Class class MyThread extends Thread
override run

Implement Runnable Implement Runnable and class MyRunnable implements


Interface override run Runnable

(Program Maybe Asked)

You might also like