0% found this document useful (0 votes)
13 views38 pages

Winter 2022 Solution - Java

The document discusses key Java concepts including bytecode significance, garbage collection, OOP characteristics, constructors, string methods, access modifiers, exception handling, overloading, overriding, and package creation. It provides examples and explanations of inheritance types and keywords like super, static, final, and this. The content is structured in a question-answer format, covering essential programming principles and practices in Java.

Uploaded by

dicepo5475
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)
13 views38 pages

Winter 2022 Solution - Java

The document discusses key Java concepts including bytecode significance, garbage collection, OOP characteristics, constructors, string methods, access modifiers, exception handling, overloading, overriding, and package creation. It provides examples and explanations of inheritance types and keywords like super, static, final, and this. The content is structured in a question-answer format, covering essential programming principles and practices in Java.

Uploaded by

dicepo5475
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/ 38

Q-1 (a) Discuss Significance of Byte Code.

Answer:

Java Byte code is significant for 3 main reasons:

1. Platform Independent:
● Bytecode allows Java programs to run on any platform with a
Java Virtual Machine (JVM) installed, enabling "write once,
run anywhere" portability.
2. Execution Policy:
● The JVM executes bytecode efficiently, employing
optimizations like JIT compilation and garbage collection.
3. Security:

z
● Bytecode verification ensures code adheres to security
aa
constraints, enhancing Java's security and preventing
malicious code execution.
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-1 (b) Explain Java garbage collection mechanism.

Answer:

Java Garbage Collection Mechanism:

● In Java, garbage collection is an automatic memory management


mechanism that frees up memory that is no longer needed by the
program.
● It works by periodically scanning the heap, which is the region of
memory where objects are stored, and identifying objects that are
no longer being referenced by the program.
● These objects are then marked for garbage collection and their
memory is released.

z
● The garbage collection process is automatic and runs in the
aa
background without any intervention from the programmer.
● Java uses a mark and sweep algorithm to identify objects that are
Aw
no longer being referenced by the program.
● This algorithm works by first marking all objects that are still being
referenced and then sweeping through the heap and releasing the
ut

memory of any objects that were not marked.


gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-1 (c) List OOP characteristics and describe
inheritance with examples.

Answer:

Object-Oriented Programming (OOP) is a programming paradigm that


focuses on creating objects that can interact with one another to solve
problems. Here are the main characteristics of OOP:

1. Encapsulation: The ability to hide implementation details within a


class, and only expose relevant methods and properties to the
outside world.
2. Inheritance: The ability to create new classes based on existing
classes, inheriting their properties and behaviour.

z
3. Polymorphism: The ability to use a single interface to represent
aa
multiple types of objects.
4. Abstraction: The ability to focus on the essential features of an
w
object, ignoring its implementation details.
A

Inheritance:
ut
gr

● Inheritance is a key aspect of OOP that allows developers to


create new classes based on existing classes, inheriting their
Ja

properties and behaviour.


● Inheritance creates a parent-child relationship between classes,
where the child class inherits all the properties and methods of the
parent class, and can also add new properties and methods of its
own.

Click :Youtube Channel | Free Material | Download App


Example:

class Animal {
void makeSound() {
[Link]("The animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
[Link]("The dog barks");
}
}

public class Main {

z
public static void main(String[] args) {
Animal animal = new Animal(); aa
[Link](); // Output: The animal makes a sound
w
Dog dog = new Dog();
A

[Link](); // Output: The dog barks


}
ut

}
gr

● In this example, the Animal class is the parent class, and the Dog
class is the child class that extends the Animal class.
Ja

● The Dog class overrides the makeSound method of the Animal


class to provide its own implementation.
● When the makeSound method is called on the animal object, the
output is "The animal makes a sound".
● When the makeSound method is called on the dog object, the
output is "The dog barks".

Click :Youtube Channel | Free Material | Download App


Q-2 (a) Explain constructor with the help of an example.

Answer:

Constructor:

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


automatically called when an object is created and ensures proper
initialization before use.

Example:

public class Person {

z
private String name;
private int age; aa
w
public Person(String name, int age) {
[Link] = name;
tA

[Link] = age;
[Link]("A new person has been created!");
}
u
gr

public static void main(String[] args) {


Person person = new Person("John", 19);
Ja

}
}

When a new instance of the Person class is created using the


constructor, the “name” and “age” values are set and the message is
printed to the console.

Output:

Click :Youtube Channel | Free Material | Download App


Q-2 (b) List out different methods available for String
class in java and explain any two with proper examples.

Answer:

Different String methods commonly used in Java:

● length()
● substring()
● equals()
● toUpperCase()
● toLowerCase()
● indexOf()

z
● charAt()
● concat()
aa
Aw
1. length(): This method returns the length of the string, which is the
number of characters in the string.
ut

Example:
gr

String str = "hello";


Ja

int len = [Link](); // len is 5

2. charAt(): This method returns the character at the specified index in


the string. The index is zero-based, meaning that the first character in
the string has an index of 0.

Example:

String str = "hello";


char c = [Link](1); // c is 'e'

Click :Youtube Channel | Free Material | Download App


Q-2 (c) Explain all access modifiers and their visibility
as class members.

Answer:

● In object-oriented programming, access modifiers are keywords


used to set the accessibility or visibility of class members (fields,
methods, and inner classes) in a class. There are four access
modifiers in Java:

1. Public:
Public members are accessible to all classes, regardless of
the package they belong to. Public members can be

z
accessed by any other class in the same program.
aa
2. Private:
Aw
Private members are only accessible within the same class.
They cannot be accessed by any other class, even if it
belongs to the same package.
ut

3. Protected:
gr

Protected members are accessible within the same class, as


Ja

well as any subclass that extends the class. They cannot be


accessed by any other class, including those in the same
package.

4. Default (also known as package-private):


Members with no access modifier specified are only
accessible within the same package. They cannot be
accessed by any other class outside the package.

Click :Youtube Channel | Free Material | Download App


Visibility:

Access Modifier Visibility

Public Accessible to all classes in any package

Private Accessible only within the same class

Protected Accessible within the same class and any subclass

Default Accessible only within the same package

z
aa
Aw
ut
gr
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-2 (c) Compare String with StringBuffer. Also, write a
program to count the occurrence of a character in a
string.

Answer:

String StringBuffer
String is an immutable class, StringBuffer, on the other hand, is
which means that once a string a mutable class, which means that
object is created, its value cannot its value can be changed after it is
be changed. created.
String objects are inherently

z
thread-safe, as they are StringBuffer, on the other hand,
immutable and can be safely
shared across multiple threads
aa
provides synchronised methods,
making it thread-safe.
without synchronisation.
Aw

Less efficient for frequent More efficient for frequent


modifications modifications
ut

Additional mutable string


String-specific methods (e.g.,
manipulation methods (e.g.,
gr

substring, indexOf)
append, insert, replace)
Ja

Click :Youtube Channel | Free Material | Download App


Program:

public class CharCount {


public static int countOccurrences(String str, char c) {
int count = 0;
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == c) {
count++;
}
}
return count;
}

public static void main(String[] args) {


String str = "hello world";

z
char c = 'l';
aa
int count = countOccurrences(str, c);
[Link]("The character '" + c + "' occurs " +
count + " times in the string '" + str + "'");
Aw
}
}
ut

Output:
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-3 (a) What is the final class? Why are they used?

Answer:

● A Final class is a class that cannot be subclassed, which means


that no other class can inherit from it.

● There are a few reasons why you might want to make a class final:

1. Security: If a class contains sensitive information or


functionality that should not be modified or extended, making
it final can help prevent unauthorised access or modification.
2. Efficiency: Final classes are often used to improve

z
performance in heavily used or performance-critical code,
aa
since the compiler can make certain optimizations that would
not be possible if the class could be subclassed.
Aw
3. Clarity: Final classes can also be used to make code more
clear and readable by indicating that a class is not intended
to be subclassed, which can help prevent errors or
ut

