0% found this document useful (0 votes)
33 views

Model Question Paper-Solutions

The document is a model question paper for the B.E. Degree Examination in Object Oriented Programming with JAVA, covering various topics such as lexical issues in Java, array operations, bitwise shifting, object-oriented principles, constructors, recursion, access specifiers, and method calling conventions. It includes programming tasks, explanations of concepts, and examples related to Java programming. The paper is structured into sections with specific questions and programming exercises for students to demonstrate their understanding of Java programming concepts.

Uploaded by

NO IR
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)
33 views

Model Question Paper-Solutions

The document is a model question paper for the B.E. Degree Examination in Object Oriented Programming with JAVA, covering various topics such as lexical issues in Java, array operations, bitwise shifting, object-oriented principles, constructors, recursion, access specifiers, and method calling conventions. It includes programming tasks, explanations of concepts, and examples related to Java programming. The paper is structured into sections with specific questions and programming exercises for students to demonstrate their understanding of Java programming concepts.

Uploaded by

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

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 java.util.*;
class Matrix
{
public static void readMatrix(int[][] A,int N)
{
Scanner kb=new Scanner(System.in);
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
A[i][j]=kb.nextInt();
}
}
}
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++)
{
System.out.print(A[i][j]+" ");
}
System.out.println();
}
}

public static void main(String[] any)


