0% found this document useful (0 votes)
10 views46 pages

Summer 2022 Solution _ Java

The document covers key concepts of Java programming, including features like platform independence and object-oriented principles. It provides examples of Java keywords, exception handling, inheritance types, and constructors. Additionally, it includes sample programs for converting infix to prefix expressions and evaluating mathematical expressions from command line arguments.

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)
10 views46 pages

Summer 2022 Solution _ Java

The document covers key concepts of Java programming, including features like platform independence and object-oriented principles. It provides examples of Java keywords, exception handling, inheritance types, and constructors. Additionally, it includes sample programs for converting infix to prefix expressions and evaluating mathematical expressions from command line arguments.

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/ 46

Object Oriented Programming-I

BE - SEMESTER–IV EXAMINATION – SUMMER 2022

Q.1(a) List out features of Java. Explain any two features.


Ans:
key features of Java are:
1. Platform Independence
2. Object-oriented

z
3. Security
4. Portability
aa
Aw
5. Garbage Collection
Two key features of Java are:
ut

1. Platform Independence – Java code can run on any platform


gr

that supports the Java Virtual Machine (JVM). This makes it


easy to develop and deploy software that can run on multiple
Ja

platforms without the need for recompilation. For example, a


Java program written on a Windows machine can be run on a
Linux or Mac machine without any changes to the code.
2. Object-oriented – Java is an object-oriented programming
language, which means that it supports encapsulation,
inheritance, and polymorphism. This makes it easy to write
modular and reusable code. Object-oriented programming
allows developers to break down complex problems into
smaller, more manageable pieces. This makes it easier to
develop, test, and maintain software over time.

Click :Youtube Channel | Free Material | Download App


Q.1(b) Write a single program which demonstrates the usage of
following keywords:
i) import, ii) new, iii) this, iv) break, v) continue
Show how to compile and run the program in java
Ans:
import java.util.Scanner;

public class KeywordExample {


private int number;

z
public KeywordExample(int number) {
aa
Aw
this.number = number;
}
ut
gr

public void printNumbers() {


Ja

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


if (i == 5) {
break;
}
if (i == 3) {
continue;
}
System.out.println(i);
}

Click :Youtube Channel | Free Material | Download App


}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

KeywordExample example = new KeywordExample(num); // ii)


new

z
example.printNumbers();
}
aa
Aw
}
ut

I. import: We import the Scanner class from the java.util package


to read input from the user.
gr
Ja

II. new: We create a new instance of the KeywordExample class


using the new keyword.

III. this: We use this keyword to refer to the current instance of the
class. In the constructor, this.number refers to the instance
variable number, and in the printNumbers() method, this is not
necessary but it demonstrates the usage.

IV. break: We use the break statement to exit the loop when the
value of i is 5.

Click :Youtube Channel | Free Material | Download App


V. continue: We use the continue statement to skip the rest of the
loop body and move to the next iteration when the value of i is
3.

To compile and run this program, follow these steps:

• Save the code as a file with a .java extension (e.g.Example.java).


• Open a command prompt or terminal window and navigate to
the directory where the file is saved.
• Compile the program by typing javac Example.java and pressing

z
Enter. aa
• Run the program by typing java Example and pressing Enter.
Aw

Q.1(c) Demonstrate use of try-catch construct in case of hierarchical


ut

Exception Handling. (i.e handling various exception belongs to the


gr

exception hierarchy).
Ja

Ans:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int result = numbers[5] / 0; // ArithmeticException

String str = null;


int length = str.length(); // NullPointerException

Click :Youtube Channel | Free Material | Download App


}
catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
catch (NullPointerException e) {

z
System.out.println("NullPointerException: " + e.getMessage());
}
aa
Aw
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
ut

}
gr

}
Ja

In this program, we have used a try-catch construct to handle


exceptions that belong to the exception hierarchy. Here's a
breakdown of the code:

• In the try block, we have two sections that may throw


exceptions:
• numbers[5] / 0 throws an ArithmeticException when trying to
divide by zero.

Click :Youtube Channel | Free Material | Download App


• str.length() throws a NullPointerException since str is initialized
to null.
• The catch blocks are ordered from specific exceptions to more
general exceptions.

• The first catch block catches ArithmeticException and handles it


by printing an error message.
• The second catch block catches
ArrayIndexOutOfBoundsException and handles it similarly.
• The third catch block catches NullPointerException.
• The last catch block catches any other exception that is not

z
caught by the previous catch blocks. This is useful for handling
aa
unexpected exceptions or as a fallback option.
• By using the try-catch construct with multiple catch blocks, we
Aw
can handle different types of exceptions in a hierarchical
manner, allowing for more specific exception handling based on
the exception types.
ut
gr

