0% found this document useful (0 votes)
9 views86 pages

Java Multithreading Overview and Concepts

The document provides an overview of multithreading in Java, explaining the concept of threads, their lifecycle, and the advantages of using multithreading over multiprocessing. It details thread priority, synchronization methods, and the potential for race conditions, along with examples of implementing threads using both inheritance and interfaces. Additionally, it illustrates thread synchronization through synchronized methods and blocks to prevent issues arising from concurrent access to shared resources.

Uploaded by

dk8083257
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)
9 views86 pages

Java Multithreading Overview and Concepts

The document provides an overview of multithreading in Java, explaining the concept of threads, their lifecycle, and the advantages of using multithreading over multiprocessing. It details thread priority, synchronization methods, and the potential for race conditions, along with examples of implementing threads using both inheritance and interfaces. Additionally, it illustrates thread synchronization through synchronized methods and blocks to prevent issues arising from concurrent access to shared resources.

Uploaded by

dk8083257
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

Module-5

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a
lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking. However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process. Java Multithreading is mostly used in
games, animation, etc.

Single Thread Model


A single threaded Java application model is depicted in Figure 1. According to the model, when
processes request for a shared resource like CPU, memory, database or files it is registered in a queue.
The processes keeps waiting. Then the scheduler checks whether resource is free and if free allots the
resource to the waiting process. It is a slow model as resources cannot be concurrently accessed and
processes need to synchronously wait until the resource becomes available.

The Java Thread Model


The Java run-time system depends on threads for many things. Threads reduce inefficiency by
preventing the waste of CPU cycles.
Threads exist in several states. Following are those states:
• New — When we create an instance of Thread class, a thread is in a new state.
• Runnable — The Java thread is in running state. Start() method is called to move to run
state from new state.
• Suspended/Blocked — A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it left off.
Thread can be suspended using suspend() until notify() occurs or sleep() for specific
milliseconds. Once their suspension is over, they come back to Runnable state.
• Dead — A thread can be terminated, which halts its execution immediately at any given
time. Once a thread is terminated, it cannot be resumed.
102
Figure: Life Cycle of a thread in Java

Thread Priority
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases,
the thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly
in a Java program.

Methods of Thread Priority


public final int getPriority(): The [Link]() method returns the priority of the given
thread.
public final void setPriority(int newPriority): The [Link]() method updates or
assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
Need of Thread priority:
When high priority threads request, low priority threads need to relinquish control.
Thread pre-emption is done based on priority and context switch among thread occur.

103
Thread Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Monitors and Thread Synchronization


Java's monitor supports two kinds of thread synchronization: mutual
exclusion and cooperation. Mutual exclusion, which is supported in the Java virtual machine via
object locks, enables multiple threads to independently work on shared data without
interfering with each other. Cooperation, which is supported in the Java virtual machine via the
wait and notify methods of class Object, enables threads to work together towards a common
goal.
A monitor is like a building that contains one special room that can be occupied by only one
thread at a time. The room usually contains some data. From the time a thread enters this room
to the time it leaves, it has exclusive access to any data in the room. Entering the monitor
building is called "entering the monitor." Entering the special room inside the building is called
"acquiring the monitor." Occupying the room is called "owning the monitor," and leaving the
room is called "releasing the monitor." Leaving the entire building is called "exiting the
monitor."
One thread must be able to execute a monitor region from beginning to end without another
thread concurrently executing a monitor region of the same monitor. A monitor enforces this
one-thread-at-a-time execution of its monitor regions. The only way a thread can enter a
monitor is by arriving at the beginning of one of the monitor regions associated with that
monitor. The only way a thread can move forward and execute the monitor region is by
acquiring the monitor.
When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the
associated monitor. The entry set is like the front hallway of the monitor building. If no other
thread is waiting in the entry set and no other thread currently owns the monitor, the thread
acquires the monitor and continues executing the monitor region. When the thread finishes
executing the monitor region, it exits (and releases) the monitor.
If a thread arrives at the beginning of a monitor region that is protected by a monitor already
owned by another thread, the newly arrived thread must wait in the entry set. When the
current owner exits the monitor, the newly arrived thread must compete with any other threads
also waiting in the entry set. Only one thread will win the competition and acquire the monitor.
104
The first kind of synchronization listed above, mutual exclusion, refers to the mutually exclusive
execution of monitor regions by multiple threads. At any one time, only one thread can be
executing a monitor region of a particular monitor. In general, mutual exclusion is important
only when multiple threads are sharing data or some other resource. If two threads are not
working with any common data or resource, they usually can't interfere with each other and
needn't execute in a mutually exclusive way.
The other kind of synchronization listed above as supported by monitors is cooperation.
Whereas mutual exclusion helps keep threads from interfering with one another while sharing
data, cooperation helps threads to work together towards some common goal.
Cooperation is important when one thread needs some data to be in a particular state and
another thread is responsible for getting the data into that state. For example, one thread, a
"read thread," may be reading data from a buffer that another thread, a "write thread," is filling.
The read thread needs the buffer to be in a "not empty" state before it can read any data out
of the buffer. If the read thread discovers that the buffer is empty, it must wait. The write thread
is responsible for filling the buffer with data. Once the write thread has done some more
writing, the read thread can do some more reading.
The form of monitor used by the Java virtual machine is called a "Wait and Notify" monitor. (It
is also sometimes called a "Signal and Continue" monitor.) In this kind of monitor, a thread that
currently owns the monitor can suspend itself inside the monitor by executing a wait command.
When a thread executes a wait, it releases the monitor and enters a wait set. The thread will
stay suspended in the wait set until some time after another thread executes a notify
command inside the monitor. When a thread executes a notify, it continues to own the monitor
until it releases the monitor of its own accord, either by executing a wait or by completing the
monitor region. After the notifying thread has released the monitor, the waiting thread will be
resurrected and will reacquire the monitor.

Implementing Threads in Java

Two ways to implement Thread in Java is to use (i) Inheritance channel where extends Thread class is
used and (ii) Interface channel where implements Runnable interface is used.

Java Thread Methods


Method Description
start() It is used to start the execution of the thread.
run() It is used to do an action for a thread.

105
sleep() It sleeps a thread for the specified amount of time.
currentThread() It returns a reference to the currently executing thread object.

join() It waits for a thread to die.


getPriority() It returns the priority of the thread.
setPriority() It changes the priority of the thread.
getName() It returns the name of the thread.
setName() It changes the name of the thread.
getId() It returns the id of the thread.
isAlive() It tests if the thread is alive.
suspend() It is used to suspend the thread.
resume() It is used to resume the suspended thread.
stop() It is used to stop the thread.
getState() It is used to return the state of the thread.
toString() It is used to return a string representation of this thread, including
the thread's name, priority, and thread group.
notify() It is used to give the notification for only one thread which is
waiting for a particular object.
notifyAll() It is used to give the notification to all waiting threads of a
particular object.

Java program to illustrate Thread methods for Main Thread


class Thr
{
public static void main(String any[]) throws InterruptedException
{
Thread t=[Link]();
[Link]([Link]());
[Link]("My Thread");
[Link](3000);
[Link]([Link]());

}
}

Java program to illustrate Thread creation using Runnable Interface


class NT1 implements Runnable
{
Thread t;
NT1()
{
t=new Thread(this,"my thread");
}
public void run()

106
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
107
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](1000);
}
}
}

Java program to illustrate multiple threading