confusion.
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-3 (b) Write exception handling mechanisms in JAVA.

Answer:

In Java, exception handling mechanisms are used to handle and


manage exceptions that may occur during the execution of a program.
The primary mechanisms for exception handling in Java include:

1. try-catch: The try-catch block is used to catch and handle


exceptions. The code that is expected to throw an exception is
placed within the try block. If an exception occurs within the try
block, it is caught and handled by the catch block, which specifies
the type of exception to catch. Multiple catch blocks can be used to

z
handle different types of exceptions.
aa
2. throw: The throw statement is used to manually throw an
exception. It is typically used in situations where a specific
Aw
condition is met and the program needs to signal an exceptional
situation. The throw statement is followed by an instance of an
exception class.
ut

3. throws: The throws keyword is used in a method declaration to


indicate that the method may throw one or more types of
gr

exceptions. It specifies that the responsibility of handling the


exception lies with the calling code.
Ja

4. finally: The finally block is used to specify code that should be


executed regardless of whether an exception occurs or not. It is
placed after the try-catch block. The finally block is commonly used
to release resources or perform cleanup operations.

Click :Youtube Channel | Free Material | Download App


Q-3 (c) Explain Overloading and Overriding with
examples.

Answer:

Overloading and overriding are fundamental concepts in object-oriented


programming.

1. Overloading:

● Overloading refers to the ability to define multiple methods


with the same name but different parameters within the same
class. The methods must have different parameter lists,

z
which can include differences in the number, type, or order of
aa
parameters. During compilation, the appropriate method is
chosen based on the arguments provided at the call site.
A w
Example:
ut

public class Calculator {


public int add(int a, int b) {
gr

return a + b;
Ja

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


return a + b + c;
}
}

// Usage:
Calculator calculator = new Calculator();
int result1 = [Link](2, 3); // Calls the
first add method
int result2 = [Link](2, 3, 4); // Calls the
second add method

Click :Youtube Channel | Free Material | Download App


2. Overriding:

● Overriding is the process of providing a different


implementation of a method in a subclass that is already
defined in its superclass. It allows a subclass to provide its
specific implementation of the inherited method. The
overridden method must have the same name, return type,
and parameters as the method in the superclass.

Example:

public class Animal {


public void makeSound() {

z
[Link]("Animal makes a sound.");

}
} aa
Aw
public class Cat extends Animal {
@Override
public void makeSound() {
ut

[Link]("Meow!");
}
gr

}
Ja

// Usage:
Animal animal = new Animal();
[Link](); // Output: Animal makes a sound.

Cat cat = new Cat();


[Link](); // Output: Meow!

OR

Click :Youtube Channel | Free Material | Download App


Q-3 (a) How can you create packages in Java?

Answer:

To create a package in Java, you can follow these steps:

● Create a new directory with the name of your package. The


directory name should be the same as your package name, and
each sub-package should be a subdirectory within the main
package directory.
● Add a package statement at the top of each Java file that belongs
to the package. The package statement should indicate the full
name of the package, including any parent packages.

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-3 (b) What is Inheritance? List out the different forms
of Inheritance and explain any one with examples.

Answer:

Inheritance:

● Inheritance is a fundamental concept in object-oriented


programming that allows a class to inherit properties and
behaviours from another class.
● There are different types of inheritance in Java:

1. Single inheritance

z
2. Multilevel inheritance
3. Hierarchical inheritance
aa
4. Multiple inheritance
Aw

Example:
ut

class Vehicle {
void start() {
gr

[Link]("Vehicle started.");
Ja

}
}

class Car extends Vehicle {


void accelerate() {
[Link]("Car accelerating.");
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
[Link](); // Output: Vehicle started.
[Link](); // Output: Car accelerating.
}
}

Click :Youtube Channel | Free Material | Download App


Q-3 (c) Explain the words super, static, final and this
with the help of an example.

Answer:

1. super: The super keyword in Java is used to refer to the