Q.2(a) Explain following Java keywords using appropriate examples:


Ja

i) static, ii) final, iii) super


Ans:
Static Keyword:
“static” is a keyword in Java that is used to define a variable, method
or block as a class-level entity. A static variable or method is
associated with the class and not with any particular instance of that
class. Static members are initialized only once when the class is
loaded into memory.
Example:
class Counter2{

Click :Youtube Channel | Free Material | Download App


static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();

z
Counter2 c2=new Counter2(); aa
Counter2 c3=new Counter2();
Aw
}
}
ut
gr

Final Keyword:
Ja

“final” is a keyword in Java that is used to make a variable, method or


class unchangeable or constant. Once a final variable is initialized, its
value cannot be changed. A final method cannot be overridden by a
subclass, and a final class cannot be extended.
Example:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}

Click :Youtube Channel | Free Material | Download App


public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}

Super keyword:
“super” is a keyword in Java that is used to refer to the superclass of
the current object. It is used to call the superclass constructor, access
the superclass’s methods, or access the superclass’s variables.
Example:
class Animal{

z
String color="white";
}
aa
Aw
class Dog extends Animal{
String color="black";
ut

void printColor(){
gr

System.out.println(color);//prints color of Dog class


System.out.println(super.color);//prints color of Animal class
Ja

}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

Click :Youtube Channel | Free Material | Download App


Q.2(b) Consider class A as the parent of class B. Explain among the
following which statement will show the compilation error.
i) A a = new A();
ii) A a = new B();
iii) B b = new A();
iv) B b = new B();

Ans:
In Java, when class A is the parent of class B, the following
statements can be considered:

z
i) A a = new A(); aa
This statement creates an object of class A and assigns it to a variable
Aw

of type A. Since class A is the parent class, there is no compilation


error in this statement.
ut
gr

ii) A a = new B();


Ja

This statement creates an object of class B and assigns it to a variable


of type A. In Java, this is allowed because of polymorphism. Class B is
a subtype of class A, so an instance of B can be assigned to a variable
of type A. Therefore, there is no compilation error in this statement.

iii) B b = new A();


This statement creates an object of class A and tries to assign it to a
variable of type B. Since class B is a subtype of class A, it is not valid
to assign an instance of the superclass (A) to a variable of the
subclass (B) without explicit casting. This statement will result in a
compilation error.

Click :Youtube Channel | Free Material | Download App


iv) B b = new B();
This statement creates an object of class B and assigns it to a variable
of type B. Since class B is the subclass of class A, and B can inherit all
the properties and behaviors of A, there is no compilation error in
this statement.

Therefore, the statement that will show a compilation error is:


iii) B b = new A();

z
Q.2(c) Write a java program to take infix expressions and convert it
aa
into prefix expressions.
Aw
Ans:
public class InfixToPrefixConverter {
ut
gr

// Function to check if a character is an operator


private static boolean isOperator(char ch) {
Ja

return ch == '+' || ch == '-' || ch == '*' || ch == '/';


}

// Function to check if a character is an operand


private static boolean isOperand(char ch) {
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch
<= 'Z');
}

// Function to get the precedence of an operator

Click :Youtube Channel | Free Material | Download App


private static int getPrecedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;

z
} aa
}
Aw

// Function to reverse a string


ut

private static String reverseString(String str) {


gr

StringBuilder sb = new StringBuilder(str);


return sb.reverse().toString();
Ja

// Function to convert infix expression to prefix expression


public static String infixToPrefix(String infix) {
String reversedInfix = reverseString(infix);
StringBuilder prefix = new StringBuilder();
StringBuilder operand = new StringBuilder();

for (int i = 0; i < reversedInfix.length(); i++) {

Click :Youtube Channel | Free Material | Download App


char ch = reversedInfix.charAt(i);

if (isOperand(ch)) {
operand.append(ch);
} else if (isOperator(ch)) {
prefix.append(ch);
prefix.append(operand.reverse());
operand.setLength(0);
}
}

z
prefix.append(operand.reverse());
aa
Aw
return prefix.reverse().toString();
}
ut
gr

public static void main(String[] args) {


String infixExpression = "(3+4)*2-5";
Ja

String prefixExpression = infixToPrefix(infixExpression);


System.out.println("Prefix Expression: " + prefixExpression);
}
}

The result is printed as the prefix expression: *-+3425

OR

Click :Youtube Channel | Free Material | Download App