class NT1 implements Runnable
{
Thread t;
String tname;
NT1(String tname)
{
[Link]=tname;
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link](tname+":"+i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class MThread
{
public static void main(String any[]) throws InterruptedException
{
108
NT1 n1=new NT1("Thread1");
NT1 n2=new NT1("Thread2");
NT1 n3=new NT1("Thread3");

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}

Race Condition in Java


Java is a multi-threaded programming language and there is a higher risk to occur race conditions.
Because the same resource may be accessed by multiple threads at the same time and may change the
data. We can say that race condition is a concurrency bug. It is closely related to deadlock in Java. It is
a condition in which the critical section (a part of the program where shared memory is accessed) is
concurrently executed by two or more threads. It leads to incorrect behavior of a program. In layman
terms, a race condition can be defined as, a condition in which two or more threads compete together
to get certain shared [Link] example, if thread A is reading data from the linked list and another
thread B is trying to delete the same data. This process leads to a race condition that may result in run
time error. Java Program to illustrate race conditions

class Callme{
public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
109
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output depends on thread who wins race in getting processor and a Thread synchronization is required.

Java program to illustrate Thread synchronization


(i) Using synchronized methods
class Callme
{
synchronized public void callme(String mesg) //Synchronized method
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
110
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);

}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
111
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
[Link](msg);
}
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Inter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a
thread is paused running in its critical section and another thread is allowed to enter (or lock) in the
same critical section to be executed. It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
112
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed. The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Producer-Consumer problem
In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a
classic example of a multi-process synchronization problem. The problem describes two processes,
the producer and the consumer, which share a common, fixed-size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece
at a time.

Solution program for Producer-Consumer problem using Multi-threading


class Item
{
int data;
boolean lock=false;
synchronized void put(int data)
{
while(lock){
try{ wait();}
catch(InterruptedException e){ };
}
lock=true;
notify();
[Link]=data;

}
synchronized void get()
{
while(!lock)
{
try{ wait();}
catch(InterruptedException e){ };
}
lock=false;
notify();
113
}
}

Suspending, resuming, and stopping threads in Java


Java's threads allow for concurrent processing of multiple requests. Java includes functionality to
pause, resume, and terminate running threads. Using these functions, you can manage thread
execution and guarantee that it proceeds normally. However, modern Java does not support suspend()
and resume() methods. We need to implement them using synchronization and inter-thread
communication.
Java program to demonstrate suspending and resuming of threads
class T implements Runnable
{
Thread t;
String name;
boolean sf;
T(String name)
{
t=new Thread(this,name);
}
public void run()
{
for(int i=10;i>=0;i--)
{
[Link]([Link]()+":"+i);
try{[Link](500);}
catch(InterruptedException e){ };
synchronized(this)
{
while(sf)
{
try{ wait();}
catch(InterruptedException e){ };
}
}
}
}
synchronized void mysuspend()
{
sf=true;

}
synchronized void myresume()
{
sf=false;
notify();
117
}
}
class SRT
{
public static void main(String any[]) throws InterruptedException
{
T t1=new T("first");
T t2=new T("second");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Java Enumerations
The Enum in Java is a data type which contains a fixed set of constants. It can be used for days
of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY)
, directions (NORTH, SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc. According to
the Java naming conventions, we should have all constants in capital letters. So, we have enum
constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available since
JDK 1.5. Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java
is more powerful. Here, we can define an enum either inside the class or outside the class.

118
Java program to demonstrate Enumeration constants and their usage
import [Link].*;
enum Apple
{
Jonathan,GoldenDel,RedDel,Winesap,Cortland
}
class Enum1
{
public static void main(String any[])
{
Apple ap=[Link];
[Link](ap);
Apple a[]=[Link]();
for(Apple x:a)
[Link](x);
[Link]("Enter the apple breed");
Scanner s=new Scanner([Link]);
String applebreed=[Link]();
[Link]([Link](applebreed));
}
}

Java program to demonstrate the class based approach of Enum and use of valueOf and values static
methods:
import [Link].*;
enum Apple
{
Jonathan(200),GoldenDel(150),RedDel(180),Winesap(300),Cortland(100);
private int price;
Apple(int price){ [Link]=price;}
int getPrice(){ return price;}
}
class Enum2
{
public static void main(String any[])
{
Apple ap=[Link];
[Link](ap);
Apple a[]=[Link]();
for(Apple x:a)
[Link](x+","+[Link]());
[Link]("Enter the apple breed");
Scanner s=new Scanner([Link]);
String applebreed=[Link]();
[Link]([Link](applebreed));
119
}
}

Java program to illustrate the months in the year as Enum and finding number of days given month
name
import [Link].*;
enum Month
{
Jan(31),Feb(28),Mar(31),Apr(30),May(31),
Jun(30),Jul(31),Aug(31),Sep(30),Oct(31),Nov(30),Dec(31);
private int nod;
Month(int nod){ [Link]=nod;}
int getDays(){ return nod;}
}
class Months
{
public static void main(String any[])
{
[Link]("Enter the month name");
Scanner s=new Scanner([Link]);
String monthname=[Link]();
Month m=[Link](monthname);
[Link]([Link]());
}
}

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
[Link] package: The [Link] package provides the utility classes to deal with objects.

120
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

Primitive Types and their Wrapper classes


Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Character wrapper class methods

Hence it has a constructor to convert from primitive character to Character object. The same can also
be done through static method valueOf. One can get primitive value from Character object using
charValue method

Boolean wrapper class methods

121
It has a 2 constructors to convert from primitive boolean to Boolean object. The constructor takes
primitive Boolean and string Boolean. The same can also be done through static method valueOf.
One can get primitive value from Boolean object using booleanValue method.
Numeric wrapper class methods

Any numeric Wrapper can be converted to its primitive equivalent using typeValue() method where
type can be any primitive.

Similarly any numeric primitive can be converted to its numeric wrapper using valueOf.

Autoboxing and Unboxing:


The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing
and opposite operation is known as unboxing. This is the new feature of Java5. So java programmer
doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:


No need of conversion between primitives and Wrappers manually so less coding is required.

Autboxing and methods example


class ABU
{
static int m(Integer i)
{
return i;
}
public static void main(String any[])
{
Integer iob;
int i=10;
iob=i; //Autoboxing
Integer iob1=m(30); //1. Autboxing, [Link] and 3. Autoboxing
[Link](i+iob);
[Link](iob1);
122
}
}

Autoboxing/Unboxing Occurs in Expressions


In general, autoboxing and unboxing take place whenever a conversion into an object or from an object
is required. This applies to expressions. Within an expression, a numeric object is automatically
unboxed. The outcome of the expression is reboxed, if necessary. For example, consider the following
program:

Autoboxing/unboxing Boolean and character values


public class MainClass {
public static void main(String args[]) {
Boolean booleanObject = true;

if (booleanObject){ //Autounboxing of Boolean value


[Link]("b is true");
}

123
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char

[Link]("ch2 is " + ch2);


}
}

LabComponent:
11. Write a program to illustrate creation of threads using runnable class. (start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds).

class Thread1 implements Runnable


{
String name;
Thread t;
Thread1(String name)
{
t=new Thread(this,name);
}
public void run()
{
[Link]([Link]()+" started");
try{[Link](500);}
catch(InterruptedException e){ };
[Link]([Link]()+" ended");
}
}

public class MyClass {


public static void main(String args[]) throws InterruptedException{
Thread1 t1=new Thread1("first");
[Link]();
[Link]("Main started..");
[Link]();
[Link]("Main ended..");
}
}

12. Develop a program to create a class MyThread in this class a constructor, call the base class
constructor, using super and start the thread. The run method of the class starts after this. It can be
observed that both main thread and created child thread are executed concurrently

public class Thread2 extends Thread


{
124
String name;
Thread2(String name)
{
super(name);
}
public void run()
{
[Link](getName()+" started");
try{[Link](500);}
catch(InterruptedException e){ };
[Link](getName()+" ended");
}
public static void main(String args[]) throws InterruptedException{
Thread2 t1=new Thread2("first");
[Link]();
[Link]("Main started..");
[Link]();
[Link]("Main ended..");
}
}

125
CONTENT BEYOND SYLLABUS-HackerRank program solving
1. Java Output Formatting

Input Format
Every line of input will contain a String followed by an integer.
Each String will have a maximum of 10 alphabetic characters, and each integer will be in the
inclusive range from to 0 to 999.
Output Format
In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less
than three digits, you must pad your output's leading digits with zeroes.
Sample Input
java 100
cpp 65
python 50
Sample Output
================================
java 100
cpp 065
python 050

Program:
import [Link];

public class Solution {


public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("================================");
for(int i=0;i<3;i++){
String s1=[Link]();
[Link](s1);
for(int j=0;j<[Link]();j++)
[Link](" ");
int x=[Link]();
if(x<10)
{
[Link]("00"+x);
}
else if(x<100)
{
[Link]("0"+x);
}
else
[Link](x);
126
//Complete this line
}
[Link]("================================");
}
}

2. Java Loops

Input Format
The first line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains three space-separated integers describing the
respective ai,bi and ni values for that query.
Output Format
For each query, print the corresponding series on a new line. Each series must be printed in order
as a single line of n space-separated integers.
Sample Input
2
0 2 10
535
Sample Output
2 6 14 30 62 126 254 510 1022 2046
8 14 26 50 98

Program:
import [Link].*;
import [Link].*;

class Solution{
public static void main(String []argh){
Scanner in = new Scanner([Link]);
int t=[Link]();
for(int i=0;i<t;i++){
int a = [Link]();
int b = [Link]();
int n = [Link]();

127
int s=a+b;
[Link](s+" ");
for(int j=1;j<n;j++)
{
s+=b*[Link](2,j);
[Link](s+" ");
}
[Link]();
}
[Link]();
}
}

Java Static Initializer Block


You are given a class Solution with a main method. Complete the given code so that it outputs the
area of a parallelogram with breadth B and height H . You should read the variables from the
standard input.
If B<=0 or H<=0 , the output should be "[Link]: Breadth and height must be
positive" without quotes.
Input Format
There are two lines of input. The first line contains B : the breadth of the parallelogram. The next
line contains H: the height of the parallelogram.
Output Format
If both values are greater than zero, then the main method must output the area of
the parallelogram. Otherwise, print "[Link]: Breadth and height must be
positive" without quotes.

Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class Solution {


static int B,H;
static boolean flag;
static{
Scanner s=new Scanner([Link]);
B=[Link]();
H=[Link]();
try{
if(B<=0 || H<=0)
{
flag=false;
throw new Exception("Breadth and height must be positive");
}
128
else
flag=true;
}
catch(Exception e)
{
[Link](e);
}
}
public static void main(String[] args){
if(flag){
int area=B*H;
[Link](area);
}

}//end of main

}//end of class

Java Subarray
Given an array of integers, find and print its number of negative subarrays on a new line.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class Solution {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should
be named Solution. */
Scanner s=new Scanner([Link]);
int N =[Link]();
int cnt=0;
int a[]=new int[N];
for(int i=0;i<N;i++)
a[i]=[Link]();
for(int i=0;i<N;i++)
{
int sum=0;
for(int j=i;j<N;j++)
{
sum+=a[j];
if(sum<0)
cnt++;
}
}
129
[Link](cnt);

}
}

Java Inheritance
Write the following code in your editor below:
1. A class named Arithmetic with a method named add that takes 2 integers as parameters
and returns an integer denoting their sum.
2. A class named Adder that inherits from a superclass named Arithmetic.
Your classes should not be be public
Program:
class Arithmetic
{
int add(int a,int b)
{
return a+b;
}
}
class Adder extends Arithmetic
{

}
public class Solution{
public static void main(String []args){
// Create a new Adder object
Adder a = new Adder();

// Print the name of the superclass on a new line


[Link]("My superclass is: " + [Link]().getSuperclass().getName());

// Print the result of 3 calls to Adder's `add(int,int)` method as 3 space-separated integers:


[Link]([Link](10,32) + " " + [Link](10,3) + " " + [Link](10,10) + "\n");
}
}

Java Interfaces
You are given an interface AdvancedArithmetic which contains a method signature int
divisor_sum(int n). You need to write a class called MyCalculator which implements the interface.
divisorSum function just takes an integer as input and return the sum of all its divisors. For example
divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12. The value of n will be at most 1000.
Read the partially completed code in the editor and complete it. You just need to write the
MyCalculator class only. Your class shouldn't be public.
Program
import [Link].*;
interface AdvancedArithmetic{

130
int divisor_sum(int n);
}

//Write your code here


class MyCalculator implements AdvancedArithmetic
{
public int divisor_sum(int n)
{
int sum=0;
for(int i=1;i<=n;i++)
{
if(n%i==0) sum+=i;
}
return sum;
}
}

class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
[Link]("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link](my_calculator.divisor_sum(n) + "\n");
[Link]();
}
/*
* ImplementedInterfaceNames method takes an object and prints the name of the interfaces it
implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = [Link]().getInterfaces();
for (int i = 0; i < [Link]; i++){
String interfaceName = theInterfaces[i].getName();
[Link](interfaceName);
}
}
}

Java Exception Handling


You will be given two integers x and y as input, you have to compute x/y. If x and y are not bit
signed integers or if y is zero, exception will occur and you have to report it. Read sample
Input/Output to know what to report in case of exceptions.
import [Link].*;
import [Link].*;
import [Link].*;
131
import [Link].*;
import [Link].*;

public class Solution {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should
be named Solution. */
Scanner s=new Scanner([Link]);
try{
int x=[Link]();
int y=[Link]();
int z=x/y;
[Link](z);
}
catch(InputMismatchException i)
{
[Link]("[Link]");
}
catch(ArithmeticException e)
{
[Link]("[Link]: / by zero");
}

}
}