superclass or parent class. It is primarily used to access members
(variables or methods) of the superclass, especially when they are
overridden in the subclass. It is also used to invoke the superclass
constructor.

class Vehicle {
String brand;

z
Vehicle(String brand) {
[Link] = brand;
aa
Aw
}

void start() {
[Link]("Vehicle started.");
ut

}
}
gr

class Car extends Vehicle {


Ja

String model;

Car(String brand, String model) {


super(brand); // Invoking superclass constructor
[Link] = model;
}

void displayDetails() {
[Link]("Brand: " + [Link]); //
Accessing superclass member
[Link]("Model: " + [Link]);
}
}

public class Main {

Click :Youtube Channel | Free Material | Download App


public static void main(String[] args) {
Car car = new Car("Toyota", "Camry");
[Link]();
}
}

2. static: The static keyword in Java is used to define class-level


variables and methods. Static members belong to the class itself
rather than individual instances of the class. They can be
accessed without creating an object of the class.

class MathUtils {
static final double PI = 3.14159; // Static constant

z
static int add(int a, int b) { // Static method

}
return a + b; aa
}
Aw

public class Main {


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

double radius = 2.5;


double circumference = 2 * [Link] * radius;
gr

// Accessing static constant


int sum = [Link](3, 5);
Ja

// Accessing static method


[Link]("Circumference: " +
circumference);
[Link]("Sum: " + sum);
}
}

Click :Youtube Channel | Free Material | Download App


3. final: The final keyword in Java is used to declare a constant
value, prevent a class from being subclassed, or prevent a method
from being overridden.

class Circle {
final double PI = 3.14159; // Final constant

void calculateArea(final double radius) { // Final


parameter
final double area = PI * radius * radius; // Final
local variable
[Link]("Area: " + area);
}
}

z
public class Main {
aa
public static void main(String[] args) {
Circle circle = new Circle();
[Link](2.5);
Aw
}
}
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


4. this: The this keyword in Java is a reference to the current object.
It is used to access instance variables, invoke other constructors
within the same class, and distinguish between instance variables
and parameters with the same name.

class Circle {
final double PI = 3.14159; // Final constant

void calculateArea(final double radius) { // Final


parameter
final double area = PI * radius * radius; // Final
local variable
[Link]("Area: " + area);
}
}

z
public class Main { aa
public static void main(String[] args) {
Aw
Circle circle = new Circle();
[Link](2.5);
}
}
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-4 (a) List out various layout panes in JavaFX.

Answer:

Layout Panes in JavaFX:

1. BorderPane
2. HBox
3. VBox
4. StackPane
5. GridPane
6. FlowPane
7. TilePane

z
8. AnchorPane
9. Pane aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-4 (b) Explain the architecture of JavaFX.

Answer:

Here is a brief overview of the architecture of JavaFX:

1. Scene Graph: The Scene Graph is the core of the JavaFX


architecture. It is a hierarchical structure of nodes, where each
node represents an element in the GUI, such as a button, label, or
text field. The Scene Graph provides a declarative and
customizable way to create and layout the user interface.
2. CSS Styling: JavaFX allows developers to style the user interface
using CSS (Cascading Style Sheets). CSS is a powerful styling

z
language that separates the presentation of the user interface from
aa
the logic of the application. Developers can create custom styles
for each node in the Scene Graph, or use pre-defined styles from
Aw
the JavaFX library.
3. Event Handling: JavaFX provides a rich set of event handlers that
allow developers to handle user input, such as mouse clicks and
ut

keyboard input. Event handling in JavaFX is based on the


observer pattern, where event sources notify event listeners of
gr

user actions.
4. Animation: JavaFX provides a powerful animation framework that
Ja

allows developers to create complex animations and transitions in


the user interface. The animation framework is based on the
timeline and keyframe concepts, where developers can define a
sequence of keyframes that define the animation.
5. Media Support: JavaFX provides built-in support for playing
media, such as video and audio files. It supports a variety of media
formats and provides a flexible media player API for controlling
playback.
6. 3D Graphics: JavaFX provides a powerful 3D graphics framework
that allows developers to create and manipulate 3D objects in the
user interface. The 3D graphics framework is based on the scene
graph, and supports features such as lighting, textures, and
materials.