Q.2(c) Write a java program that evaluates a math expression given
in string form from command line arguments.
Ans:
public class ExpressionEvaluator {

// Function to evaluate a math expression


private static double evaluateExpression(String expression) {
try {
return Double.parseDouble(expression); // If the expression is a single
number, return it

z
} catch (NumberFormatException e) {
aa
// Expression is not a single number, evaluate it
Aw
String[] tokens = expression.split(" ");

double result = Double.parseDouble(tokens[0]);


ut

int i = 1;
gr
Ja

while (i < tokens.length) {


String operator = tokens[i];
double operand = Double.parseDouble(tokens[i + 1]);

switch (operator) {
case "+":
result += operand;
break;
case "-":
result -= operand;

Click :Youtube Channel | Free Material | Download App


break;
case "*":
result *= operand;
break;
case "/":
result /= operand;
break;
default:
throw new IllegalArgumentException("Invalid operator: " +
operator);

z
}
aa
Aw
i += 2;
}
ut

return result;
gr

}
Ja

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java ExpressionEvaluator <expression>");
return;
}

String expression = args[0];


double result = evaluateExpression(expression);

Click :Youtube Channel | Free Material | Download App


System.out.println("Result: " + result);
}
}

Output:
java ExpressionEvaluator "3 + 4 * 2 - 5"
Result: 6.0

Q.3(a) Defines types of inheritance.


Ans:

z
In Java, there are five types of inheritance:
aa
1. Single Inheritance: In single inheritance, a subclass extends a
single superclass.
Aw

2. Multilevel Inheritance: In multilevel inheritance, a subclass


extends a superclass, which in turn extends another superclass,
ut

and so on.
gr

3. Hierarchical Inheritance: In hierarchical inheritance, multiple


Ja

subclasses extend a single superclass.


4. Multiple Inheritance: Multiple inheritance is a type of
inheritance in which a subclass can have more than one
superclass. However, Java does not support multiple
inheritance directly.
5. Hybrid Inheritance: Hybrid inheritance is a combination of
multiple and hierarchical inheritance. It is achieved by
combining two or more types of inheritance in a single
program.

Click :Youtube Channel | Free Material | Download App


Q.3(b) Explain the following constructors using appropriate
example:
i) Default constructor and Parameterised constructor
ii) Shallow copy and Deep copy constructor.
Ans:
Default constructor: A default constructor is a constructor with no
parameters. If a class does not have any constructor defined, then a
default constructor is automatically created by the compiler. The
default constructor initializes the instance variables of the class with
default values.

z
Example:
class Student3{
aa
Aw
int id;
String name;
//method to display the value of id and name
ut

void display(){System.out.println(id+" "+name);}


gr
Ja

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Click :Youtube Channel | Free Material | Download App


Parameterised constructor: A parameterized constructor is a
constructor that takes parameters. It is used to initialize the instance
variables of the class with the values passed as parameters.
Example:
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;

z
name = n;
}
aa
Aw
//method to display the values
void display(){System.out.println(id+" "+name);}
ut