132
Model Question Paper-I/II with effect from 2023-24 (CBCS
Scheme) - BCS306A

Third Semester B.E. Degree Examination


Object Oriented Programming with JAVA
1a Explain different lexical issues in JAVA (6M)
Whitespace - Java is a free-form language. This means that you do not need to follow
any special indentation rules. n Java, whitespace includes a space, tab, newline, or
form feed.
Identifiers - Identifiers are used to name things, such as classes, variables, and
methods. An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollar-sign characters.
Literals - A constant value in Java is created by using a literal representation of it. A
literal can be used anywhere a value of its type is allowed.
Comments – There are three types of comments defined by Java. You have already
seen two: single-line and multiline. The third type is called a documentation comment.
This type of comment is used to produce an HTML file that documents your program.
Separators - In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon.

Keywords - There are 61 keywords currently defined in the Java language. These
keywords, combined with the syntax of the operators and separators, form the
foundation of the Java language.

1b Define Array. Write a Java program to implement the addition of two matrixes.
(7M)
Arrays in Java
An array is a collection of similar type of elements which has contiguous memory
location. Java array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements

Java program for addition of two matrices:


import [Link].*;
class Matrix
{
public static void readMatrix(int[][] A,int N)
{
Scanner kb=new Scanner([Link]);
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
A[i][j]=[Link]();
}
}
}
public static void addMatrix(int[][] A, int[][] B, int[][] C,int N)
{
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
}
public static void printMatrix(int[][] A,int N)
{
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
[Link](A[i][j]+" ");
}
[Link]();
}
}

public static void main(String[] any)


{
int N=[Link](any[0]);
int[][] A=new int[N][N];
int B[][]=new int[N][N];
int C[][]=new int[N][N];
[Link]("Enter Matrix A");
readMatrix(A,N);
[Link]("Enter Matrix B");
readMatrix(B,N);
addMatrix(A,B,C,N);
[Link]("Sum Matrix C");
printMatrix(C,N);
}
}
1c Explain the following operations with examples. (i)<< (ii)>> (iii)>>> (6M)
These operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively. They can be used when we have to
multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;

• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as multiplying the number with some
power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of
the initial number. Similar effect to dividing the number with some power
of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
Example program snippet:
int d = 0b1010;
int e = 0b1100;
[Link]("d << 2: " + (d << 2));
[Link]("e >> 1: " + (e >> 1));
[Link]("e >>> 1: " + (e >>> 1));

Output:
d << 2: 40
e >> 1: 6
e >>> 1: 6

2a Explain object-oriented principles (7M)


There are three major pillars on which object-oriented programming
relies: encapsulation, inheritance, and polymorphism.

Encapsulation: This is the idea of wrapping everything up about a particular


thing, whether a Checking Account or Armadillo, into a defined object with
features and behaviors. Once we do, we can ask the object itself to do what it is
supposed to do, whether that is Deposit Money or Defend Yourself. But nobody
outside the object needs to worry about how it does its jobs. We just tell it to do it
and go about our day. If every object, simply minds its own business and stays
out of the business of other objects, all is good with the world.
Inheritance: This is the idea that we don’t have to define absolutely everything
about an object over and over again if it shares features and behaviors with other
objects. We can define a class for Accounts and then let our Checking Account or
Savings Account inherit all the stuff in common. Likewise, we can define a class
for Animals, and let our Armadillo inherit features like Number Of Legs and
Weight as well as behaviors such as Breathe and Sleep. We call these overarching
classes parent classes, and the ones that inherit from them, child classes. We can
then inherit from the child classes and so on. But our Checking Account is more
specialized than our Accounts because we can Write A Check, which we can’t do
with a Savings Account. Our Armadillo can Roll Into A Ball, but other animals
such as a Giraffe don’t have that behavior. Since we go from more general to more
specialized, I like to say that a child is like its parents, but much more special.
Polymorphism: This fancy name just means that we can treat the same object as
different things depending on how we need it at different times, and we can treat
groups of different objects that share an ancestor or trait as if they were that
ancestor or trait. So, we could have a set of different Checking, Savings, and Credit
Accounts and ask each to Get Balance so we can figure out how much we have to
spend on vacation this year. Or we could ask a queue of animals to Move Quickly,
and not care how the Porpoise or Eagle or Armadillo would handle that shared
behavior. I like to think that we are different things to different people, so even if
not, every Dungeon Master has a spouse to think him or her a nuisance, we can
ask any of them to organize a game for Saturday night.

2b Write a Java program to sort the elements using a for loop. (7M)
public class Sorting {
public static void main(String[] args) {
int[] array = {2, 3, 8, -4, -3}; // Example array to be sorted
// Bubble Sort Algorithm
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j + 1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// Print the sorted array
[Link]("Sorted array:");
for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}
}
2c Explain different types of if statements in JAVA (6M)
1. If Statement in Java
Java if statement is the simplest decision making statement. It encompasses a boolean
condition followed by a scope of code which is executed only when the condition
evaluates to true. However if there are no curly braces to limit the scope of sentences
to be executed if the condition evaluates to true, then only the first line is executed.
Syntax:
if(condition)
{
//code to be executed
}

2. if else statement in Java


This pair of keywords is used to divide a program to be executed into two parts, one
being the code to be executed if the condition evaluates to true and the other one to
be executed if the value is false. However if no curly braces are given the first
statement after the if or else keyword is executed.
if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}

3. Nested if Statements in Java


If the condition of the outer if statement evaluates to true then the inner if statement
is evaluated.
Nested if’s are important if we have to declare extended conditions to a previous
condition
Syntax:
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

4. if-else-if Statements in Java


