Java Multithreading Overview and Concepts
Java Multithreading Overview and Concepts
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.
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.
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)
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.
105
sleep() It sleeps a thread for the specified amount of time.
currentThread() It returns a reference to the currently executing thread object.
}
}
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);
}
}
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
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();
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();
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.
}
synchronized void get()
{
while(!lock)
{
try{ wait();}
catch(InterruptedException e){ };
}
lock=false;
notify();
113
}
}
}
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]());
}
}
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.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
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
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.
123
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
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).
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
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];
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]();
}
}
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
}//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].*;
}
}
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();
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);
}
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);
}
}
}
}
}
132
Model Question Paper-I/II with effect from 2023-24 (CBCS
Scheme) - BCS306A
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
• <<, 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
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
}
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.
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.
}
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]);
}
}
}
}
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);
}
}
Example code:
// First interface
interface Animal {
void eat();
void sleep();
}
// Second interface
interface Pet {
void play();
void beFriendly();
}
class Override
{
public static void main(String any[])
{
B b=new B();
[Link](5);
}
}
class AB
{
public static void main(String[] any)
{
B b=new B();
}
}
}
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.
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.
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.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
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.
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...");
}
}
}
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.
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();
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.
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]());
}
}
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]();
}
}
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
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]();
}
}
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.
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 {
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
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.
}
}
class Employee {
// Instance variables
String name;
String designation;
int empId;
double basicSalary;
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.
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]();
}}
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");
}
// Subclass
class Dog extends Animal {
// Overriding method (method in subclass)
public void sound() {
[Link]("Dog barks");
}
}
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");
}
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;
// private member
private int empId;
// protected member
protected double salary;
// File: [Link]
package mypackage;
// 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.");
}
}
// Deposit money
[Link](2000.0);
[Link]();
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.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
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);
}
}
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.
}
}
class SynT
{
public static void main(String any[]) throws InterruptedException
{
Callme c=new Callme();
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.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
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..");
}
}
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 .