public static void main(String args[]){


gr

//creating objects and passing values


Ja

Student4 s1 = new Student4(111,"Karan");


Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Shallow copy constructor: A shallow copy constructor is a


constructor that creates a new object with the same values as the
original object. In a shallow copy, only the values of the primitive

Click :Youtube Channel | Free Material | Download App


data types are copied, while the reference variables are copied as a
reference to the original object.
Example:
import java.util.* ;
class Demo{
private int[] my_data;
public Demo(int[] my_vals){
my_data = my_vals;
}
public void display_data(){

z
System.out.println(Arrays.toString(my_data) );
aa
}
Aw
}
public class Use_Demo{
ut

public static void main(String[] args){


gr

int[] my_vals = {56, 89, 91};


Demo my_inst = new Demo(my_vals);
Ja

my_inst.display_data();
my_vals[0] = 65;
my_inst.display_data();
}
}

Deep copy constructor: A deep copy constructor is a constructor that


creates a new object with the same values as the original object. In a
deep copy, both the primitive data types and reference variables are
copied as new objects.

Click :Youtube Channel | Free Material | Download App


Example:
import java.util.*;
class Demo{
private int[] my_data;
public Demo(int[] my_vals){
my_data = new int[my_vals.length];
for (int i = 0; i < my_data.length; i++){
my_data[i] = my_vals[i];
}
}

z
public void display_data(){
System.out.println(Arrays.toString(my_data));
aa
Aw
}
}
ut

public class Use_Demo{


gr

public static void main(String[] args){


Ja

int[] my_vals = {56, 89, 91};


Demo my_inst = new Demo(my_vals);
my_inst.display_data();
my_vals[0] = 65;
my_inst.display_data();
}
}

Click :Youtube Channel | Free Material | Download App


Q.3(c) Explain file io using byte stream with appropriate example.
hint: use FileInputStream, FileOutputStream
Ans:
In Java, file I/O using byte streams involves reading from and writing
to files at the byte level. The FileInputStream and FileOutputStream
classes are commonly used for this purpose. The FileInputStream
class is used for reading data from a file as a sequence of bytes, while
the FileOutputStream class is used for writing data to a file as a
sequence of bytes.
Example:

z
import java.io.FileInputStream;
import java.io.FileOutputStream; aa
import java.io.IOException;
Aw

public class FileIOExample {


ut
gr

public static void main(String[] args) {


Ja

String sourceFile = "source.txt";


String destinationFile = "destination.txt";

// Reading from source file using FileInputStream


try (FileInputStream fis = new FileInputStream(sourceFile)) {
int data;
while ((data = fis.read()) != -1) {
// Process the read byte
System.out.print((char) data); // Print the byte as a character
}

Click :Youtube Channel | Free Material | Download App


} catch (IOException e) {
e.printStackTrace();
}

// Writing to destination file using FileOutputStream


try (FileOutputStream fos = new FileOutputStream(destinationFile)) {
String content = "Hello, World!";
byte[] byteData = content.getBytes(); // Convert the content to bytes

fos.write(byteData); // Write the bytes to the file

z
System.out.println("\nData written to the file.");
aa
} catch (IOException e) {
Aw
e.printStackTrace();
}
ut

}
gr

• In this example, we have two files: source.txt and


Ja

destination.txt.

• To read from the source.txt file, we create a FileInputStream


object (fis) and use its read() method in a loop. The read()
method reads a byte from the file and returns it as an integer.
The loop continues until the end of the file is reached (read()
returns -1). In the loop, we process each byte (in this case, we
print it as a character).

• To write to the destination.txt file, we create a


FileOutputStream object (fos) and convert the content "Hello,

Click :Youtube Channel | Free Material | Download App


World!" to bytes using the getBytes() method. We then use the
write() method of the FileOutputStream class to write the byte
data to the file.

• Both the FileInputStream and FileOutputStream implement the


AutoCloseable interface, so we use the try-with-resources
statement to ensure that the streams are properly closed after
usage.

OR

z
Q.3(a) Define types of polymorphism.
Ans: aa
In Java, polymorphism refers to the ability of an object to take
Aw
on multiple forms. There are two main types of polymorphism
supported by Java:
1. Compile-time Polymorphism (Static Polymorphism):
ut

• Also known as method overloading or early binding.


gr

• Occurs when multiple methods in a class have the same

name but different parameters.


Ja

• The decision on which method to call is made by the

compiler based on the arguments passed during the


method call.
• The appropriate method is bound at compile-time.

• Examples include having multiple constructors in a class

with different parameter lists or having multiple methods


with the same name but different parameters.

2. Runtime Polymorphism (Dynamic Polymorphism):


• Also known as method overriding or late binding.

• Occurs when a subclass overrides a method defined in its

superclass.

Click :Youtube Channel | Free Material | Download App


• The decision on which method to call is made at runtime
based on the actual type of the object.
• The method of the specific subclass is called, even if the
reference variable is of the superclass type.
• Allows for polymorphic behavior, where the same method
call on different objects can have different
implementations.
• Examples include overriding a superclass method in a
subclass or implementing an interface method in a class.

Q.3(b) Explain the following:


i) Arguments and Parameters of a function

z
ii) Pass by Value and Pass by reference
Ans: aa
Aw
i) Arguments and Parameters of a function:

Parameters: Parameters are variables defined in the function


ut

declaration/definition. They represent the data that the


gr

function expects to receive when it is called. Parameters are


defined with a specific data type and a name. They act as
Ja

placeholders for the actual values that will be passed as


arguments when the function is called.

Example:

void greet(String name) { // 'name' is a parameter of type String


System.out.println("Hello, " + name + "!");
}

Click :Youtube Channel | Free Material | Download App


Arguments: Arguments are the actual values that are passed to a
function when it is called. They are the concrete values that are
substituted for the parameters in the function call. Arguments can be
literals, variables, or expressions.
Example:

greet("John"); // "John" is an argument passed to the 'greet' function

• In the example, the greet function has a parameter named


name of type String. When the function is called with the
argument "John", the value "John" is passed to the name
parameter, and the function prints "Hello, John!".

z
ii) Pass by Value and Pass by Reference: aa
Aw

Pass by Value: In Java, arguments are passed by value. This means


that when a function is called, the value of the arguments is copied
ut