These statements are similar to the if else statements. The only difference lies in the
fact that each of the else statements can be paired with a different if condition
statement. This renders the ladder as a multiple-choice option for the user. As soon as
one of the if conditions evaluates to true the equivalent code is executed and the rest
of the ladder is ignored.
Syntax:
if
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else if(condition)
{
//code to be executed
}
else
{
//code to be executed
}

3a What are constructors? Explain two types of constructors with an example


program (7M)
A constructor in Java is a special method that is used to initialize objects. Following
are salient points related to a constructor:
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes.
constructor name must match the class name, and it cannot have a return
type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
Types of constructors:

Default constructors are provided by compiler only when programmer has not
declared any other constructor. It will be a zero argument empty body constructor.
Programmers can declare their own version of no-argument constructors and fill some
initialization code. Parameterized constructors have constructors with parameters.

Eg: Box constructors


Box(double depth,double width,double height)
{
[Link]=depth;
[Link]=width;
[Link]=height;
}
Box()
{
}

Invoking constructors:
Box b1=new Box(7.1,4,2);

3b Define recursion. Write a recursive program to find nth Fibonacci number (7M)
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to
solve. Just as loops can run into the problem of infinite looping, recursive functions
can run into the problem of infinite recursion. Infinite recursion is when the function
never stops calling itself. Every recursive function should have a halting condition,
which is the condition where the function stops calling itself.

public class Fibonacci {


public static void main(String[] args) {
int n = 10; // Example: Find the 10th Fibonacci number
int result = fibonacci(n);
[Link]("The " + n + "th Fibonacci number is: " + result);
}

// Recursive method to find the nth Fibonacci number


public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

3c Explain the various access specifiers in Java. (6M)


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. One can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc.
Eg: Illustrating access specifiers/modifiers in Java
class A
{
public int x;
private int y;

}
class Access
{
public static void main(String[] any)
{
A a=new A();
a.x=10;
a.y=5;
[Link](a.x);
}
}
In this example, x is accessible and y cannot be accessed.

4a Explain call by value and call by reference with an example program (7M)
There are two methods to pass the data into the method, i.e., call by value and call by
reference.
In call by value method, the value of the actual parameters is copied into the
formal parameters.
In call by value method, we can not modify the value of the actual parameter
by the formal parameter.
In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the formal
parameter.
The actual parameter is the argument which is used in the method call whereas
formal parameter is the argument which is used in the function definition.
Eg program
class Swap
{
static void swap(int a,int b)
{
int temp= a;
a=b;
b=temp;
}
public static void main(String any[])
{
int a=5,b=6;
[Link]("Before:"+a+","+b);
swap(a,b);
[Link]("After:"+a+","+b);
}
}
Memory allocation
Call by reference
In call by reference, the address of the variable is passed into the method as
the actual parameter.
The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
Objects are passed by reference and can be used to wrap variables and provide
call by reference in Java.
Eg program

class Swap
{
static void swap(Obj o1)
{
int temp=o1.a;
o1.a=o1.b;
o1.b=temp;
}
public static void main(String any[])
{
Obj o1=new Obj();
o1.a=5;
o1.b=6;
[Link]("Before:"+o1.a+","+o1.b);
swap(o1);
[Link]("After:"+o1.a+","+o1.b);
}
}
4b Write a program to perform Stack operations using proper class and Methods. (7M)
class Stack
{
int max;
int top;
int data[];
Stack(int max)
{
[Link]=max;
top=-1;
data=new int[max];
}
void push(int ele)
{
if(top==max-1)
{
[Link]("Stack Overflow");
return;
}
data[++top]=ele;
}
void pop()
{
if(top==-1)
{
[Link]("Stack Overflow");
return;
}
[Link]("Popped Element="+data[top--]);
}
void display()
{
for(int i=top;i>=0;i--)
{
[Link](data[i]);
}
}
}

public class StackApp


{
public static void main(String args[])
{
Stack s=new Stack(10);
[Link](30);
[Link](40);
[Link](50);
[Link](90);
[Link]();
[Link]();
[Link]();
}
}

4c Explain the use of this in JAVA with an example. (6M)


The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). This scenario is called “Instance variable hiding”.
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

Eg usage of this keyword:


Box(double depth,double width,double height)
{
[Link]=depth;
[Link]=width;
[Link]=height;
}
Instance variables depth, width and height are hidden by parameters with same
name. Hence to represent instance variables this keyword has been used.

5a Write a Java program to implement multilevel inheritance with 3 levels of


hierarchy. (7M)
class Box
{
double width;
double height;
double depth;
int x=2;
Box(double width,double height,double depth)
{
[Link]=width;
[Link]=height;
[Link]=depth;
}
void disp()
{
[Link]("Box...");
}

}
class WeightBox extends Box
{
double weight;
int x=3;
WeightBox(double width,double height,double depth,double weight)
{
super(width,height,depth);
[Link]=weight;
}
void disp()
{
[Link]("WeightBox...");
[Link]();
}

}
class ColorBox extends Box
{
int color;
ColorBox(double width,double height,double depth,int color)
{
super(width,height,depth);
[Link]=color;
}
}
class Shipment extends WeightBox
{
int cost;
Shipment(double width,double height,double depth,double weight,int
cost)
{
super(width,height,depth,weight);
[Link]=cost;
}
}

class Inheritance2
{
public static void main(String[] any)
{
WeightBox w1=new WeightBox(1.2,3.4,1.1,20.0);
[Link]();
ColorBox c1=new ColorBox(1.2,3.4,1.1,2000);
}
}

5b Explain how an interface is used to achieve multiple Inheritances in Java. (7M)


A class in Java can implement multiple interfaces, thus inheriting the abstract
methods of all the interfaces. This allows a class to achieve multiple inheritance-like
behavior.

Example code:
// First interface
interface Animal {
void eat();
void sleep();
}

// Second interface
interface Pet {
void play();
void beFriendly();
}

// Class implementing multiple interfaces


public class Dog implements Animal, Pet {

public void eat() {


[Link]("Dog is eating.");
}
public void sleep() {
[Link]("Dog is sleeping.");
}
public void play() {
[Link]("Dog is playing.");
}
public void beFriendly() {
[Link]("Dog is being friendly.");
}

public static void main(String[] args) {


Dog myDog = new Dog();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
5c Explain the method overriding with a suitable example (6M)
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java. In other words, If a subclass provides the
specific implementation of the method that has been declared by one of its parent
class, it is known as method overriding. Method overriding is used to provide the
specific implementation of a method which is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example program for method overriding in Java:
class A
{
void disp(int x)
{
[Link]("A:"+x);
}
}
class B extends A
{
void disp()
{
[Link]("plain B");
}
void disp(int x)
{
[Link]("B:"+x);
[Link](x);
}
}

class Override
{
public static void main(String any[])
{
B b=new B();
[Link](5);
}
}

6a What is single-level inheritance? Write a Java program to implement single-level


inheritance. (7M)
Single level inheritance
Only one class is derived from the parent class. In this type of inheritance, the
properties are derived from a single parent class and not more than that. As the
properties are derived from only a single base class the reusability of a code is
facilitated along with the addition of new features. Flow diagram:
class A
{
A()
{
[Link]("A");
}
}
class B extends A
{
B()
{
[Link]("B");
}
}

class AB
{
public static void main(String[] any)
{
B b=new B();
}
}

6b What is the importance of the super keyword in inheritance? Illustrate with a


suitable example. (7M)
The super keyword in Java is a reference variable which is used to refer immediate
parent class object. Whenever you create the instance of subclass, an instance of parent
class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Eg:
class Animal{
String color="white";
Animal(){[Link]("animal is created");}
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
String color="black";
Dog()
{
super(); //Superclass constructor invoked
}
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//superclass variable
}
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link](); //call superclass methods
bark();
}

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

6c What is abstract class and abstract method? Explain with an example (6M)
A method which is declared as abstract and does not have implementation is known
as an abstract method.
Eg: abstract void printStatus();//no method body and abstract
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated. An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.
Eg: abstract class A{}
Example code for Abstract classes and methods
abstract class A
{
abstract void disp1();
void disp2()
{
[Link]("D2");
}
void disp3()
{
[Link]("D3");
}
}
class B extends A
{
void disp1()
{
[Link]("D1");
}

class Abs
{
public static void main(String[] any)
{
B b=new B();
b.disp2();
}
}

7a Define package. Explain the steps involved in creating a user-defined package with
an example. (7M)
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

Creating and using packages


Adding a class to a Package : We can add more classes to a created package by using
package name at the top of the program and saving it in the package directory. We
need a new java file to define a public class, otherwise we can add the new class to
an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the subpackages. These
are not imported by default, they have to imported explicitly. Also, members of a
subpackage have no access privileges, i.e., they are considered as different package
for protected and default access specifiers.
Example :
import [Link].*;
util is a subpackage created inside java package.

Steps involved in creating a user-defined package with an example.


Create a subfolder mypack and inside it create following class:
package mypack;
public class Account
{
double bal;
String name;
String accno;
public Account(String accno, String name,double bal)
{
[Link]=accno;
[Link]=bal;
[Link]=name;
}
public void show()
{
[Link](“Account Number=”+accno+"Account
Name="+name+", Balance="+bal);
}
}

In the folder above this, create following main class:


import mypack.*;
class AC
{
public static void main(String any[])
{
Account a1=new Account(“101”,"James",20000);
[Link]();
}
}

7b Write a program that contains one method that will throw an


IllegalAccessException and use proper exception handles so that the exception
should be printed. (7M)
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
methodThatThrowsException();
} catch (IllegalAccessException e) {
// Handle the exception
[Link]("Caught an IllegalAccessException: " + [Link]());
[Link]();
}
}