Click :Youtube Channel | Free Material | Download App


Q-4 (c) Discuss BufferedInputStream and
BufferedOutputStream classes with an example.

Answer:

1. BufferedInputStream:

● The BufferedInputStream class reads data from an input


stream in chunks and stores it in an internal buffer.
● This buffer is filled from the underlying input stream, and
subsequent read operations fetch data from this buffer,
minimising the number of system calls.
● It provides methods for reading data in different formats,

z
such as bytes or characters.

Example:
aa
A w
import [Link].*;
ut

public class BufferedInputStreamExample {


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

try (BufferedInputStream bufferedInputStream = new


BufferedInputStream(new FileInputStream("[Link]"))) {
Ja

int data;
while ((data = [Link]()) != -1)
{
[Link]((char) data);
}
} catch (IOException e) {
[Link]();
}
}
}

Click :Youtube Channel | Free Material | Download App


2. BufferedOutputStream:

● The BufferedOutputStream class writes data to an output


stream in chunks, buffering the data internally.
● Instead of writing each byte or character immediately to the
underlying output stream, it stores them in an internal buffer.
● When the buffer is full or when the stream is explicitly
flushed, the buffered data is written to the output stream as a
single operation, reducing the number of system calls.

Example:

import [Link].*;

z
public class BufferedOutputStreamExample {
aa
public static void main(String[] args) {
try (BufferedOutputStream bufferedOutputStream = new
Aw
BufferedOutputStream(new FileOutputStream("[Link]"))) {
String data = "Hello, World!";
[Link]([Link]());
} catch (IOException e) {
ut

[Link]();
}
gr

}
}
Ja

OR

Click :Youtube Channel | Free Material | Download App


Q-4 (a) List out JavaFX UI controls and explain any one
in detail.

Answer:

1. Button: A control that represents a clickable button.


2. Label: A control that displays a text label.
3. TextField: A control that allows the user to input text.
4. TextArea: A control that allows the user to input multi-line text.
5. CheckBox: A control that represents a check box.
6. RadioButton: A control that represents a radio button.
7. ComboBox: A control that represents a drop-down list of options.
8. ListView: A control that displays a list of items.

z
9. TableView: A control that displays data in a tabular format.
aa
10. DatePicker: A control that allows the user to select a date.
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-4 (b) Demonstrate animation effect in JavaFX.