into the function's parameter variables. Any changes made to the


gr

parameter variables within the function do not affect the original


arguments
Ja

Example:
void increment(int num) { // 'num' is a parameter
num++; // Increment the value of 'num'
System.out.println("Inside function: " + num);
}

int value = 5;
increment(value); // 'value' is an argument
System.out.println("Outside function: " + value);

Click :Youtube Channel | Free Material | Download App


• In the example, the increment function takes an argument value.
However, when the function increments the value of num, it does
not affect the original value variable outside the function.

Pass by Reference: Unlike some other programming languages, Java


does not have direct pass-by-reference. In Java, objects are passed by
value of the reference. When an object is passed as an argument to a
function, a copy of the reference to the object is passed. This means
that changes made to the object's properties within the function are
reflected outside the function, but reassigning the reference within
the function does not affect the original reference.

z
Example:
class Person {
aa
Aw
String name;
ut

Person(String name) {
this.name = name;
gr

}
Ja

void changeName(Person person) {


person.name = "Alice"; // Modify the object's property
person = new Person("Bob"); // Reassign the reference
}

Person p = new Person("John");


changeName(p);

Click :Youtube Channel | Free Material | Download App


System.out.println(p.name);

In the example, the changeName function modifies the name


property of the Person object. The change made to the object is
reflected outside the function. However, when a new Person object is
assigned to the person parameter within the function, it does not
affect the original reference p outside the function.

Q.3(c) Explain file io using character stream with appropriate


example.

z
hint: use FileReader, FileWriter
Ans: aa
File IO using character streams in Java is a way of reading and writing
Aw
data to and from a file in a character-wise manner. This is useful
when we need to deal with text-based data that contains special
characters such as newline, tab, or any non-ASCII characters. Java
ut

provides two classes FileReader and FileWriter to perform file IO


gr

operations using character streams.


Ja

Example:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileIOExample {

public static void main(String[] args) {


String sourceFile = "source.txt";
String destinationFile = "destination.txt";

// Reading from source file using FileReader


try (FileReader reader = new FileReader(sourceFile)) {
int data;

Click :Youtube Channel | Free Material | Download App


while ((data = reader.read()) != -1) {
// Process the read character
System.out.print((char) data); // Print the character
}
} catch (IOException e) {
e.printStackTrace();
}

// Writing to destination file using FileWriter


try (FileWriter writer = new FileWriter(destinationFile)) {

String content = "Hello, World!";


writer.write(content); // Write the content to the file
System.out.println("\nData written to the file.");

z
} catch (IOException e) {
e.printStackTrace();
aa
Aw
}
}
}
ut

• In this example, we have two files: source.txt and destination.txt.


gr
Ja

• To read from the source.txt file, we create a FileReader object


(reader) and use its read() method in a loop. The read() method
reads a character from the file and returns it as an integer. The
loop continues until the end of the file is reached (read() returns -
1). In the loop, we process each character (in this case, we print
it).

• To write to the destination.txt file, we create a FileWriter object


(writer) and use its write() method to write the content "Hello,
World!" to the file.

Click :Youtube Channel | Free Material | Download App


• Both the FileReader and FileWriter implement the AutoCloseable
interface, so we use the try-with-resources statement to ensure
that the streams are properly closed after usage.

Q.4(a) Define Encapsulation and access specifier


Ans:
Encapsulation is a mechanism in object-oriented programming that
combines data and functions that operate on that data into a single
unit called a class. It allows us to hide the implementation details of
an object from the outside world and restrict access to its internal
state.

z
Access specifiers, also known as access modifiers, determine the
aa
level of access to the members of a class in Java. There are four
Aw
access specifiers in Java:
1. Public: Members declared as public are accessible from
anywhere in the program.
ut

2. Private: Members declared as private are only accessible within


gr

the same class.


Ja

3. Protected: Members declared as protected are accessible


within the same class, within its subclasses, and within other
classes in the same package.
4. Default: Members declared with no access specifier (i.e., no
public, private, or protected keyword) are accessible within the
same package.

Click :Youtube Channel | Free Material | Download App


Q.4(b) Explain multithreading using Thread class
Ans:
In Java, multithreading allows multiple threads of execution to run
concurrently within a single program. The Thread class is a
fundamental class in Java that represents a thread of execution. By
extending the Thread class, you can create and manage threads in
your Java programs.
Example:
class MyThread extends Thread {
public void run() {

z
for (int i = 0; i < 5; i++) {
aa
System.out.println("Thread is running: " + i);
Aw
}
}
}
ut
gr

public class Main {


Ja

public static void main(String[] args) {


MyThread thread = new MyThread();
thread.start(); // Start the thread

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


System.out.println("Main thread is running: " + i);
}
}
}