public static void methodThatThrowsException() throws IllegalAccessException {


// Deliberately throw an IllegalAccessException
throw new IllegalAccessException("This is an intentionally thrown
IllegalAccessException.");
}
}
7c Define an exception. What are the key terms used in exception handling?
Explain. (6M)
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. In Java, an
exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime. Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc. The core advantage of exception handling is to maintain the
normal flow of the application. An exception normally disrupts the normal flow of
the application; that is why we need to handle exceptions
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

8a Explain the concept of importing packages in Java and provide an example


demonstrating the usage of the import statement. (7M)
We can add more classes to a created package by using package name at the top of
the program and saving it in the package directory. We need a new java file to define
a public class, otherwise we can add the new class to an existing .java file and
recompile it.

Subpackages: Packages that are inside another package are the subpackages. These
are not imported by default, they have to imported explicitly. Also, members of a
subpackage have no access privileges, i.e., they are considered as different package
for protected and default access specifiers.
Example :
import [Link].*;
util is a subpackage created inside java package.

Steps involved in creating a user-defined package with an example.


Create a subfolder mypack and inside it create following class:
package mypack;
public class Account
{
double bal;
String name;
String accno;
public Account(String accno, String name,double bal)
{
[Link]=accno;
[Link]=bal;
[Link]=name;
}
public void show()
{
[Link](“Account Number=”+accno+"Account
Name="+name+", Balance="+bal);
}
}

In the folder above this, create following main class:


import mypack.*;
class AC
{
public static void main(String any[])
{
Account a1=new Account(“101”,"James",20000);
[Link]();
}
}

8b How do you create your own exception class? Explain with a program. (7M)
User-defined exceptions in Java allow developers to create custom exception classes
that are specific to their application's needs. These custom exceptions can be used to
provide more meaningful error messages and handle specific error conditions more
gracefully.
class DivideByZero extends Exception
{
String message;
DivideByZero(String message)
{
[Link]=message;
}
public String toString()
{
return "USer attempted "+message;
}
}
class DZ
{
static int compute(int a,int b) throws DivideByZero
{
if(b==0)
throw new DivideByZero("Divide By Zero...");
return a/b;
}
public static void main(String args[])
{
int a=[Link](args[0]);
int b=[Link](args[1]);
try{
[Link](compute(a,b));
}
catch(DivideByZero z)
{
[Link](z);
}
finally{
[Link]("I am always der...");
}
}
}

8c Demonstrate the working of a nested try block with an example (6M)


In Java, using a try block inside another try block is permitted. It is called as nested
try block. Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Java Nested try Example


public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
When any try block does not have a catch block for a particular exception, then the
catch block of the outer (parent) try block are checked for that exception, and if it
matches, the catch block of outer try block is executed. If none of the catch block
specified in the code is unable to handle the exception, then the Java runtime system
will handle the exception. Then it displays the system generated message for that
exception.

9a What do you mean by a thread? Explain the different ways of creating threads (7M)
Multithreading in Java is a process of executing multiple threads simultaneously. A
thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process. Java Multithreading is mostly used
in games, animation, etc.

Two ways to implement Thread in Java is to use (i) Inheritance channel where
extends Thread class is used and (ii) Interface channel where implements Runnable
interface is used.

Java program to illustrate Thread creation using Runnable Interface


class NT1 implements Runnable
{
Thread t;
NT1()
{
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](1000);
}
}
}

9b What is the need of synchronization? Explain with an example how


synchronization is implemented in JAVA. (7M)
Java is a multi-threaded programming language and there is a higher risk to occur
race conditions. Because the same resource may be accessed by multiple threads at
the same time and may change the data. We can say that race condition is
a concurrency bug. It is closely related to deadlock in Java. It is a condition in which
the critical section (a part of the program where shared memory is accessed) is
concurrently executed by two or more threads. It leads to incorrect behavior of a
program. In layman terms, a race condition can be defined as, a condition in which
two or more threads compete together to get certain shared [Link] example, if
thread A is reading data from the linked list and another thread B is trying to delete
the same data. Output depends on thread who wins race in getting processor and a
Thread synchronization is required.

Java program to illustrate Thread synchronization


(i) Using synchronized methods
class Callme
{
synchronized public void callme(String mesg) //Synchronized method
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);

}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
[Link](msg);
}
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

9c Discuss values() and value Of() methods in Enumerations with suitable examples
(6M)
values() Method
The values() method returns an array containing all the constants of the enum in the
order they were declared. This method is implicitly declared by the compiler for all
enums.

valueOf(String name) Method


The valueOf(String name) method returns the enum constant of the specified enum
type with the specified name. The string must match exactly the identifier used to
declare the enum constant.
Example:
import [Link].*;
enum Apple
{
Jonathan(200),GoldenDel(150),RedDel(180),Winesap(300),Cortland(100);
private int price;
Apple(int price){ [Link]=price;}
int getPrice(){ return price;}
}
class Enum2
{
public static void main(String any[])
{
Apple ap=[Link];
[Link](ap);
Apple a[]=[Link]();
for(Apple x:a)
[Link](x+","+[Link]());
[Link]("Enter the apple breed");
Scanner s=new Scanner([Link]);
String applebreed=[Link]();
[Link]([Link](applebreed));
}
}

10a What is multithreading? Write a program to create multiple threads in JAVA (7M)
Multithreading in Java is a process of executing multiple threads simultaneously. A
thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process. Java Multithreading is mostly used
in games, animation, etc.
class NT1 implements Runnable
{
Thread t;
String tname;
NT1(String tname)
{
[Link]=tname;
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link](tname+":"+i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class MThread
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1("Thread1");
NT1 n2=new NT1("Thread2");
NT1 n3=new NT1("Thread3");

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}

10b Explain with an example how inter-thread communication is implemented in


JAVA. (7M)
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other. Cooperation (Inter-thread communication)
is a mechanism in which a thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
wait()
notify()
notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed. The current thread must own this object's
monitor, so it must be called from the synchronized method only otherwise it will
throw exception.
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

class Item
{
int data;
boolean lock=false;
synchronized void put(int data)
{
while(lock){
try{ wait();}
catch(InterruptedException e){ };
}
lock=true;
notify();
[Link]=data;

}
synchronized void get()
{
while(!lock)
{
try{ wait();}
catch(InterruptedException e){ };
}
lock=false;
notify();
[Link](data);
}
}
class Producer implements Runnable
{
Item i;
Thread t;
Producer(Item i)
{
this.i=i;
t=new Thread(this,"Producer");
}
public void run()
{
int j=0;
while(true)
{
[Link](j);
j++;
}
}
}
class Consumer implements Runnable
{
Item i;
Thread t;
Consumer(Item i)
{
this.i=i;
t=new Thread(this,"Consumer");
}
public void run()
{
while(true)
{
[Link]();
}
}
}
class PCS
{
public static void main(String any[]) throws InterruptedException
{
Item i=new Item();
Producer p=new Producer(i);
Consumer c= new Consumer(i);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

10c Explain auto-boxing/unboxing in expressions (6M)


In general, autoboxing and unboxing take place whenever a conversion into an object
or from an object is required. This applies to expressions. Within an expression, a
numeric object is automatically unboxed. The outcome of the expression is reboxed,
if necessary. For example, consider the following program:
Question Paper (Jan24) - BCS306A

1a Discuss the different data types supported by Java along with default values
and literals (8M)
In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language. ava provides a rich
set of data types that can be broadly categorized into primitive and reference types.
Primitive data types, such as byte, short, int, long, float, double, char, and boolean,
are the basic building blocks for data representation. They store simple values like
integers, floating-point numbers, characters, and boolean values. For instance, int
stores integers, double stores decimal values, boolean stores true or false, and char
stores a single character. These types are highly efficient and directly mapped to
memory. On the other hand, reference data types represent more complex data
structures and include objects, arrays, and user-defined classes or interfaces. For
example, a String is a reference type that holds sequences of characters, while arrays
allow storing multiple elements of the same type. While primitive types are faster and
use less memory, reference types provide flexibility and are used to model real-world
objects in a program.

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

1b Develop a Java program to convert Celsius temperature to Fahrenheit (6M)


import [Link];

public class CelsiusToFahrenheit {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);

// Ask the user to input temperature in Celsius


[Link]("Enter temperature in Celsius: ");
double celsius = [Link]();

// Convert the Celsius temperature to Fahrenheit


double fahrenheit = (celsius * 9/5) + 32;

// Display the result


[Link](celsius + " Celsius is equal to " + fahrenheit + " Fahrenheit.");

// Close the scanner


[Link]();
}
}
1c Justify the statement “Compile once and run anywhere” in Java (6M)
"Compile once and run anywhere" refers to the idea that a program, once compiled
into an intermediate or platform-independent format, can be executed on any system
without needing to be recompiled for each specific platform. This concept is central to
technologies like Java, which compiles code into bytecode that can be executed on
any device with a compatible Java Virtual Machine (JVM). The idea aims to enhance
portability, as the same codebase can run on multiple operating systems or
architectures without modification.
This is achieved by compiling source code into an intermediary format, such as
bytecode, rather than machine code tied to a specific operating system or hardware.
Java is a classic example of this, where the source code is compiled into bytecode
that the JVM interprets, enabling it to run on any platform that supports the JVM,
whether it's Windows, Linux, or macOS. This approach simplifies deployment and
ensures consistency across diverse environments.

2a List the various operators supported by Java. Illustrate the working of >> and
>>> with an example (8M)
Java provides many types of operators which can be used according to the need.
They are classified based on the functionality they provide. In this article, we will learn
about Java Operators and learn all their types. Operators in Java are the symbols
used for performing specific operations in Java. Operators make tasks like addition,
multiplication, etc which look easy although the implementation of these tasks is quite
complex.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of the initial number. Similar
effect to dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.
class BithShift
{
public static void main(String[] any)
{

int i=-1;
int res1=i>>24;
int res2=i>>>24;
[Link](res1);
[Link](res2);
}
}

2b Develop a Java program to add two matrices using command line arguments
(10M)
import [Link].*;
class Matrix
{
public static void readMatrix(int[][] A,int N)
{
Scanner kb=new Scanner([Link]);
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
A[i][j]=[Link]();
}
}
}
public static void addMatrix(int[][] A, int[][] B, int[][] C,int N)
{
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
}
public static void printMatrix(int[][] A,int N)
{
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
[Link](A[i][j]+" ");
}
[Link]();
}
}