Answer:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class AnimationExample extends Application {

z
@Override
public void start(Stage primaryStage) {
// Create a rectangle
aa
Rectangle rectangle = new Rectangle(50, 50, [Link]);
Aw

// Create a translate transition


TranslateTransition translateTransition = new
ut

TranslateTransition([Link](2), rectangle);
[Link](250); // Move the rectangle to
gr

the right by 250 pixels


[Link](true); // Move the
Ja

rectangle back to its initial position

[Link]([Link]);
// Repeat the animation indefinitely

// Create a pane and add the rectangle to it


Pane root = new Pane(rectangle);

// Create a scene and add the pane to it


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

// Set the scene on the primary stage


[Link](scene);
[Link]("Animation Example");
[Link]();

Click :Youtube Channel | Free Material | Download App


// Start the animation
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-4 (c) Create a class called Student. Write a student
manager program to manipulate the student
information from files by using FileInputStream and
FileOutputStream.

Answer:

import [Link].*;
import [Link];
import [Link];

public class Student {


private int id;

z
private String name;
private String address; aa
Aw
public Student(int id, String name, String address) {
[Link] = id;
[Link] = name;
[Link] = address;
ut

}
gr

public int getId() {


return id;
Ja

public String getName() {


return name;
}

public String getAddress() {


return address;
}
}

class StudentManager {
private static final String FILE_NAME = "[Link]";

public static void main(String[] args) {

Click :Youtube Channel | Free Material | Download App


List<Student> students = new ArrayList<>();
[Link](new Student(1, "John Doe", "123 Main St"));
[Link](new Student(2, "Jane Doe", "456 Oak Ave"));
[Link](new Student(3, "Bob Smith", "789 Elm St"));

saveStudentsToFile(students);
List<Student> loadedStudents = loadStudentsFromFile();

[Link]("Loaded students:");
for (Student student : loadedStudents) {
[Link]([Link]() + " " +
[Link]() + " " + [Link]());
}
}

private static void saveStudentsToFile(List<Student> students)

z
{
try (FileOutputStream fos = new
FileOutputStream(FILE_NAME);
aa
Aw
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
[Link](students);
} catch (IOException e) {
ut

[Link]();
}
gr

}
Ja

private static List<Student> loadStudentsFromFile() {


List<Student> students = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis)) {
students = (List<Student>) [Link]();
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
return students;
}
}

Click :Youtube Channel | Free Material | Download App


Q-5 (a) What is Java Collection?

Answer:

● Java Collection refers to a framework provided by Java that


consists of classes and interfaces to store, manipulate, and
process groups of objects.
● It provides a set of predefined classes and interfaces that offer
various data structures and algorithms to manage and organise
collections of objects efficiently.
● Key points about Java Collection are:

1. Collections Framework: Java Collection is a part of the

z
larger Collections Framework, which includes the Collection,
aa
List, Set, Queue, and Map interfaces, along with their
respective implementations and utility classes.
Aw
2. Dynamic Data Structures: Java Collection provides
dynamic data structures such as ArrayList, LinkedList,
HashSet, TreeSet, HashMap, and TreeMap, among others.
ut

These data structures are designed to store and manage


groups of objects with different characteristics and
gr

requirements.
3. Standardised API: Java Collection offers a standardised
Ja

API (Application Programming Interface) that provides a


consistent set of methods and operations to work with
collections. It includes methods for adding, removing,
accessing, and manipulating elements within collections, as
well as algorithms for sorting, searching, and iterating over
elements.

Click :Youtube Channel | Free Material | Download App


Q-5 (b) List out methods of Iterator and explain it.

Answer:

● The Iterator interface in Java provides a way to iterate over


elements in a collection in a sequential manner.
● It is part of the Java Collections Framework and is commonly used
with collection classes such as ArrayList, LinkedList, and HashSet.
● Here are the methods of the Iterator interface along with their
explanations:

1. boolean hasNext():

z
● This method checks if there is a next element in the
aa
collection. It returns true if there is at least one more
element to iterate over, and false otherwise.
Aw

2. E next():
ut

● This method returns the next element in the collection


and advances the iterator to the next position. If there
gr

are no more elements, it throws a


NoSuchElementException.
Ja

3. void remove():

● This method removes the last element returned by the


next() method from the underlying collection. It is an
optional operation, and if it is not supported by the
collection, it throws an
UnsupportedOperationException. This method can
only be called once after calling next().

Click :Youtube Channel | Free Material | Download App


Q-5 (c) Explain Set and Map in Java with example.

Answer:

1. Set:
● A Set is an interface in the Java Collections Framework that
represents a collection of unique elements.
● It does not allow duplicate values, and the elements are
unordered.
● The Set interface is implemented by classes such as
HashSet, TreeSet, and LinkedHashSet.

Example:

z
import [Link];
import [Link];
aa
w
public class SetExample {
A

public static void main(String[] args) {


Set<String> fruits = new HashSet<>();
ut

// Adding elements to the set


gr

[Link]("Apple");
Ja

[Link]("Banana");
[Link]("Orange");
// Duplicate element, will not be added
[Link]("Apple");

// Printing the set


for (String fruit : fruits) {
[Link](fruit);
}
}
}

Click :Youtube Channel | Free Material | Download App


2. Map:
● A Map is an interface in the Java Collections Framework that
represents a collection of key-value pairs.
● Each key is unique, and it is used to retrieve the associated
value. The Map interface is implemented by classes such as
HashMap, TreeMap, and LinkedHashMap.

Example:

import [Link];
import [Link];

public class MapExample {


public static void main(String[] args) {

z
Map<String, Integer> ages = new HashMap<>();
aa
// Adding key-value pairs to the map
[Link]("John", 25);
Aw
[Link]("Jane", 30);
[Link]("Bob", 28);
ut

// Retrieving values from the map


[Link]("John's age: " +
gr

[Link]("John"));
Ja

// Removing a key-value pair from the map


[Link]("Bob");

// Checking if a key exists in the map


[Link]("Is Bob's age present? " +
[Link]("Bob"));

// Printing the map


for ([Link]<String, Integer> entry :
[Link]()) {
[Link]([Link]() + ": " +
[Link]());
}
}
}

OR

Click :Youtube Channel | Free Material | Download App


Q-5 (a) What is a Vector class?

Answer:

● In Java, a Vector is a class that represents a dynamic array, which


means that its size can change during runtime.
● It is similar to an ArrayList, but it is synchronised, which means that
it is thread-safe, and multiple threads can access it at the same
time without any issues.
● The Vector class provides several methods to manipulate and
access elements of the array, such as add(), remove(), get(), set(),
size(), and more.
● It can be used to store objects of any type, and it automatically

z
resizes itself as elements are added or removed.
aa
● However, it is important to note that the Vector class is considered
to be less efficient than the ArrayList class because of its
Aw
synchronised nature.
● Therefore, it is recommended to use ArrayList instead of Vector in
most cases, unless synchronisation is specifically required.
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App


Q-5 (b) Describe with diagram the life cycle of Thread.

Answer:

The life cycle of a thread in Java can be described using the following
diagram:

z
aa
Aw
1. New: The thread is in the new state when it is created, but it has
not yet started to execute.
2. Runnable: When the start() method is called on a thread object, it
ut

enters the runnable state. In this state, the thread is ready to run,
but the operating system has not yet assigned a processor to it.
gr

3. Running: When the operating system assigns a processor to the


Ja

thread, it enters the running state. The thread executes the code in
its run() method.
4. Blocked: A thread enters the blocked state when it is waiting for a
monitor lock to be released, such as when it is waiting to enter a
synchronised block.
5. Waiting: A thread enters the waiting state when it is waiting for
another thread to perform a particular action, such as when it calls
the wait() method.
6. Timed Waiting: A thread enters the timed waiting state when it is
waiting for a specified period of time, such as when it calls the
sleep() method.
7. Terminated: When a thread completes its run() method or throws
an unhandled exception, it enters the terminated state and cannot
be restarted.

Click :Youtube Channel | Free Material | Download App


Q-5 (c) Explain synchronisation in Thread with suitable
examples.

Answer:

● In Java, synchronisation is a mechanism that allows multiple


threads to coordinate their access to shared resources or critical
sections of code.
● It ensures that only one thread can execute a synchronised block
or method at a time, preventing potential data inconsistencies and
race conditions.
● Synchronisation is achieved using the synchronised keyword or by
using explicit locks.

z
Example: aa
w
class Counter {
A

private int count = 0;


ut

public synchronized void increment() {


count++;
gr

}
Ja

public synchronized void decrement() {


count--;
}

public synchronized int getCount() {


return count;
}
}

class CounterThread extends Thread {


private Counter counter;

public CounterThread(Counter counter) {


[Link] = counter;
}

Click :Youtube Channel | Free Material | Download App


public void run() {
for (int i = 0; i < 1000; i++) {
[Link]();
[Link]();
}
}
}

public class SynchronizationExample {


public static void main(String[] args) throws
InterruptedException {
Counter counter = new Counter();

CounterThread thread1 = new CounterThread(counter);


CounterThread thread2 = new CounterThread(counter);

z
[Link]();
[Link](); aa
Aw
[Link]();
[Link]();

[Link]("Final count: " + [Link]());


ut

}
}
gr
Ja

Click :Youtube Channel | Free Material | Download App

You might also like