Click :Youtube Channel | Free Material | Download App


• In this example, we create a subclass MyThread that extends
the Thread class. The MyThread class overrides the run()
method, which contains the code to be executed by the thread.
• In the Main class, we create an instance of MyThread named
thread. We then call the start() method on the thread object to
start the execution of the thread. The start() method internally
calls the run() method defined in the MyThread class.
• Simultaneously, the main thread continues its execution in the
main() method. Both the main thread and the MyThread thread
run concurrently, printing their respective messages in the
console.
• By extending the Thread class and overriding the run() method,

z
you can define custom behavior for your threads. This allows
aa
you to perform multiple tasks concurrently or handle time-
consuming operations in the background while your main
Aw
program continues its execution.
ut

Q.4(c) Write a short note on Java Collections.


gr

Ans:
Ja

Java Collections is a framework provided by Java that consists of


classes and interfaces for handling groups of objects. It provides
implementations of various data structures, such as lists, sets, maps,
queues, and more. The Java Collections framework offers a
convenient and efficient way to store, manipulate, and retrieve data
in a structured manner.

Key features of Java Collections include:

1. Interfaces: The framework provides a set of core interfaces


like List, Set, Map, Queue, and Deque, which define the

Click :Youtube Channel | Free Material | Download App


behavior and operations that can be performed on different
types of collections.

2. Implementations: The framework offers several classes that


implement these interfaces. For example, ArrayList and
LinkedList are implementations of the List interface, while
HashSet and TreeSet are implementations of the Set
interface.

3. Generics: Java Collections extensively use generics, allowing


type safety and enabling the storage of specific types of

z
objects in collections. This ensures that type errors are
aa
caught at compile-time, enhancing code reliability.
Aw

4. Algorithms: The framework provides various utility methods


ut

and algorithms to operate on collections, such as searching,


sorting, shuffling, and more. These algorithms simplify
gr

common operations and improve code readability.


Ja

5. Iterators: Collections in Java provide iterator objects that


allow sequential access to the elements within a collection.
Iterators enable efficient traversal and manipulation of
elements in a collection.

6. Thread-safety: The Java Collections framework provides


thread-safe implementations of collections, which can be
safely accessed and modified concurrently by multiple
threads without causing data corruption or race conditions.

Click :Youtube Channel | Free Material | Download App


Examples of thread-safe collections include
ConcurrentHashMap and CopyOnWriteArrayList.

7. Performance: The Java Collections framework is designed to


offer high-performance implementations for various
collection types. The choice of the collection class can impact
performance, depending on the specific use case and the
required operations.

OR

z
aa
Q.4(a) Differentiate between Abstract class and Interfaces
Aw
Ans:
Abstract Class Interfaces
Defined using the abstract Defined using the interface
ut

keyword. keyword.
gr

Can be extended by only one Can be implemented by multiple


class. classes.
Ja

Can have constructors. Cannot have constructors.


Can have instance variables. Can have constant fields.

Can have concrete methods. Can only have abstract method


declarations.
Does not support multiple Supports multiple inheritance
inheritance. (via interface implementation).
Used when creating a common Used when defining a contract
base class with some that multiple unrelated classes
implementation details shared can implement.
among subclasses.

Click :Youtube Channel | Free Material | Download App


Offers a partial implementation Defines a contract or behavior
and allows for code reuse among that unrelated classes can
related classes. adhere to.
Allows for greater flexibility in Provides a clear separation of
terms of adding new methods or concerns and allows for greater
changing existing ones in future flexibility in terms of swapping
versions. implementations.

Q.4(b) Explain multithreading using Runnable interface


Ans:

z
Multithreading is a concept in Java that allows concurrent execution
aa
of multiple threads within a single program. The Runnable interface
is a functional interface in Java that defines a single method called
Aw
run(), which represents the code that will be executed in a separate
thread.
ut

Example:
gr

public class MyRunnable implements Runnable {


@Override
Ja

public void run() {


for (int i = 0; i < 5; i++) {
System.out.println("Thread is running: " + i);
}
}
}

public class Main {


public static void main(String[] args) {

Click :Youtube Channel | Free Material | Download App


// Create an instance of MyRunnable
MyRunnable myRunnable = new MyRunnable();

// Create a Thread object with MyRunnable as the target


Thread thread = new Thread(myRunnable);

// Start the thread


thread.start();

// Continue with the main thread

z
for (int i = 0; i < 5; i++) { aa
System.out.println("Main thread is running: " + i);
Aw
}
}
ut

}
gr