public static void main(String[] any)


{
int N=[Link](any[0]);
int[][] A=new int[N][N];
int B[][]=new int[N][N];
int C[][]=new int[N][N];
[Link]("Enter Matrix A");
readMatrix(A,N);
[Link]("Enter Matrix B");
readMatrix(B,N);
addMatrix(A,B,C,N);
[Link]("Sum Matrix C");
printMatrix(C,N);
}
}

2c Explain the syntax of declaration of 2D arrays in Java (2M)


A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array,


that can hold a maximum of 12 elements. Java uses zero-based indexing, that is,
indexing of arrays in Java starts with 0 and not 1.

3a Examine Java garbage collection mechanism by classifying the generations of


Java heap (6M)
In java, garbage means unreferenced objects. Garbage Collection is process of
reclaiming the runtime unused memory automatically. In other words, it is a way to
destroy the unused objects. To do so, we were using free() function in C language and
delete() in C++. But, in java it is performed automatically. So, java provides better
memory management.
Advantages in Java:
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
Further garbage collection is done sporadically. The exact workings of a garbage
collector are not specified and are up to the garbage collector (usually implemented
by a VM of sorts, but not necessarily).

Java uses a generational garbage collection strategy, which divides the heap memory
into several generations based on the lifespan of objects.
1. Young Generation
• Purpose: This area stores new objects that are likely to have a short lifespan.
• Subdivisions:
o Eden Space: Most objects are initially allocated in this space. When
objects are created, they are placed in the Eden space.
o Survivor Spaces (S0 and S1): After the first garbage collection event
(minor GC), objects that survive are moved to one of the survivor
spaces. These spaces help in further promoting objects that live longer.
• Collection: Garbage collection in the young generation is frequent and is
known as Minor GC. It is relatively fast because the young generation usually
contains a small number of objects, most of which are short-lived.

2. Old Generation (Tenured Generation)


• Purpose: This area stores objects that have survived multiple garbage
collection cycles in the young generation and are considered to be long-lived.
• Collection: Garbage collection in the old generation occurs less frequently and
is known as Major GC or Full GC. These collections are more expensive
because they examine a larger pool of objects.

3. Permanent Generation (or Metaspace in newer versions of Java)


• Purpose: The permanent generation holds metadata about classes and
methods, such as class definitions and method information. In Java versions
prior to Java 8, this area was called the Permanent Generation.
• Collection: In newer Java versions (Java 8 and beyond), the permanent
generation was replaced by Metaspace, which resides in native memory
(outside the heap). Garbage collection here occurs during major GC events,
but this space doesn't have the same focus as the Young and Old generations.

3b Develop a Java program to find area of rectangle, area of circle and area of
triangle using method overloading concept. Call these methods from main
method with suitable inputs (10M)
public class AreaCalculator {

// Method to calculate area of rectangle


public double findArea(double length, double breadth) {
return length * breadth;
}

// Method to calculate area of circle


public double findArea(double radius) {
return [Link] * radius * radius;
}

// Method to calculate area of triangle


public double findArea(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();

// Calling the method to find area of rectangle


double rectangleArea = [Link](5.0, 3.0); // Length = 5, Breadth = 3
[Link]("Area of Rectangle: " + rectangleArea);

// Calling the method to find area of circle


double circleArea = [Link](7.0); // Radius = 7
[Link]("Area of Circle: " + circleArea);

// Calling the method to find area of triangle


double triangleArea = [Link](6.0, 4.0); // Base = 6, Height = 4
[Link]("Area of Triangle: " + triangleArea);
}
}
3c Interpret the general form a class with example (4M)
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. Objects are instances of the class.
Syntax to declare a class:

4a Outline the following keywords with example (i) this and (ii) static (6M)
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). This scenario is called “Instance variable hiding”.
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

Eg usage of this keyword:


Box(double depth,double width,double height)
{
[Link]=depth;
[Link]=width;
[Link]=height;
}
Instance variables depth, width and height are hidden by parameters with same
name. Hence to represent instance variables this keyword has been used.

The static keyword in Java is used for memory management mainly. We can apply
static keyword with variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Static variables:
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
o static variables are like global variables in Java
Static methods
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of
it.
Static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Static class
We can declare a class static by using the static keyword. A class can be declared
static only if it is a nested class. It does not require any reference of the outer class.
The property of the static class is that it does not allows us to access the non-static
members of the outer class.

Eg program illustrating static keyword:


class Stt
{
static int x;
static void displayagain()
{
[Link]("Display again.....");
}
static void display()
{
[Link](x);
displayagain();
}
static
{
[Link]("I am the starter");
}
public static void main(String any[])
{
Stt s1=new Stt();
Stt s2=new Stt();
Stt s3=new Stt();
s1.x=10;
[Link]();
[Link]();
[Link]();
/*[Link](s1.x);
[Link](s2.x);
[Link](s3.x);*/

}
}

4b Develop a class Empoyee which contains ‘name’, ‘designation’,’empid’ and


‘basic salary’ as instance variables and read() and write() methods. Using this
class, read and write five employee information from main method (10M)
import [Link];

class Employee {
// Instance variables
String name;
String designation;
int empId;
double basicSalary;

// Method to read employee information


public void read() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee Name: ");
name = [Link]();
[Link]("Enter Designation: ");
designation = [Link]();
[Link]("Enter Employee ID: ");
empId = [Link]();
[Link]("Enter Basic Salary: ");
basicSalary = [Link]();
[Link](); // Consume the leftover newline character
}

// Method to write/display employee information


public void write() {
[Link]("\nEmployee Information:");
[Link]("Name: " + name);
[Link]("Designation: " + designation);
[Link]("Employee ID: " + empId);
[Link]("Basic Salary: " + basicSalary);
}
}

public class Main {


public static void main(String[] args) {
// Create an array of Employee objects
Employee[] employees = new Employee[5];

// Loop to read and write information for 5 employees


for (int i = 0; i < 5; i++) {
employees[i] = new Employee(); // Initialize each employee object
[Link]("\nEnter details for Employee " + (i + 1));
employees[i].read(); // Read employee details
employees[i].write(); // Display employee details
}
}
}
4c Interpret with examples, types of constructors (4M)
Types of constructors:

Default constructors are provided by compiler only when programmer has not
declared any other constructor. It will be a zero argument empty body constructor.
Programmers can declare their own version of no-argument constructors and fill some
initialization code. Parameterized constructors have constructors with parameters.

Eg: Box constructors


Box(double depth,double width,double height)
{
[Link]=depth;
[Link]=width;
[Link]=height;
}
Box()
{

Invoking constructors:
Box b1=new Box(7.1,4,2);

5a Illustrate the use of super keyword in Java with suitable example. Also explain
dynamic method dispatch (10M)
The super keyword in Java is a reference variable which is used to refer immediate
parent class object. Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Eg:
class Animal{
String color="white";
Animal(){[Link]("animal is created");}
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
String color="black";
Dog()
{
super(); //Superclass constructor invoked
}
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//superclass variable
}
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link](); //call superclass methods
bark();
}

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

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call