{
int N=Integer.parseInt(any[0]);
int[][] A=new int[N][N];
int B[][]=new int[N][N];
int C[][]=new int[N][N];
System.out.println("Enter Matrix A");
readMatrix(A,N);
System.out.println("Enter Matrix B");
readMatrix(B,N);
addMatrix(A,B,C,N);
System.out.println("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;
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("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 < array.length - 1; i++) {
for (int j = 0; j < array.length - 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
System.out.println("Sorted array:");
for (int i = 0; i < array.length; i++) {
System.out.print(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)
{
this.depth=depth;
this.width=width;
this.height=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);
System.out.println("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;
System.out.println(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;
System.out.println("Before:"+a+","+b);
swap(a,b);
System.out.println("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;
System.out.println("Before:"+o1.a+","+o1.b);
swap(o1);
System.out.println("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)
{
this.max=max;
top=-1;
data=new int[max];
}
void push(int ele)
{
if(top==max-1)
{
System.out.println("Stack Overflow");
return;
}
data[++top]=ele;
}
void pop()
{
if(top==-1)
{
System.out.println("Stack Overflow");
return;
}
System.out.println("Popped Element="+data[top--]);
}
void display()
{
for(int i=top;i>=0;i--)
{
System.out.println(data[i]);
}
}
}

public class StackApp


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

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)
{
this.depth=depth;
this.width=width;
this.height=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)
{
this.width=width;
this.height=height;
this.depth=depth;
}
void disp()
{
System.out.println("Box...");
}

}
class WeightBox extends Box
{
double weight;
int x=3;
WeightBox(double width,double height,double depth,double weight)
{
super(width,height,depth);
this.weight=weight;
}
void disp()
{
System.out.println("WeightBox...");
super.disp();
}

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

class Inheritance2
{
public static void main(String[] any)
{
WeightBox w1=new WeightBox(1.2,3.4,1.1,20.0);
w1.disp();
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() {


System.out.println("Dog is eating.");
}
public void sleep() {
System.out.println("Dog is sleeping.");
}
public void play() {
System.out.println("Dog is playing.");
}
public void beFriendly() {
System.out.println("Dog is being friendly.");
}

public static void main(String[] args) {


Dog myDog = new Dog();
myDog.eat();
myDog.sleep();
myDog.play();
myDog.beFriendly();
}
}
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)
{
System.out.println("A:"+x);
}
}
class B extends A
{
void disp()
{
System.out.println("plain B");
}
void disp(int x)
{
System.out.println("B:"+x);
super.disp(x);
}
}

class Override
{
public static void main(String any[])
{
B b=new B();
b.disp(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()
{
System.out.println("A");
}
}
class B extends A
{
B()
{
System.out.println("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(){System.out.println("animal is created");}
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
String color="black";
Dog()
{
super(); //Superclass constructor invoked
}
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//superclass variable
}
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat(); //call superclass methods
bark();
}

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

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()
{
System.out.println("D2");
}
void disp3()
{
System.out.println("D3");
}
}
class B extends A
{
void disp1()
{
System.out.println("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 java.util.*;
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)
{
this.accno=accno;
this.bal=bal;
this.name=name;
}
public void show()
{
System.out.println(“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);
a1.show();
}
}

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
System.out.println("Caught an IllegalAccessException: " + e.getMessage());
e.printStackTrace();
}
}

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 java.util.*;
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)
{
this.accno=accno;
this.bal=bal;
this.name=name;
}
public void show()
{
System.out.println(“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);
a1.show();
}
}

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)
{
this.message=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=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
try{
System.out.println(compute(a,b));
}
catch(DivideByZero z)
{
System.out.println(z);
}
finally{
System.out.println("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{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(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)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("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++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
n1.t.start();
for(int i=5;i<10;i++)
{
System.out.println(i);
Thread.sleep(500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
n1.start();
for(int i=5;i<10;i++)
{
System.out.println(i);
Thread.sleep(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 resources.For 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
{
System.out.println("["+mesg);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){ };
System.out.println("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
this.msg=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
c.callme(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);
s1.t.start();
s2.t.start();
s3.t.start();
s1.t.join();
s2.t.join();
s3.t.join();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
System.out.println("["+mesg);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){ };
System.out.println("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
this.msg=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
c.callme(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);
s1.t.start();
s2.t.start();
s3.t.start();
s1.t.join();
s2.t.join();
s3.t.join();
}
}

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 java.util.*;
enum Apple
{
Jonathan(200),GoldenDel(150),RedDel(180),Winesap(300),Cortland(100);
private int price;
Apple(int price){ this.price=price;}
int getPrice(){ return price;}
}
class Enum2
{
public static void main(String any[])
{
Apple ap=Apple.Winesap;
System.out.println(ap);
Apple a[]=Apple.values();
for(Apple x:a)
System.out.println(x+","+x.getPrice());
System.out.println("Enter the apple breed");
Scanner s=new Scanner(System.in);
String applebreed=s.nextLine();
System.out.println(Apple.valueOf(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)
{
this.tname=tname;
t=new Thread(this,"my thread");
}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(tname+":"+i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
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");

n1.t.start();
n2.t.start();
n3.t.start();
n1.t.join();
n2.t.join();
n3.t.join();
System.out.println(n1.t.isAlive());
System.out.println(n2.t.isAlive());
System.out.println(n3.t.isAlive());
}
}

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();
this.data=data;

}
synchronized void get()
{
while(!lock)
{
try{ wait();}
catch(InterruptedException e){ };
}
lock=false;
notify();
System.out.println(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)
{
i.put(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)
{
i.get();
}
}
}
class PCS
{
public static void main(String any[]) throws InterruptedException
{
Item i=new Item();
Producer p=new Producer(i);
Consumer c= new Consumer(i);
p.t.start();
c.t.start();
p.t.join();
c.t.join();
}
}

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 java.util.Scanner;

public class CelsiusToFahrenheit {


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

// Ask the user to input temperature in Celsius


System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();

// Convert the Celsius temperature to Fahrenheit


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

// Display the result


System.out.println(celsius + " Celsius is equal to " + fahrenheit + " Fahrenheit.");

// Close the scanner


scanner.close();
}
}
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;
System.out.println(res1);
System.out.println(res2);
}
}

2b Develop a Java program to add two matrices using command line arguments
(10M)
import java.util.*;
class Matrix
{
public static void readMatrix(int[][] A,int N)
{
Scanner kb=new Scanner(System.in);
for(int i=0;i<=N-1;i++)
{
for(int j=0;j<=N-1;j++)
{
A[i][j]=kb.nextInt();
}
}
}
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++)
{
System.out.print(A[i][j]+" ");
}
System.out.println();
}
}

public static void main(String[] any)


{
int N=Integer.parseInt(any[0]);
int[][] A=new int[N][N];
int B[][]=new int[N][N];
int C[][]=new int[N][N];
System.out.println("Enter Matrix A");
readMatrix(A,N);
System.out.println("Enter Matrix B");
readMatrix(B,N);
addMatrix(A,B,C,N);
System.out.println("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 Math.PI * 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 = calculator.findArea(5.0, 3.0); // Length = 5, Breadth = 3
System.out.println("Area of Rectangle: " + rectangleArea);

// Calling the method to find area of circle


double circleArea = calculator.findArea(7.0); // Radius = 7
System.out.println("Area of Circle: " + circleArea);

// Calling the method to find area of triangle


double triangleArea = calculator.findArea(6.0, 4.0); // Base = 6, Height = 4
System.out.println("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)
{
this.depth=depth;
this.width=width;
this.height=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()
{
System.out.println("Display again.....");
}
static void display()
{
System.out.println(x);
displayagain();
}
static
{
System.out.println("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;
s1.display();
s2.display();
s3.display();
/*System.out.println(s1.x);
System.out.println(s2.x);
System.out.println(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 java.util.Scanner;

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

// Method to read employee information


public void read() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Name: ");
name = sc.nextLine();
System.out.print("Enter Designation: ");
designation = sc.nextLine();
System.out.print("Enter Employee ID: ");
empId = sc.nextInt();
System.out.print("Enter Basic Salary: ");
basicSalary = sc.nextDouble();
sc.nextLine(); // Consume the leftover newline character
}

// Method to write/display employee information


public void write() {
System.out.println("\nEmployee Information:");
System.out.println("Name: " + name);
System.out.println("Designation: " + designation);
System.out.println("Employee ID: " + empId);
System.out.println("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
System.out.println("\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)
{
this.depth=depth;
this.width=width;
this.height=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(){System.out.println("animal is created");}
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
String color="black";
Dog()
{
super(); //Superclass constructor invoked
}
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//superclass variable
}
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat(); //call superclass methods
bark();
}

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

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()
{
System.out.println("Display A");
}
}
class B extends A
{
void disp()
{
System.out.println("Display B");
}
}
class C extends B
{
void disp()
{
System.out.println("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;
r.disp(); //Dynamic Method Dispatch
r=b;
r.disp(); //Dynamic Method Dispatch
r=c;
r.disp(); //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)
{
this.radius=radius;
}
public void resize (int radius)
{
this.radius=radius;
}
void disp()
{
System.out.println("Radius:"+radius);
}
}
class IRC
{
public static void main(String args[])
{
Circle c=new Circle(3);
c.disp();
c.resize(5);
c.disp();
}
}

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() {
System.out.println("Animal makes a sound");
}

// Method overloading: different parameter type


public void sleep() {
System.out.println("Animal is sleeping");
}

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


public void sleep(int hours) {
System.out.println("Animal is sleeping for " + hours + " hours");
}
}

// Subclass
class Dog extends Animal {
// Overriding method (method in subclass)
public void sound() {
System.out.println("Dog barks");
}

// Method overloading in subclass: different parameter type


public void sleep(String timeOfDay) {
System.out.println("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();
animal.sound(); // Calls Animal's sound method (overridden in Dog)
animal.sleep(); // Calls Animal's sleep method (overloaded)
animal.sleep(5); // Calls Animal's sleep method with parameter (overloaded)

// Create a Dog object and call its methods


Dog dog = new Dog();
dog.sound(); // Calls Dog's overridden sound method
dog.sleep(); // Calls Animal's sleep method (overloaded in Animal)
dog.sleep("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()
{
System.out.println("My subclass will draw");
}
void erase()
{
System.out.println("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()
{
System.out.println("Triangle drawn");
}
void erase()
{
x1=x2=x3=y1=y2=y3=0;
System.out.println("Triangle erased");
}
}
class Circle extends Shape
{
int x,y;
double radius;
Circle(int x,int y, double radius)
{
this.x=x;
this.y=y;
this.radius=radius;
}
void draw()
{
System.out.println("Circle drawn");
}
void erase()
{
radius=0;
System.out.println("Circle erased");
}
}
class Square extends Shape
{
int x,y;
int side;
Square(int x,int y, int side)
{
this.x=x;
this.y=y;
this.side=side;
}
void draw()
{
System.out.println("Square drawn");
}
void erase()
{
side=0;
System.out.println("Square erased");
}

public class ShapeApp


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

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) {
this.name = name;
this.empId = empId;
this.salary = salary;
this.age = age;
}

// Public method to access private member empId


public int getEmpId() {
return empId;
}

// Default method to display employee information


void displayInfo() {
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + getEmpId()); // Access private member via
method
System.out.println("Salary: " + salary);
System.out.println("Age: " + age);
}
}

// File: TestEmployee.java
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


System.out.println("Employee Name: " + emp.name);

// Access private member through public method


System.out.println("Employee ID: " + emp.getEmpId());

// Access protected member


System.out.println("Salary: " + emp.salary);

// Access default member


System.out.println("Age: " + emp.age);

// Call method to display all employee info


emp.displayInfo();
}
}
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) {
this.accountHolder = accountHolder;
this.balance = balance;
}

// Deposit method
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("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;
System.out.println("Withdrawn: " + amount);
}
} else {
System.out.println("Invalid withdrawal amount.");
}
}

// Method to check the balance


public void checkBalance() {
System.out.println("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


account.checkBalance();

// Deposit money
account.deposit(2000.0);
account.checkBalance();

// Trying to withdraw with insufficient balance to maintain minimum


try {
account.withdraw(5000.0); // This should throw the exception
account.checkBalance();
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}

// Checking balance after attempted withdrawals


account.checkBalance();
}
}

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{
System.out.println(a/b);
System.out.println(arr[-1]);
}

catch(ArithmeticException e)
{
System.out.println("specific");
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("generic");
e.printStackTrace(); //Display exception details
}
System.out.println("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)
{
this.accno=accno;
this.bal=bal;
this.name=name;
}
public void displayBalance()
{
System.out.println(“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);
a1.displayBalance ();
}
}

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++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread1
{
public static void main(String any[]) throws InterruptedException
{
NT1 n1=new NT1();
n1.t.start();
for(int i=5;i<10;i++)
{
System.out.println(i);
Thread.sleep(500);
}
}
}

Java program to illustrate Thread creation using Thread class


class NT2 extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Thread2
{
public static void main(String any[]) throws InterruptedException
{
NT2 n1=new NT2();
n1.start();
for(int i=5;i<10;i++)
{
System.out.println(i);
Thread.sleep(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 resources.For 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
{
System.out.println("["+mesg);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){ };
System.out.println("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
this.msg=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
c.callme(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);
s1.t.start();
s2.t.start();
s3.t.start();
s1.t.join();
s2.t.join();
s3.t.join();
}
}

(ii) Using synchronized block


class Callme
{
synchronized public void callme(String mesg)
{
System.out.println("["+mesg);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){ };
System.out.println("]");
}
}
class SThread implements Runnable
{
Thread t;
String msg;
Callme c;
SThread(String msg,Callme c)
{
this.msg=msg;
this.c=c;
t=new Thread(this);
}
public void run()
{
synchronized(c) //Synchronized block
{
c.callme(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);
s1.t.start();
s2.t.start();
s3.t.start();
s1.t.join();
s2.t.join();
s3.t.join();
}
}

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, 2.Autounboxing and 3. Autoboxing
System.out.println(i+iob);
System.out.println(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.
java.util package: The java.util 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()
{
System.out.println(getName()+" started");
try{Thread.sleep(500);}
catch(InterruptedException e){ };
System.out.println(getName()+" ended");
}
public static void main(String args[]) throws InterruptedException{
Thread2 t1=new Thread2("first");
t1.start();
System.out.println("Main started..");
t1.join();
System.out.println("Main ended..");
}
}

You might also like