• In this example, we define a class MyRunnable that implements


the Runnable interface. The run() method is overridden with
Ja

the code that will be executed in a separate thread. In this case,


it simply prints some messages in a loop.

• In the Main class, we create an instance of MyRunnable and


pass it as a parameter when creating a new Thread object. We
then start the thread using the start() method. This causes the
run() method of MyRunnable to be executed concurrently in a
separate thread.

Click :Youtube Channel | Free Material | Download App


• Meanwhile, the main thread continues executing the code in
the main() method. It also prints some messages in a loop.

• When you run this code, you'll see that the messages from the
MyRunnable thread and the main thread are printed
interleaved, indicating concurrent execution.

Q.4(c) Write a program to add input elements in ArrayList collection


class, then sort the inserted elements in descending order and
display the sorted output.
hint: use Collections.reverseOrder()

z
Ans:

import java.util.ArrayList;
aa
Aw
import java.util.Collections;
import java.util.Scanner;
ut

public class Main {


gr

public static void main(String[] args) {


// Create an ArrayList to store the input elements
Ja

ArrayList<Integer> numbers = new ArrayList<>();

// Read input elements from the user


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int count = scanner.nextInt();

System.out.println("Enter the elements:");


for (int i = 0; i < count; i++) {
int element = scanner.nextInt();
numbers.add(element);
}

Click :Youtube Channel | Free Material | Download App


// Sort the elements in descending order
Collections.sort(numbers, Collections.reverseOrder());

// Display the sorted output


System.out.println("Sorted Output:");
for (int number : numbers) {
System.out.println(number);
}
}
}

z
• In this code, we first create an ArrayList<Integer> called numbers
aa
to store the input elements. We then use a Scanner to read the
number of elements to be entered and the actual elements from
Aw
the user.

• Next, we use a loop to add the input elements to the numbers


ut

ArrayList.
gr

• After that, we sort the elements in descending order using the


Ja

Collections.sort() method with Collections.reverseOrder() as the


second argument. This ensures that the elements are sorted in
descending order.

• Finally, we display the sorted output by iterating over the numbers


ArrayList and printing each element.

When you run this program, it will prompt you to enter the number
of elements and then the elements themselves. After you've entered
all the elements, it will display the sorted output in descending order.

Click :Youtube Channel | Free Material | Download App


Q.5(a) Explain following Java keywords using appropriate examples:
i) throw, ii) throws, iii) finally
Ans:
i) Throw: It is a Java keyword used to explicitly throw an exception. It
is used to throw a new exception or re-throw an existing exception to
the calling method or higher up in the call stack. Here is an example:

public void validateAge(int age) {


if(age < 18) {
‘throw new T1legalArgumentException("Age must be at least 18
years");
}
}

z
aa
ii) Throws: In Java, the throws keyword is used to declare that a
method may throw a particular type of exception. It is part of the
Aw
method signature and helps in specifying the exceptions that can be
thrown by that method. Example:
ut

public class Example {


gr

public static void main(String[] args) {


try {
Ja

divideNumbers(10, 0);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void divideNumbers(int a, int b) throws


ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
} else {
int result = a / b;
System.out.println("Result: " + result);
}

Click :Youtube Channel | Free Material | Download App


}
}

iii) Finally: In Java, the finally keyword is used in conjunction with a


try-catch block to define a block of code that will always be executed,
regardless of whether an exception is thrown or not. The finally block
ensures that certain cleanup or finalization tasks are performed
before exiting the method or the try-catch block. Example:
public class Example {
public static void main(String[] args) {
try {
int result = divideNumbers(10, 2);
System.out.println("Result: " + result);

z
} catch (ArithmeticException e) {
aa
System.out.println("Error: " + e.getMessage());
} finally {
Aw
System.out.println("Finally block executed.");
}
}
ut

public static int divideNumbers(int a, int b) {


gr

try {
return a / b;
Ja

} catch (ArithmeticException e) {
throw new ArithmeticException("Cannot divide by zero.");
}
}
}

Click :Youtube Channel | Free Material | Download App


Q.5(b) In multi-threading using Thread class, explain with an
example how a start() method call invokes the run method of the
class extending Thread class.
Ans:
In Java, the Thread class is used to create and control threads of
execution. Each thread in Java is associated with an instance of the
Thread class. To create a new thread, we can either create a class
that extends the Thread class or implement the Runnable interface.

When we create a class that extends the Thread class, we must


override the run() method. The run() method contains the code that
the thread will execute when it starts. To start the thread, we call the

z
start() method on the Thread instance. This method will create a new
aa
thread of execution and then call the run() method on the new
thread.
Aw