to an overridden method is resolved at runtime rather than compile-time. In this
process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.
Example Java program to demonstrate Dynamic Method Dispatch:
class A
{
void disp()
{
[Link]("Display A");
}
}
class B extends A
{
void disp()
{
[Link]("Display B");
}
}
class C extends B
{
void disp()
{
[Link]("Display C");
}
}
class DMD
{
public static void main(String any[])
{
A a=new A();
B b=new B();
C c=new C();
A r;
r=a;
[Link](); //Dynamic Method Dispatch
r=b;
[Link](); //Dynamic Method Dispatch
r=c;
[Link](); //Dynamic Method Dispatch
}
}
5b Develop a JAVA program to create an interface Resizable with methods
resize(int radius) that allow an object to be resized. Create a class Circle that
implements the Resizable interface and implements the resize methods (10M)
interface Resizable
{
void resize (int radius);
}
class Circle implements Resizable
{
int radius;
Circle(int radius)
{
[Link]=radius;
}
public void resize (int radius)
{
[Link]=radius;
}
void disp()
{
[Link]("Radius:"+radius);
}
}
class IRC
{
public static void main(String args[])
{
Circle c=new Circle(3);
[Link]();
[Link](5);
[Link]();
}
}

6a Compare and contrast method overloading and method overriding with suitable
example (8M)
The differences between Method Overloading and Method Overriding in Java are
as follows:
Program example to demonstrate both:
// Superclass
class Animal {
// Overriding method (method in superclass)
public void sound() {
[Link]("Animal makes a sound");
}

// Method overloading: different parameter type


public void sleep() {
[Link]("Animal is sleeping");
}

// Method overloading: same method name, but with a parameter


public void sleep(int hours) {
[Link]("Animal is sleeping for " + hours + " hours");
}
}

// Subclass
class Dog extends Animal {
// Overriding method (method in subclass)
public void sound() {
[Link]("Dog barks");
}

// Method overloading in subclass: different parameter type


public void sleep(String timeOfDay) {
[Link]("Dog is sleeping at " + timeOfDay);
}
}

public class Main {


public static void main(String[] args) {
// Create an Animal object and call its methods
Animal animal = new Animal();
[Link](); // Calls Animal's sound method (overridden in Dog)
[Link](); // Calls Animal's sleep method (overloaded)
[Link](5); // Calls Animal's sleep method with parameter (overloaded)

// Create a Dog object and call its methods


Dog dog = new Dog();
[Link](); // Calls Dog's overridden sound method
[Link](); // Calls Animal's sleep method (overloaded in Animal)
[Link]("night"); // Calls Dog's sleep method (overloaded in Dog)
}
}
6b Define inheritance and list the different types of inheritance in Java (4M)
Single level inheritance
Only one class is derived from the parent class. In this type of inheritance, the
properties are derived from a single parent class and not more than that. As the
properties are derived from only a single base class the reusability of a code is
facilitated along with the addition of new features.
Multi-level Inheritance
The multi-level inheritance includes the involvement of at least two or more than
two classes. One class inherits the features from a parent class and the newly
created sub-class becomes the base class for another new class.
Hierarchical Inheritance
The type of inheritance where many subclasses inherit from one single class is
known as Hierarchical Inheritance. Hierarchical Inheritance a combination of more
than one type of inheritance. It is different from the multilevel inheritance, as the
multiple classes are being derived from one superclass. These newly derived
classes inherit the features, methods, etc, from this one superclass. This process
facilitates the reusability of a code and dynamic polymorphism (method overriding).
Multiple Inheritance
Multiple inheritances is a type of inheritance where a subclass can inherit features
from more than one parent class. Multiple inheritances should not be confused
with multi-level inheritance, in multiple inheritances the newly derived class can
have more than one superclass. And this newly derived class can inherit the
features from these superclasses it has inherited from, so there are no
restrictions. In Java, multiple inheritance does not exist directly. However, it can be
achieved through interfaces.
Hybrid Inheritance
Hybrid inheritance is a combination of more than two types of inheritances single
and multiple. It can be achieved through interfaces only as multiple inheritance is
not supported by Java. It is basically the combination of simple, multiple,
hierarchical inheritances
6c . Develop a JAVA program to create a class named shape. Create three sub
classes namely: circle, triangle and square, each class has two member
functions named draw () and erase (). Demonstrate polymorphism concepts by
developing suitable methods, defining member data and main program. (8M)
class Shape
{
void draw()
{
[Link]("My subclass will draw");
}
void erase()
{
[Link]("My subclass will erase");
}

}
class Triangle extends Shape
{
int x1,y1,x2,y2,x3,y3;
Triangle(int x1,int y1, int x2,int y2,int x3,int y3)
{
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
this.x3=x3;
this.y3=y3;
}
void draw()
{
[Link]("Triangle drawn");
}
void erase()
{
x1=x2=x3=y1=y2=y3=0;
[Link]("Triangle erased");
}
}
class Circle extends Shape
{
int x,y;
double radius;
Circle(int x,int y, double radius)
{
this.x=x;
this.y=y;
[Link]=radius;
}
void draw()
{
[Link]("Circle drawn");
}
void erase()
{
radius=0;
[Link]("Circle erased");
}
}
class Square extends Shape
{
int x,y;
int side;
Square(int x,int y, int side)
{
this.x=x;
this.y=y;
[Link]=side;
}
void draw()
{
[Link]("Square drawn");
}
void erase()
{
side=0;
[Link]("Square erased");
}

public class ShapeApp


{
public static void main(String args[])
{
Shape s=new Circle(2,3,4);
[Link]();
[Link]();
s=new Triangle(2,3,1,2,3,4);
[Link]();
[Link]();
s=new Square(2,3,4);
[Link]();
[Link]();
}
}

7a Explain various levels of access protections available for packages and their
implications with suitable examples. (10M)
Member access and packages in Java

public keyword
If a class member is “public” then it can be accessed from anywhere. The member
variable or method is accessed globally. This is the simplest way to provide access to
class members. However, we should take care of using this keyword with class
variables otherwise anybody can change the values. Usually, class variables are kept
as private and getter-setter methods are provided to work with them.
private keyword
If a class member is “private” then it will be accessible only inside the same class. This
is the most restricted access and the class member will not be visible to the outer
world. Usually, we keep class variables as private and methods that are intended to
be used only inside the class as private.
protected keyword
If class member is “protected” then it will be accessible only to the classes in the same
package and to the subclasses. This modifier is less restricted from private but more
restricted from public access. Usually, we use this keyword to make sure the class
variables are accessible only to the subclasses.
default access
If a class member doesn’t have any access modifier specified, then it’s treated with
default access. The access rules are similar to classes and the class member with
default access will be accessible to the classes in the same package only. This access
is more restricted than public and protected but less restricted than private.

Example code:
package mypackage;

public class Employee {


// public member
public String name;

// private member
private int empId;

// protected member
protected double salary;

// default member (no modifier)


int age;

// Constructor to initialize employee details


public Employee(String name, int empId, double salary, int age) {
[Link] = name;
[Link] = empId;
[Link] = salary;
[Link] = age;
}

// Public method to access private member empId


public int getEmpId() {
return empId;
}

// Default method to display employee information


void displayInfo() {
[Link]("Employee Name: " + name);
[Link]("Employee ID: " + getEmpId()); // Access private member via
method
[Link]("Salary: " + salary);
[Link]("Age: " + age);
}
}

// File: [Link]
package mypackage;

public class TestEmployee {


public static void main(String[] args) {
// Create an Employee object
Employee emp = new Employee("John Doe", 101, 50000, 30);

// Access public member


[Link]("Employee Name: " + [Link]);

// Access private member through public method


[Link]("Employee ID: " + [Link]());

// Access protected member


[Link]("Salary: " + [Link]);

// Access default member


[Link]("Age: " + [Link]);

// Call method to display all employee info


[Link]();
}
}
7b Build a Java program for banking application to throw an exception when a
person tries to withdraw the amount even though he/she has lesser than
minimum balance (Use custom exception) 10M
class BankingException extends Exception {
public BankingException(String message) {
super(message);
}
}
class BankAccount {
private String accountHolder;
private double balance;
private static final double MIN_BALANCE = 1000.0; // Minimum balance
requirement

// Constructor to initialize account details


public BankAccount(String accountHolder, double balance) {
[Link] = accountHolder;
[Link] = balance;
}

// Deposit method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount);
} else {
[Link]("Invalid deposit amount.");
}
}
// Withdrawal method with exception handling
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > 0) {
if (balance - amount < MIN_BALANCE) {
throw new BankingException("Withdrawal denied. Insufficient balance to
maintain minimum required balance of " + MIN_BALANCE);
} else {
balance -= amount;
[Link]("Withdrawn: " + amount);
}
} else {
[Link]("Invalid withdrawal amount.");
}
}

// Method to check the balance


public void checkBalance() {
[Link]("Current balance: " + balance);
}
}

// Main Class to test the program


public class BankingApp {
public static void main(String[] args) {
// Create a BankAccount object
BankAccount account = new BankAccount("John Doe", 5000.0);

// Checking initial balance


[Link]();

// Deposit money
[Link](2000.0);
[Link]();

// Trying to withdraw with insufficient balance to maintain minimum


try {
[Link](5000.0); // This should throw the exception
[Link]();
} catch (InsufficientBalanceException e) {
[Link]([Link]());
}

// Checking balance after attempted withdrawals


[Link]();
}
}

8a Define Exception. Explain exception handling mechanism provided in Java


with syntax and example (10M)
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained. In Java,
an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime. Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc. The core advantage of exception handling is to maintain the
normal flow of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place
an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies


that there may occur an exception in the method. It doesn't throw
an exception. It is always used with method signature.

Example Exception handling program:


class Exc
{
public static void main(String any[])
{
int a=5,b=0;
int arr[]={1,2,3};
try{
[Link](a/b);
[Link](arr[-1]);
}

catch(ArithmeticException e)
{
[Link]("specific");
[Link]();
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]();
}
catch(Exception e)
{
[Link]("generic");
[Link](); //Display exception details
}
[Link]("I continue");
}
}
8b Create a package called balance containing class AccountBalance with method
displayBalance(). Import this class in another package to access method of
Account class. (10M)
package balance;
public class AccountBalance
{
double bal;
String name;
String accno;
public AccountBalance(String accno, String name,double bal)
{
[Link]=accno;
[Link]=bal;
[Link]=name;
}
public void displayBalance()
{
[Link](“Account Number=”+accno+"Account
Name="+name+", Balance="+bal);
}
}

In the folder above this, create following main class:


import balance.*;
class AC
{
public static void main(String any[])
{
AccountBalance a1=new AccountBalance(“101”,"James",20000);
[Link] ();
}
}

9a Define thread and explain different ways of creating thread (6M)


A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking. However, we use
multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process. Java Multithreading is mostly used
in games, animation, etc.

Two ways to implement Thread in Java is to use (i) Inheritance channel where
extends Thread class is used and (ii) Interface channel where implements Runnable
interface is used.

Java program to illustrate Thread creation using Runnable Interface


class NT1 implements Runnable
{
Thread t;
NT1()
{
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
[Link](i);
try{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]();
}
}
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
[Link]();
for(int i=5;i<10;i++)
{
[Link](i);
[Link](1000);
}
}
}
9b How synchronization can be achieved between threads in Java? Explain with
an example (6M)
ava is a multi-threaded programming language and there is a higher risk to occur race
conditions. Because the same resource may be accessed by multiple threads at the
same time and may change the data. We can say that race condition is
a concurrency bug. It is closely related to deadlock in Java. It is a condition in which
the critical section (a part of the program where shared memory is accessed) is
concurrently executed by two or more threads. It leads to incorrect behavior of a
program. In layman terms, a race condition can be defined as, a condition in which
two or more threads compete together to get certain shared [Link] example,
if thread A is reading data from the linked list and another thread B is trying to delete
the same data. Output depends on thread who wins race in getting processor and a
Thread synchronization is required.

Java program to illustrate Thread synchronization


(i) Using synchronized methods
class Callme
{
synchronized public void callme(String mesg) //Synchronized method
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
[Link](msg);

}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
[Link]("["+mesg);
try{
[Link](1000);
}
catch(InterruptedException e){ };
[Link]("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
[Link]=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
[Link](msg);
}
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();

SThread s1=new SThread("AIML",c);


SThread s2=new SThread("AIDS",c);
SThread s3=new SThread("AIBI",c);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

9c Develop a Java program for automatic conversion of wrapper class type into
corresponding primitive type that demonstrates unboxing (8M)
The automatic conversion of primitive data types into its equivalent Wrapper type is
known as boxing and opposite operation is known as unboxing. This is the new feature
of Java5. So java programmer doesn't need to write the conversion code
class ABU
{
static int m(Integer i)
{
return i;
}
public static void main(String any[])
{
Integer iob;
int i=10;
iob=i; //Autoboxing
Integer iob1=m(30); //1. Autboxing, [Link] and 3. Autoboxing
[Link](i+iob);
[Link](iob1);
}
}
10a Summarize the type wrappers supported in Java (6M)
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic conversion of
primitive into an object is known as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with
objects many times like in Collections, Serialization, Synchronization, etc. Let
us see the different scenarios, where we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass
a primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
[Link] package: The [Link] package provides the utility classes to deal with
objects.
Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only.

Primitive Types and their Wrapper classes

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

10b Explain autoboxing/unboxing that happens in expressions and operators (6M)


In general, autoboxing and unboxing take place whenever a conversion into an object
or from an object is required. This applies to expressions. Within an expression, a
numeric object is automatically unboxed. The outcome of the expression is reboxed,
if necessary. For example, consider the following program:

10c Develop a program to create a class MyThread in this class a constructor, call
the base class constructor, using super and start the thread. The run method of
the class starts after this. It can be observed that both main thread and created
child thread are executed concurrently (8M)
public class Thread2 extends Thread
{
String name;
Thread2(String name)
{
super(name);
}
public void run()
{
[Link](getName()+" started");
try{[Link](500);}
catch(InterruptedException e){ };
[Link](getName()+" ended");
}
public static void main(String args[]) throws InterruptedException{
Thread2 t1=new Thread2("first");
[Link]();
[Link]("Main started..");
[Link]();
[Link]("Main ended..");
}
}

Common questions

Powered by AI

Exception handling is critical for maintaining robustness in Java programs that interact with external resources like files or databases because these operations are prone to produce runtime errors such as IOExceptions or SQLExceptions. By catching and handling these exceptions, a program can prevent crashes, ensure data integrity, handle errors gracefully, and maintain application stability. This allows the program to either perform alternative logic, inform the user, or log the error for debugging purposes without halting execution .

When you extend the Thread class, you cannot inherit from any other class because Java does not support multiple inheritance. This limits your class design choices. On the other hand, implementing the Runnable interface allows a class to extend another class while still capable of executing in a thread. The Runnable interface is generally preferred due to this versatility, as it allows for an application's architecture to be more flexible and function more modularly .

A race condition in multithreading is when two or more threads access shared resources concurrently and try to change them, leading to unpredictable and incorrect behavior of the program. It is considered dangerous because it can cause data inconsistencies and runtime errors. This occurs when the critical section of code is accessed by multiple threads without proper synchronization. For example, if one thread reads data from a resource while another deletes it simultaneously, it can result in a runtime error .

Thread synchronization helps prevent race conditions by ensuring that only one thread can access the critical section of code that interacts with shared resources at any given time. This is typically achieved using synchronized methods or blocks, which lock the object the thread is working on, preventing other threads from accessing the same resource until the lock is released .

Exception handling in Java maintains the flow of an application by catching runtime errors, allowing the program to continue executing instead of crashing. Using keywords like 'try', 'catch', 'finally', 'throw', and 'throws', it ensures the program can handle exceptions gracefully. For instance, a try block is used to wrap code that might throw an exception, followed by one or more catch blocks that handle specific exceptions, and finally blocks that execute code such as cleanup operations, regardless of whether an exception occurred .

A synchronized block provides a finer level of synchronization than a synchronized method by allowing developers to lock only the critical section of a method instead of the entire method, which can lead to increased efficiency by reducing the time threads spend locked. However, the potential downside is the increased complexity in writing and understanding code as developers must carefully manage the critical sections. If not done correctly, it may result in deadlocks or insufficient protection against race conditions .

In performance-critical Java applications, using synchronized blocks over synchronized methods can lead to better performance since they allow for more granular control over locks, resulting in less contention among threads. By synchronizing only the necessary part of the code, rather than the entire method, the application can reduce the time that threads spend waiting for locks, thereby enhancing throughput and responsiveness. However, this approach requires careful design to avoid complex code that may lead to scalability and maintenance challenges .

The `this` keyword in Java helps avoid variable shadowing by distinguishing between instance variables and method/constructor parameters with the same name. It refers to the current class instance. In a constructor, for example, if a parameter name conflicts with an instance variable name, `this` can be used to explicitly indicate the instance variable. For example, in the constructor Box(double depth,double width,double height), using `this.depth=depth;` clarifies that the instance variable `depth` is being assigned the parameter value .

The static keyword in Java is used for memory management. When applied to variables, it indicates that the variable is shared across all instances of a class, rather than each instance having its own copy. Static variables get memory only once at class loading time. Static methods, on the other hand, belong to the class itself rather than any specific instance of the class, and can be called without creating an instance. They can access static data members directly but cannot access instance variables .

Inter-thread communication enhances multithreaded applications by allowing threads to communicate state changes and synchronize their actions without being continuously active, reducing unnecessary processor usage. It allows a thread that produces data to inform another thread when it is ready to use, which improves efficiency and resource utilization. This is achieved through key methods like wait(), notify(), and notifyAll() that manage thread states and access to shared resources effectively .

You might also like