An example of creating a class that extends the Thread class and


overriding the run() method:
ut
gr

public class MyThread extends Thread {


Ja

@Override
public void run() {
System.out.println("Thread is running");
}
}

To start the thread, we can create an instance of the MyThread class


and call the start() method:

public class Main {


public static void main(String[] args) {
MyThread my Thread = new MyThread();
myThread.start();

Click :Youtube Channel | Free Material | Download App


}
}
When we call myThread.start(), a new thread of execution is created
and the run() method is called on the new thread. The output of the
above code will be:
Output: Thread is running

Q.5(c) Write a short note on JAVAFX controls.


Ans:
JavaFX controls are a set of user interface components or widgets
that provide the foundation for building interactive and visually
appealing graphical user interfaces (GUIs) in Java applications. These
controls offer a wide range of functionality, including displaying text,

z
aa
accepting user input, handling events, and organizing the layout of
the user interface.
Aw

Some commonly used JavaFX controls include:


ut

1. Button: Represents a clickable button that performs an action


gr

when pressed.
2. TextField: Allows users to enter and edit text.
Ja

3. Label: Displays a non-editable text or an image.


4. CheckBox: Presents a checkable box that allows users to select
one or more options.
5. RadioButton: Represents a single-selection choice in a group of
options.
6. ComboBox: Provides a drop-down list of options, allowing users to
select one.
7. ListView: Displays a scrollable list of items from which users can
select one or more.
8. TableView: Organizes data in a table format, with rows and
columns.

Click :Youtube Channel | Free Material | Download App


9. Slider: Offers a draggable knob that allows users to select a value
from a range.
10. ProgressIndicator: Shows the progress of a long-running task.
11. DatePicker: Allows users to select a date from a calendar.
12. WebView: Embeds a web browser within the application to
display web content.

These controls provide various properties, styles, and event handling


mechanisms to customize their appearance and behavior. They can
be arranged and managed using layout containers like VBox, HBox,
GridPane, and others to achieve desired UI layouts.

z
JavaFX controls are part of the JavaFX framework and are included in
aa
the Java SE platform, starting from Java 8. They offer a rich set of
features and enable developers to create modern and responsive
Aw
user interfaces for desktop, mobile, and embedded applications

OR
ut
gr

Q.5(a) Explain thread life cycle.


Ja

Ans:
The life cycle of a thread in Java can be described as:

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 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.
3. Running: When the operating system assigns a processor to the
thread, it enters the running state. The thread executes the
code in its run() method.

Click :Youtube Channel | Free Material | Download App


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

z
aa
Q.5(b) In multi-threads using the Runnable interface, explain with
Aw
an example how a start() method calls the run() method of a class
implementing a runnable interface.
Ans:
ut

In Java, when working with multi-threading using the Runnable


gr

interface, you can create a separate thread of execution by


implementing the run() method. The start() method of the Thread
Ja

class is then used to start the execution of the run() method.

Example:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}

Click :Youtube Channel | Free Material | Download App


}

• In this example, we have a class MyRunnable that implements the


Runnable interface. It overrides the run() method, which contains
the code that will be executed in a separate thread.

• In the main() method, we create an instance of MyRunnable and


then create a new Thread object, passing the MyRunnable
instance as the constructor argument. Next, we call the start()
method on the Thread object. This starts the execution of the
run() method in a separate thread.

z
• When you run this code, the output will be "Thread is running"
aa
because the run() method of MyRunnable is executed by the
newly created thread.
Aw

By using the start() method, you initiate the execution of the run()
method on a separate thread, allowing concurrent execution of code
ut
gr
Ja

Q.5(c) Develop a GUI based application using JAVAFX controls.

Click :Youtube Channel | Free Material | Download App


Ans:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class GUIApplication extends Application {


private Label label;

public static void main(String[] args) {


launch(args);
}

z
@Override
aa
public void start(Stage primaryStage) {
Aw
primaryStage.setTitle("GUI Application");

// Create a label
ut

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


gr

// Create a button
Ja

Button button = new Button("Click Me");


button.setOnAction(e -> updateLabelText());

// Create a layout and add the label and button


VBox layout = new VBox(10);
layout.getChildren().addAll(label, button);

// Create a scene with the layout


Scene scene = new Scene(layout, 200, 100);

// Set the scene and show the stage


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

Click :Youtube Channel | Free Material | Download App


private void updateLabelText() {
label.setText("Button Clicked!");
}
}

When you run this code, a window will appear with the label and
button. Clicking the button will update the label text accordingly.

z
aa
Aw
ut
gr
Ja

Click :Youtube Channel | Free Material | Download App

You might also like