2-2 OOP Java QB-Answers
2-2 OOP Java QB-Answers
Unit 1
Part A
Bloom’s
SI. No. Question
Taxonomy Level
Define object and class. Give an example
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
Public class Dog { } // Dog is a class
1 L1
Object − Objects have states and behaviors. Example: A dog has states -
color, name, breed as well as behaviors – wagging the tail, barking, eating.
An object is an instance of a class.
Dog d1 = new Dog(); // d1 is an object
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
What is the use of super keyword? L1
The super keyword refers to superclass (parent) objects. It is used to call
8 superclass methods, and to access the superclass constructor. The most
common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
What is the use of final keyword in java? L1
The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or
9 override).
The final keyword is useful when you want a variable to always store the
same value, like PI (3.14159...).
The final keyword is called a "modifier"
Differentiate class, abstract class, and interface L1
Class
It can be directly instantiated using the new keyword
Abstract class
Abstract class cannot be instantiated.
Abstract class can have abstract and non-abstract methods.
10 Abstract class doesn't support multiple inheritance.
Abstract class can have final, non-final, static and non-static variables.
Interface can have only abstract methods. Since Java 8, it can have default
and static methods also.
Interface supports multiple inheritance.
Interface has only static and final
variables.
Part B
Bloom’s
SI.
Question Taxonomy
No.
Level
a. What are the differences between object-oriented programming vs procedural oriented
programming?
Type of instances
variables have a type – - int data=30;
Static binding
class Dog{
private void eat(){System.out.println("dog is eating...");}
Dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
In case of method
overloading, parameter must In case of method overriding, parameter must be same.
be different.
Method overloading is the
Method overriding is the example of run time
example of compile time
polymorphism.
polymorphism.
In java, method overloading
can't be performed by changing
return type of the method
Return type must be same or covariant in method
only. Return type can be same
overriding.
or different in method
overloading. But you must
have to change the parameter.
public class Test {
public static void main(String[] args) {
public class Test { A a = new A();
public static void a.p(10);
main(String[] args) { a.p(10.0);
public add () }
{ }
}
public add (int i, int j) class B {
{ public void p(double i) {
} System.out.println(i * 2);
public add (int k, double d) }
{ }
}
} class A extends B {
} // This method overrides the method in B
public void p(double i) {
System.out.println(i); } }
• Java Is Object-Oriented
Java is inherently object-oriented. Although many object-oriented languages began
strictly as procedural languages, Java was designed from the start to be object-
oriented. Object-oriented programming (OOP) is a popular programming approach
that is replacing traditional procedural programming techniques.
One of the central issues in software development is how to reuse code. Object-
oriented programming provides great flexibility, modularity, clarity, and reusability
through encapsulation, inheritance, and polymorphism
• Java Is Distributed
Distributed computing involves several computers working together on a network.
Java is designed to make distributed computing easy. Since networking capability is
inherently integrated into Java, writing network programs is like sending and
receiving data to and from a file.
• Java Is Interpreted
You need an interpreter to run Java programs. The programs are compiled into the
Java Virtual Machine code called bytecode. The bytecode is machine-independent
and can run on any machine that has a Java interpreter, which is part of the Java
Virtual Machine (JVM).
5 L1
• Java Is Robust
Java compilers can detect many problems that would first show up at execution
time in other languages.
Java has eliminated certain types of error-prone programming constructs found in
other languages.
Java has a runtime exception-handling feature to provide programming support for
robustness.
• Java Is Secure
Java implements several security mechanisms to protect your system against harm
caused by stray programs.
• Java Is Architecture-Neutral
Write once, run anywhere
With a Java Virtual Machine (JVM), you can write one program that will run on
any platform.
• Java Is Portable
Because Java is architecture neutral, Java programs are portable. They can be run
on any platform without being recompiled.
• Java's Performance
Java’s performance Because Java is architecture neutral, Java programs are
portable. They can be run on any platform without being recompiled.
• Java Is Multithreaded
Multithread programming is smoothly integrated in Java, whereas in other
languages you have to call procedures specific to the operating system to enable
multithreading.
• Java Is Dynamic
Java was designed to adapt to an evolving environment. New code can be loaded on
the fly without recompilation. There is no need for developers to create, and for
users to install, major new software versions. New features can be incorporated
transparently as needed.
c. Create a class Cylinder with attributes radius and height, each of which has a default value
of 1. Provide a method that calculates the cylinders’ volume, which is pi multiplied by
the square of the radius multiplied by the height. It has set and get methods for both radius
and height. The set method should verify that radius and height are positive numbers.
Write a program to test class Cylinder.
import java.util.Scanner;
class CylVol1 {
double rad=1.0;
double ht=1.0;
double pi=3.141592653;
CylVol1() {
System.out.println("Calculating the Volume of a Cylinder"); }
public void setValues(double r, double h) {
if(r>0 & h>0) {
rad=r;
ht=h; }
else if(r<0 & h<0) {
rad=0;
ht=0;
System.out.println(" Please Enter a positive values to get the volume"); } }
public double[] getValues() {
double ret[]=new double[3];
ret[0]=rad;
ret[1]=ht;
ret[2]=pi;
return ret;
}
}
d.
public class CylVol{
public static void main(String[] args) {
// TODO Auto-generated method stub
CylVol1 cvol=new CylVol1();
Scanner s=new Scanner(System.in);
double radius;
double height;
double vol;
//double val[]=new double[2];
System.out.println("Enter a value for the Radius");
radius=s.nextDouble();
System.out.println("Enter a value for the Height");
height=s.nextDouble();
cvol.setValues(radius,height);
double val[]=cvol.getValues();
vol= val[2]*val[0]*val[0]*val[1];
System.out.println("The volume of the Cylinder is: "+ vol);
}
}} }
Output:
Calculating the Volume of a Cylinder
Enter a value for the Radius
5
Enter a value for the Height
5
The volume of the Cylinder is: 246.74010993458947
What is the use of inheritance? List the types of inheritance. Write a simple java program
for multilevel inheritance.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java?
6 L2
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Types:
Single, Multi Level, Multiple, Hybrid, Hierarchical Inheritance
Multiple inheritance is not supported in java through class. (to prevent ambiguity )
To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
// Multilevel Hierarchy
class A {
void funcA() { System.out.println("This is class A");
}}
class B extends A {
void funcB() { System.out.println("This is class B");
}}
class C extends B {
void funcC() {System.out.println("This is class C");
}}
public class Demo {
public static void main(String args[])
{ C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC(); } }
What is the use of Math class? Why can’t we create object for Math class? Write a java
program that will illustrate the methods available in Math class.
The mathematical operations to be done very quick and easily through the Math class.
A non-instance method is called a static method. A static method can be invoked without
using an object.
All the methods defined in the Math class are static methods. They are not tied to a specific
object instance.
import java.util.Scanner;
public class MathSample {
public static void main(String[] args)
{ double d=0;
System.out.println("The sin(0) is "+ Math.sin(d));
System.out.println("The cos(0) is "+ Math.cos(d));
System.out.println("The asin(0) is "+ Math.asin(d));
d=90;
System.out.println("The sin(90) is "+ Math.sin(d));
System.out.println("The cos(90) is "+ Math.cos(d));
7 L2
System.out.println("The asin(90) is "+ Math.asin(d));
System.out.println("The tan(90) is "+Math.tan(d));
System.out.println("The atan(90) is "+ Math.atan(d));
System.out.println("The e power 1 is "+ Math.exp(1));
System.out.println("The log 1 is "+ Math.log(1));
System.out.println("The 2 power 3 is "+ Math.pow(2,3));
System.out.println("The square root of 4 is "+ Math.sqrt(4));
System.out.println("The nearest integer of 1.256 is "+ Math.ceil(1.256));
System.out.println("The nearest integer of 1.256 is "+ Math.floor(1.256));
System.out.println("The nearest integer of 1.256 is "+ Math.rint(1.256));
System.out.println("The maximum in between two numbers 5 and 3 is "+
Math.max(5,3));
System.out.println("The minimum in between two numbers 5 and 3 is "+
Math.min(5,3));
System.out.println("The random numbers in between 1 and 9 are "+(int)
(Math.random() * 10));
}}
Write a java program to generate the Fibonacci numbers using recursion.
class FibonacciExample2{
static int n1=0,n2=1,n3=0;
static void printFibonacci(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
}
}
public static void main(String args[]){
int count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}
Operator Precedence
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
Implement the below scenario along with
its own features with inheritance & Show
that how to access animal class data
members and its own constructor through
9 L3
super keyword
Inheritance
Inheritance in java is a mechanism in
which one object acquires (inherits) all the properties and behaviors of parent object. The
idea behind inheritance in java is that you can create new classes that are built upon
existing classes.
Inheritance represents the IS-A relationship, also known as parent-child relationship
Multi-Level Inheritance
Implementation / Explanation
Object
Rectangle Clickable
Button
What is the purpose of inheritance in object-oriented programming?
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java?
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Multiple inheritance is not supported in java through class. (to prevent ambiguity )
To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
For example, where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So, whether you have same method or different, there will be compile
time error.
class A{
void msg(){ System.out.println("Hello");} }
class B{
void msg(){ System.out.println("Welcome"); } }
class C extends A,B { //suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg(); //Now which msg() method would be invoked? } }
Unit 2
Part A
Bloom’s
SI. No. Question
Taxonomy Level
Define package. Give an example. L1
A package is a grouping of related types providing access protection and
name space management.
Note that types refers to classes, interfaces, enumerations, and annotation
types. Enumerations and annotation types are special kinds of classes and
interfaces, respectively, so types are often referred to in this lesson simply
as classes and interfaces.
Example:
1
import package.name.Class; // Import a single class import java.util.Scanner;
import package.name.*; // Import the whole package import java.util.*;
MyPackageClass.java
package mypack;
class MyPackageClass
{ public static void main(String[] args)
{ System.out.println("This is my package!"); } }
Define interface. Give an example. L1
An interface is a class like construct that contains only constants and abstract
methods. In many ways, an interface is similar to an abstract class, but the
intent of an interface is to specify common behavior for objects.
For example, you can specify that the objects are comparable, edible,
2 cloneable using appropriate interfaces.
An interface in Java is a blueprint of a class. It has static constants and
abstract methods. To distinguish an interface from a class, Java uses the
following syntax to define an interface.
public interface InterfaceName {
constant declarations;
abstract method signatures; }
What is the use of CLASSPATH? L1
Classpath is a parameter in the Java Virtual Machine or the Java
3 compiler that specifies the location of user-defined classes and packages.
The parameter may be set either on the command-line, or through
an environment variable
What is the use of Stream class? L1
The Stream class defines objects which accepts a sequence of characters.
Streams may also have an output in which case multiple stream objects can
4 be cascaded to build a stream pipe where the output of a stream is directed
into the input of the next stream object "down the line". The InputStream is
used to read data from a source and the OutputStream is used for writing data
to a destination.
What are enumerations? Give an example. L1
An enum type is a special data type that enables for a variable to be a set of
predefined constants. The variable must be equal to one of the values that
have been predefined for it.
5 enum Color {
RED,
GREEN,
BLUE;
}
What do you mean by generics in java? .
Generics means parameterized types. The idea is to allow type (Integer, L1
String, … etc., and user-defined types) to be a parameter to methods, classes,
6
and interfaces. Using Generics, it is possible to create classes that work with
different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
What is the need of serialization and deserialization? L2
Serialization is a mechanism of converting the state of an object into a byte
stream, which then can be saved into a file on the local disk or sent over the
7
network to any other machine. Deserialization is the reverse process where
the byte stream is used to recreate the actual Java object in memory. This
mechanism is used to persist the object.
What is auto boxing? L1
8 Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper classes.
For example, converting an int to an Integer, a double to a Double, and so
on.
What is the use of wrapper class? L1
Wrapper classes are used to convert any data type into an object. The
9 primitive data types are not objects; they do not belong to any class; they
are defined in the language itself. Sometimes, it is required to convert data
types into objects in Java language.
How does java support multiple inheritance? Justify. L2
Does Java support multiple inheritance explain why or why not?
10 Java doesn't support multiple inheritances in classes because it can lead to
diamond problem (ambiguity). Java supports multiple inheritance through
implementing multiple interfaces
Part B
Bloom’s
SI.
Question Taxonomy
No.
Level
How is java supporting the multiple inheritance? Write a java program to achieve the
multiple inheritance.
Multiple inheritance is not supported in java through class. (to prevent ambiguity )
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Hence, the java is supporting multiple inheritance through interfaces.
interface Printable{
void print();
}
interface Showable{
void show();
1 } L3
// Multiple Interface
class Sendil implements Printable, Showable{
public void print(){
System.out.println("Hello"); }
public void show(){
System.out.println("Welcome");}
2. import java.io.FileNotFoundException; L3
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = “First Program for Files” + “File Handling in Java using "+ "
FileWriter and FileReader";
System.out.println("Writing successful");
// variable declaration
int ch;
// check if File exists or not
FileReader fr=null;
try
{ fr = new FileReader(“output.txt"); }
catch (FileNotFoundException fe)
{ System.out.println("File not found"); }
import java.io.*;
public class NewClass
{
public static void main(String[] args)
{
try
{
double d = 1.5;
4 L3
float f = 14.56f;
// Creating a new RandomAccessFile - "f1"
RandomAccessFile f1 = new RandomAccessFile("f1.txt", "rw");
// Writing to file
f1.writeUTF("Welcome For Random Access Fi1e");
// read() method :
System.out.println("Use of read() method : " + f1.read());
f1.seek(0);
byte[] b = {1, 2, 3};
// readBoolean() method :
System.out.println("Use of readBoolean() : " + f1.readBoolean());
// readByte() method :
System.out.println("Use of readByte() : " + f1.readByte());
f1.writeChar('c');
f1.seek(0);
// readChar() :
System.out.println("Use of readChar() : " + f1.readChar());
f1.seek(0);
f1.writeDouble(d);
f1.seek(0);
// read double
System.out.println("Use of readDouble() : " + f1.readDouble());
f1.seek(0);
f1.writeFloat(f);
f1.seek(0);
// readFloat() :
System.out.println("Use of readFloat() : " + f1.readFloat());
f1.seek(0);
// Create array upto f1.length
byte[] arr = new byte[(int) f1.length()];
// readFully() :
f1.readFully(arr);
String str1 = new String(arr);
System.out.println("Use of readFully() : " + str1);
f1.seek(0);
An interface is a class like construct that contains only constants and abstract methods.
In many ways, an interface is similar to an abstract class, but the intent of an interface
is to specify common behavior for objects.
For example, you can specify that the objects are comparable, edible, cloneable using
appropriate interfaces.
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
To distinguish an interface from a class, Java uses the following syntax to define an
interface
public interface InterfaceName {
constant declarations;
abstract method signatures; }
An interface is treated like a special class in Java. Each interface is compiled into a
separate bytecode file, just like a regular class.
Like an abstract class, you cannot create an instance from an interface using the new
operator, but in most cases, you can use an interface more or less the same way you use
5 L2
an abstract class.
For example, you can use an interface as a data type for a variable, as the result of
casting, and so on.
interface Outer
{
void dispOuter(); //this method for Outer interface
interface Inner
{
void dispInner(); //this method for Inner interface
}
}
class NestedInterfaceEx implements Outer.Inner,Outer
{
public void dispOuter()
{
System.out.println("We are in Outer interface.........!");
}
public void dispInner()
{
System.out.println("We are in Inner interface.");
}
package mypack;
import mypack.*;
class Test
{
public static void main(String as[])
{
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
Demonstrate about Reading console Input and Writing Console Output
Using BufferReader or Scanner or Console class, we can achieve the above
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
7 L2
{ Scanner in = new
Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " +
s); int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b); } }
OR
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import
java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new
BufferedReader(
new InputStreamReader(System.in));
An enum type is a special data type that enables for a variable to be a set of predefined
constants. The variable must be equal to one of the values that have been predefined for
it
All enums implicitly extend java.lang.Enum class. As a class can only
extend one parent in Java, so an enum cannot extend anything else.
toString() method is overridden in java.lang.Enum class, which returns enum constant
name.
enum can implement many interfaces.
class Main {
public static void main(String[] args) {
// create primitive types
int a = 5;
double b = 5.65;
//converts into wrapper objects
Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);
Autoboxing is the automatic conversion that the Java compiler makes between the
primitive types and their corresponding object wrapper classes. For example,
converting an int to an Integer, a double to a Double, and so on. If the conversion goes
the other way, this is called unboxing
Unboxing on the other hand refers to converting an object of a wrapper type to its
corresponding primitive value. For example conversion of Integer to int. The Java
compiler applies to unbox when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding
primitive type.
• Assigned to a variable of the corresponding primitive type
// Boxing
class BoxingExample1{
public static void main(String args[]){
10 int a=50; L2
//Unbxiing
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a); } }
//output : 50
Unit 3
Part A
Bloom’s
SI. No. Question
Taxonomy Level
Differentiate the error and exception.
Error Exception
1. An error is the mistake in a program 1. An exception is an event or
which detect by a compiler during condition that disrupts the normal flow
1 compilation. of a program's execution. L1
2. An errors are detected at compile- 2.An exceptions are detect at run-time
time by java-compiler. by java-interpreter
3. An errors are easy to detect & 3. An exceptions are difficult to detect
resolve. & handle.
List the types of exceptions. L1
IOException
FileNotFoundException
SQLException
2 ClassNotFoundException
NullPointerException
ArrayIndexOutOfBoundsException
IllegalArgumentException
ArithmeticException
What is the difference between throw and throws? L2
throw throws
1. The throw keyword is used 1. The throws keyword is used in
inside a function. It is used when it the function signature. It is used
is required to throw an Exception when the function has some
logically. statements that can lead to
3 exceptions.
2. The throw keyword is used to 2. The throws keyword can be
throw an exception explicitly. It used to declare multiple exceptions,
can throw only one exception at a separated by a comma.
time.
3. It is used with user-defined- 3. It is used with predefined-
exception. defined-exception.
What is the use of finally block in java? L2
The finally block in java is used in exception handling to specify a block of
4 code that will be execute whether an exception occurs or not. The finally
block is optional and follows the try and catch blocks in a try-catch-finally
statement. The ”finally” keyword is used to define finally block
What is multitasking? Give an example. L1
Multitasking refers to the capability of an operating system or computer
system to execute multiple tasks or processes concurrently or
simultaneously. It allows multiple tasks to be executed simultaneously, even
5 though the processor switches between tasks rapidly.
Multitasking can be achieved through various mechanisms, such as time-
sharing, multiprocessing, or parallel processing.
Example: The user is simultaneously running a web browser, a media player,
and a word processor
What is process? What is thread? Give an example. L1
Process: A process can be defined as an instance of a running program. It
represents an independent unit of execution that has its own memory space,
resources, and program counter. Simply the process is program under
execution, during execution program is dividing into processes. Example: A
text editor application
6
Thread:
A thread, also known as a lightweight process, is a subset of a process. It is a
unit of execution within a process, sharing the same memory space and
resources of the process it belongs to. Multiple threads within a process can
execute concurrently, allowing for parallel or concurrent processing.
Example: In multithreading program multiple threads can run simultaneously
List any four unchecked exceptions. L1
NullPointerException
7 ArrayIndexOutOfBoundsException
IllegalArgumentException:
ArithmeticException
How to assign priorities to threads? L1
In Java, we can assign priorities to threads using the ‘setPriority()’ method
of the Thread class. The ‘setPriority()’ method allows us to specify the
8 priority of a thread as an integer value between 1 and 10, where 1 represents
the lowest priority, and 10 represents the highest priority.
For example,
t1.setPriority(Thread.MAX_PRIORITY); or t1.setPriority(10);
What is thread synchronization? L1
Thread synchronization is a technique used in multithreaded programming to
ensure that multiple threads can safely access shared resources or execute
9 critical sections of code without interfering with each other. It helps prevent
race conditions and data inconsistencies that can occur when multiple threads
access shared data concurrently. In java ‘synchronized’ keyword is used to
implements synchronization.
How to handle exceptions?
Handling exceptions in Java involves using try-catch blocks to catch and
handle specific types of exceptions that may occur during the execution of a
program.
try
{
10
// Code that may throw an exception
}
catch(ExceptionType1 e)
{
// Exception handling code for ExceptionType1
}
Part B
Bloom’s
SI.
Question Taxonomy
No.
Level
How can you handle the run time exceptions? Write a simple java program to handle run time
exceptions.
In Java, Exception is an abnormal condition or an event which disrupts the normal flow of the
program. It is an object which is thrown at runtime.
An exception Handling is a mechanism to handle runtime errors or exceptions such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-
bounds array, and numeric errors.
These are the exceptions that are not checked at compile time. In Java exceptions
under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked. ArithmeticException is an unchecked exception, ex: divide a number by
0.
In java exception can handle using try, catch & finally block.
try block:
Place the code that may potentially throw an exception within a try block. The try block defines
the scope in which exceptions will be caught and handled.
catch block: Immediately following the try block, includes one or more catch blocks to catch
1 specific types of exceptions that may be thrown within the try block. Each catch block specifies L2
the type of exception it can handle.
finally block:
The finally block in Java is used in exception handling to specify a block of code that will be
executed whether an exception occurs or not. The finally block is optional and follows the try
and catch blocks in a try-catch-finally statement
Example:
//Program for Handling an Exception.
public class ExceptionHandlingEx
{ public static void main(String[] args)
{ try {
int a=10,b=0,c;
c=a/0; //may possibility of an exception }
catch(ArithmeticException e) //run-time exception)
{ System.out.println(e); }
finally {
System.out.println("This code will always execute"); } } }
2. Exception: An exception is refers to an abnormal or unexpected event that occurs during the L2
execution of a program, resulting in the interruption of the normal flow of the program. When
an exception occurs, the program's normal execution is halted, and the control is transferred to a
specific exception-handling code block.
Exceptions are typically caused by errors or exceptional conditions that arise during program
execution, such as division by zero, accessing invalid memory locations, or attempting to
perform an operation on incompatible data types.
Types of Exceptions:
A. Built-in-Exceptions or Predefined-Exceptions
Checked Exception
Unchecked Exception
B. User-Defined-Exceptions
A) Built-in-Exceptions (or Predefined-Exceptions)
Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
Checked-Exceptions (or Compile-time-exceptions)
Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
Checked-Exceptions are:
1. FileNotFoundException: This exception is a subclass of IOException and is thrown
when an attempt to access a file fails because the file does not exist or cannot be found.
2. IOException: This is a general exception that is thrown when an input/output operation
fails or is interrupted.
3. SQLException: This exception is specific to database operations and occurs when there
is an error in executing database queries or interacting with the database.
4. ClassNotFoundException: This exception is thrown when an application tries to load a
class through its string name but the class with the specified name cannot be found.
5. InterruptedException: This exception is thrown when a thread is waiting, sleeping, or
occupied in a blocking operation, and it is interrupted by another thread.
6. InstantiationException: This is a checked exception in Java that is thrown when an
attempt to create an instance of a class using the new operator.Etc.
Unchecked exceptions, also known as runtime exceptions, are exceptions that do not require
explicit handling or declaration in the code. These exceptions occur during the runtime of a
program.
Unchecked-Exceptions are:
1. NullPointerException: This exception occurs when a program attempts to access or
perform operations on a null object reference.
2. ArithmeticException: This exception is thrown when an arithmetic operation
encounters an exceptional condition, such as division by zero.
3. ArrayIndexOutOfBoundsException: This exception occurs when an invalid index is
used to access an array, i.e., an index that is outside the valid range of array elements.
4. IllegalArgumentException: This exception is thrown when a method receives an
invalid argument or parameter.
5. IllegalStateException: This exception is thrown when the state of an object is
inappropriate or inconsistent for the requested operation.
6. NumberFormatException: This exception is thrown when an invalid conversion is
attempted between numeric types, such as parsing a string that does not represent a
valid number. Etc.
B) User-Defined Exceptions
User-defined exceptions, also known as custom exceptions, which are defined by the user to
handle specific run-time-error conditions in a program. In many programming languages,
including Python, Java, and C++, you can create your own exceptions by deriving class from an
Exception class (or Base class).
Write a java program to create multiple threads, apply priority among them and show how it
3 L3
will run?
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Setting priorities of above threads by
// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th3 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Draw and discuss the thread life cycle.
Write a program to illustrate the use of multiple catch blocks for a try block.
//Write a program to illustrate the use of multiple catch blocks for a try block.
package exception;
public class MultiCatchTryEx
{
public static void main(String[] args)
{
int numbers[]={1,2,3,4,5};
int index=4;
try {
int result=numbers[index]/0; // Division by zero
6 System.out.println("Result:"+result); } L2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds:"+e.getMessage());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception:"+e.getMessage());
}
catch(Exception e)
{
System.out.println("General exception:"+e.getMessage());
}} }
Write a program to illustrate user defined exception that checks the internal and external marks
if the internal marks are greater than 30 it raises the exception “internal marks are exceed”, if
the external marks are greater than 70 exception is raised and display the message the “external
marks are exceed.”
import java.util.Scanner;
class MarksException extends Exception
{public MarksException(String msg)
{ super(msg);
}}
class MarksChecker
{
public static void checkMarks(int internalMarks, int externalMarks) throws MarksException {
if(internalMarks>30)
{
throw new MarksException("An Exception is occured Internal marks exceeded!..&
marks:"+internalMarks);
}
if(externalMarks>70)
{
throw new MarksException("An Exception is occured External marks exceeded!..&
marks:"+externalMarks);
}}}
public class MarksCheckerEx
{
publict static void main(String args[])
7 { L3
try
{
Scanner in=new Scanner(System.in);
int internalMarks,externalMarks;
System.out.println("Please enter less than 30 internal marks:");
internalMarks=in.nextInt();
System.out.println("Please enter less than 70 internal marks:");
externalMarks=in.nextInt();
MarksChecker.checkMarks(internalMarks, externalMarks);
}
catch(MarksException e) {
System.out.println(e.getMessage());
} catch(NumberFormatException e) {
System.out.println("Invalid input! Please enter valid marks....!"); } } }
Output
Write a Java program that exactly implements the producer – consumer problem using the
concept of interthread communication
package javath;
import java.util.LinkedList;
class PC
{
LinkedList<Integer> queue =new LinkedList<>();
int capacity=2;
public void produce() throws Exception
{
int add_data_ele=0;
while(true)
{
synchronized(this)
{
while(queue.size() == capacity)
wait();
System.out.println("Producer produced-"+add_data_ele);
queue.add(add_data_ele++);
notify();
Thread.sleep(1000);
}
}
}
8 L3
public void consume() throws InterruptedException
{
while(true)
{
synchronized(this)
{
while (queue.size()== 0)
wait();
int removed_data_ele = queue.removeFirst();
System.out.println("Consumer consumed-"+removed_data_ele);
notify();
Thread.sleep(1000);
}
}
}
}
public class ProducerConsumerEx
{
public static void main(String[] args)
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{ try
{
pc.produce();}
catch(Exception e) {}
}
});
OUTPUT:
Write a Java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
9 value of cube of the number. L3
What is meant by re-throwing exception? Demonstrate with a suitable scenario for this.
When an exception is cached in a catch block, you can re-throw it using the throw keyword
(which is used to throw the exception objects).
While re-throwing exceptions you can throw the same exception as it is without adjusting it as.
Wrap it within a new exception and throw it. When you wrap a cached exception within
another exception and throw it, it is known as exception chaining or, exception wrapping, by
doing this you can adjust your exception, throwing a higher level of exception maintaining the
abstraction.
Step-by-step process of re-throwing an exception:
Step-1: An exception is thrown by a method or encountered during the execution of a block of
code.
Step-2: The exception is caught using a try-catch block.
Step-3: Inside the catch block, you have the option to perform some error handling operations,
such as logging, cleanup, or recovery.
Step-4: After handling the exception, you may decide to rethrow it by using the throw
statement.
Step-5: The rethrown exception is then propagated up the call stack to be caught by an
exception handler at a higher level.
Scenarios re-throwing an exception:
Adding context: You can catch an exception, enrich its error message with additional
10 information, and then rethrow it. This provides more meaningful and detailed information about L2
the exception to aid in debugging and troubleshooting.
Exception translation: In some cases, you may encounter a lower-level exception that is specific
to a particular library or framework. You can catch that exception, wrap it in a higher-level
exception that is more appropriate for your application, and then rethrow it. This helps to
decouple your code from specific implementation details and provides a more generalized and
consistent exception handling mechanism.
Centralized exception handling: By rethrowing an exception, you can consolidate exception
handling in a centralized location, such as a top-level exception handler or a global exception
handler. This promotes code modularity, improves maintainability, and avoids scattering
exception handling logic throughout your codebase.
Iterator ListIterator
The Iterator interface is designed to iterate The ListIterator interface extends
Ans 3 over collections that implement the the Iterator interface and is
Collection interface, such as ArrayList, specifically designed for traversing
HashSet, or LinkedList. collections that implement the List
interface, such as ArrayList or
LinkedList. Therefore, ListIterator
is only applicable to list-like
structures.
The Iterator interface allows for forward- The ListIterator interface allows
only traversal of a collection. It provides bidirectional traversal. It adds
methods like next() to retrieve the next additional methods like previous()
element in the collection and hasNext() to to retrieve the previous element
check if there are more elements. and hasPrevious() to check if there
are elements preceding the current
position.
Q4 What are the possible ways to traverse through elements of any Collection? L1
Ans 4 In Java, there are several ways to traverse through the elements of a collection,
regardless of the specific implementation of the Collection interface. Here are some
common approaches:
Iterator: The Iterator interface provides a standard way to iterate over elements in
a collection. You can obtain an iterator using the iterator() method of the Collection
interface. The Iterator allows you to sequentially access elements using methods
like next() and hasNext(). It is the most general and widely used way to traverse
collections.
Enhanced for-each loop: If you are using Java 5 or later, you can use the
enhanced for-each loop, also known as the for-each loop, to iterate over a
collection. It simplifies the syntax by automatically handling the iteration and
removing the need for an explicit iterator.
Q5 Write the two constructors of Date Class. L1
Ans 5 The Date class encapsulates the current date and time. Date supports the following
non-deprecated constructors:
1. Date( )
The first constructor initializes the object with the current date and time.
2. Date(long millisec)
The second constructor accepts one argument that equals the number of
milliseconds that have elapsed since midnight, January 1, 1970.
Q6 What is Comparator? Write the syntax of it. L1
Ans 6 In Java, a Comparator is an interface that allows you to define custom comparison
logic for objects. It provides a way to compare two objects of a specific type based
on a specified criteria. The Comparator interface is part of the java.util package and
is typically used to sort collections of objects or to control the order of elements in
data structures like trees or priority queues.
The Comparator interface has the following syntax:
interface Comparator<T>
Here, T specifies the type of objects being compared.
Q7 What is the difference between HashMap and Hashtable? L1
Ans 7 HashMap Hashtable
HashMap is not synchronized by default. Hashtable is synchronized, which means
It does not provide inherent thread-safety, it is designed to be thread-safe.
but you can make it thread-safe by using
external synchronization mechanisms
HashMap allows null values and a single Hashtable does not allow null keys or
null key values.
HashMap provides better performance Hashtable performance is not as good as
than Hashtable. Because Hashtable is HashMap as it is synchronized
synchronized, the overhead of
synchronization may impact
performance, especially in highly
concurrent scenarios.
Q8 Write the steps to use Scanner class. L1
Ans 8 In general, to use Scanner, follow this procedure:
1. Determine if a specific type of input is available by calling one of Scanner’s
hasNextX methods, where X is the type of data desired.
2. If input is available, read it by calling one of Scanner’s nextX methods.
3. Repeat the process until input is exhausted.
4. Close the Scanner by calling close( ).
Discuss the Vector class and its constructor. Write a simple java
Q4 L2
program for the same.
Ans 4 Vector implements a dynamic array. It is similar to ArrayList, but with two
differences: Vector is synchronized, and it contains many legacy methods
that duplicate the functionality of methods defined by the Collections
Framework.
Vector is declared like this:
class Vector<E>
Here, E specifies the type of element that will be stored.
The Vector constructors are:
1. Vector( )
2. Vector(int size)
3. Vector(int size, int incr)
4. Vector(Collection<? extends E> c)
The first form creates a default vector, which has an initial size of 10.
The second form creates a vector whose initial capacity is specified by size.
The third form creates a vector whose initial capacity is specified by size and
whose increment is specified by incr. The increment specifies the number of
elements to allocate each time that a vector is resized upward.
The fourth form creates a vector that contains the elements of collection c.
import java.util.*;
class VectorDemo {
public static void main(String[] args) {
Vector<Integer> v = new Vector<Integer>(3, 2); // initial size is 3, increment
is 2
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after four additions: " +v.capacity());
v.addElement(5);
System.out.println("Current capacity: " +v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Current capacity: "
+v.capacity()); v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: "
+v.capacity()); v.addElement(11);
v. addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
Enumeration<Integer> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
• The output from this program is shown
here: Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12
What is StringTokenizer? Discuss the StringTokenizer class and its
Q5 L2
constructors in java. Write a simple java program for the same.
Ans 5 The StringTokenizer class provides the first step in the parsing process, often
called the lexer (lexical analyzer) or scanner. StringTokenizer implements
the Enumeration interface. Therefore, given an input string, you can
enumerate the individual tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that
contains delimiters. Delimiters are characters that separate tokens. Each
character in the delimiters string is considered a valid delimiter—for
example, ",;:" sets the delimiters to a comma, semicolon, and colon.
The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
In all versions, str is the string that will be tokenized.
In the first version, the default delimiters are used.
In the second and third versions, delimiters is a string that specifies the
delimiters.
In the third version, if delimAsToken is true, then the delimiters are also
returned as tokens when the string is parsed. Otherwise, the delimiters are
not returned. Delimiters are not returned as tokens by the first two forms.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=McGraw Hill;" +
"copyright=2022";
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is shown
here: title Java: The Complete Reference
author Schildt
publisher McGraw Hill
copyright 2022
What is the use of Scanner class in java? Write a simple java program
Q6 to get the input for different data types like integer, float, double and L2
string from the user.
Ans 6 Scanner is the complement of Formatter. It reads formatted input and
converts it into its binary form.
Scanner can be used to read input from the console, a file, a string, or any
source that implements the Readable interface or ReadableByteChannel.
In general, to use Scanner, follow this procedure:
1. Determine if a specific type of input is available by calling one of
Scanner’s hasNextX methods, where X is the type of data desired.
2. If input is available, read it by calling one of Scanner’s nextX
methods.
3. Repeat the process until input is exhausted.
4. Close the Scanner by calling close( ).
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read an integer
System.out.print("Enter an integer: ");
int intValue = scanner.nextInt();
System.out.println("Integer value: " + intValue);
// Read a float
System.out.print("Enter a float: ");
float floatValue = scanner.nextFloat();
System.out.println("Float value: " + floatValue);
// Read a double
System.out.print("Enter a double:
");
double doubleValue = scanner.nextDouble();
System.out.println("Double value: " + doubleValue);
// Read a string
scanner.nextLine(); // Consume the remaining newline character
System.out.print("Enter a string: ");
String stringValue = scanner.nextLine();
System.out.println("String value: " + stringValue);
scanner.close(); } }
In the above program, a Scanner object named scanner is created to read
input from the console (System.in).
The program prompts the user to enter different values: an integer, a float, a
double, and a string. The nextInt(), nextFloat(), nextDouble(), and nextLine()
methods of the Scanner class are used to read the corresponding data types
from the user.
Note that after using nextXXX() methods to read numeric values, you may
need to use nextLine() to consume the remaining newline character before
reading a string. This is because the nextXXX() methods do not consume the
newline character, and it will be read by the subsequent nextLine() call
without waiting for user input.
Finally, the program displays the values entered by the user.
Output of the program
Enter an integer: 123
Integer value: 123
Enter a float: 3.14
Float value: 3.14
Enter a double: 2.71828
Double value: 2.71828
Enter a string: Hello, world!
String value: Hello, world!
Input Data: 25,3,43,9,6,4, 52
Q7 Write a java program to sort and search the elements using Collection L3
algorithms.
Ans 7 import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionAlgorithmsExample {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = new
ArrayList<>(); numbers.add(25);
numbers.add(3);
numbers.add(43);
numbers.add(9);
numbers.add(6);
numbers.add(4);
numbers.add(52);
// Sorting the list
Collections.sort(numbers);
// Displaying the sorted list
System.out.println("Sorted List: " + numbers);
// Searching for an element
int searchElement = 9;
int index = Collections.binarySearch(numbers, searchElement);
if (index >= 0) {
System.out.println("Element " + searchElement + " found at index "
+ index);
} else {
System.out.println("Element " + searchElement + " not found");
}
}
}
In the above program, we create a list called numbers and add the given
elements: 25, 3, 43, 9, 6, 4, 52.
The program then uses the Collections.sort() method to sort the list in
ascending order.
After sorting, the sorted list is displayed using System.out.println().
Next, we search for the element 9 using the Collections.binarySearch()
method. It returns the index of the element if found, or a negative value if not
found.
Finally, based on the search result, the program displays whether the element
was found or not.
Output of the program
Sorted List: [3, 4, 6, 9, 25, 43, 52]
Element 9 found at index 3
Q8 How to access the Java Collection using Iterators? Discuss
Ans 8 To cycle through the elements in a collection one way is to employ an
iterator, which is an object that implements either the Iterator or the
ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing
elements.
ListIterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements.
Iterator and ListIterator are generic interfaces which are declared as shown
here:
interface Iterator<E>
interface ListIterator<E>
Here, E specifies the type of objects being iterated.
To access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to
the start of the collection. By using this iterator object, you can access each
element in the collection, one element at a time. In general, to use an iterator
to cycle through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s
iterator( ) method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long
as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling
listIterator( ).
A list iterator gives you the ability to access the collection in either the
forward or backward direction and lets you modify an element. Otherwise,
ListIterator is used just like Iterator.
import java.util.*;
class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>(); // Create an array list.
al.add("C"); // Add elements to the array list.
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: "); // Use iterator to display
contents of al.
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
ListIterator<String> litr = al.listIterator(); // Modify objects being iterated.
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al:
"); itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
System.out.print("Modified list backwards: "); // Now, display the list
backwards.
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output of the program
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Explain the following Collection classes using simple java program
Q9 L3
a. ArrayList b.PriorityQueue c. HashSet d. LinkedList e. TreeSet
Ans 9 a. ArrayList:The ArrayList class in Java is an implementation of the List
interface that uses an array to store elements. It provides dynamic resizing,
allowing the list to grow or shrink as elements are added or removed.
Elements can be accessed using their indices.
import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList
List<String> list = new ArrayList<>();
// Add elements to the list
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Accessing elements by index
System.out.println("Element at index 1: " + list.get(1));
// Iterating through the list
System.out.println("Elements in the list:");
for (String element : list) {
System.out.println(element);
}
// Removing an element
list.remove("Banana");
System.out.println("Elements in the list after removal:");
for (String element : list) {
System.out.println(element);
}
}
}
b. PriorityQueue:The PriorityQueue class in Java is an implementation of the
Queue interface that provides a priority-based ordering of elements.
Elements are added based on their priority, and the element with the highest
priority is retrieved first.
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueueExample {
public static void main(String[] args)
{
// Create a PriorityQueue
Queue<String> queue = new PriorityQueue<>();
// Add elements to the queue
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Orange");
// Accessing the element with the highest priority
String highestPriorityElement = queue.peek();
System.out.println("Element with highest priority: " +
highestPriorityElement);
// Removing elements in priority order
System.out.println("Elements in priority order:");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
c. HashSet:The HashSet class in Java is an implementation of the Set
interface that uses a hash table to store elements. It does not maintain the
insertion order or allow duplicate elements. It provides constant-time
performance for basic operations like adding, removing, and searching for
elements.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet
Set<String> set = new HashSet<>();
// Add elements to the set
set.add("Apple");
set.add("Banana");
set.add("Orange");
// Displaying elements in the set
System.out.println("Elements in the set:");
for (String element : set) {
System.out.println(element);
}
// Removing an element
set.remove("Banana");
System.out.println("Elements in the set after removal:");
for (String element : set) {
System.out.println(element);
}
}
}
d. LinkedList: The LinkedList class in Java is an implementation of the List
interface that uses a doubly-linked list to store elements. It provides efficient
insertion and deletion operations, but slower random access compared to
ArrayList. It supports operations like adding, removing, and accessing
elements by their indices.
import java.util.LinkedList;
import java.util.List;
public class LinkedListExample {
public static void main(String[] args) {
// Create a LinkedList
List<String> list = new LinkedList<>();
// Add elements to the list
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Accessing elements by index
System.out.println("Element at index 1: " + list.get(1));
// Iterating through the list
System.out.println("Elements in the list:");
for (String element : list) {
System.out.println(element);
}
// Removing an element
list.remove("Banana");
System.out.println("Elements in the list after removal:");
for (String element : list) {
System.out.println(element);
}
}
}
e. TreeSet: The TreeSet class in Java is an implementation of the SortedSet
interface that uses a tree structure (Red-Black tree) to store elements. It
maintains elements in sorted order based on their natural ordering or a
custom comparator. It provides efficient operations for adding, removing,
and searching elements.
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet
Set<String> set = new TreeSet<>();
// Add elements to the set
set.add("Apple");
set.add("Banana");
set.add("Orange");
// Displaying elements in sorted order
System.out.println("Elements in sorted order:");
for (String element : set) {
System.out.println(element);
}
// Removing an element
set.remove("Banana");
System.out.println("Elements in sorted order after
removal:"); for (String element : set) {
System.out.println(element);
}
}
}
Explain date and Calendar classes. Write a program to print current
Q10 L2
time and date.
Ans 10 The Date class encapsulates the current date and time. Date supports the
following non-deprecated constructors:
1. Date( )
The first constructor initializes the object with the current date and time.
2. Date(long millisec)
The second constructor accepts one argument that equals the number of
milliseconds that have elapsed since midnight, January 1, 1970.
The abstract Calendar class provides a set of methods that allows you to
convert a time in milliseconds to a number of useful components. Some
examples of the type of information that can be provided are year, month,
day, hour, minute, and second.
It is intended that subclasses of Calendar will provide the specific
functionality to interpret time information according to their own rules.
Calendar provides no public constructors. Calendar defines several protected
instance variables.
import java.util.Calendar;
class CalendarDemo {
public static void main(String[] args) {
String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug","Sep", "Oct", "Nov", "Dec"};
// Create a calendar initialized with the current date and time in the default
locale and timezone.
Calendar calendar = Calendar.getInstance();
System.out.print("Date: "); // Display current time and date information.
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
calendar.set(Calendar.HOUR, 10); // Set the time and date information and
display it.
calendar.set(Calendar.MINUTE, 29);
calendar.set(Calendar.SECOND, 22);
System.out.print("Updated time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
}
}
Sample Output of the program is:
Date: Jan 1 2022
Time: 11:29:39
Updated time: 10:29:22
Unit 5
Part A
Bloom’s
SI. No. Question
Taxonomy Level
What are the limitations of AWT?
Limitations of AWT
• The buttons of AWT does not support pictures.
1 L1
• It is heavyweight in nature.
• Two very important components trees and tables are not present.
• Extensibility is not possible as it is platform dependent
What is the difference between Grid Layout and Grid Bag Layout?
GridLayou GridBagLayout
A GridLayout arranges the GridBagLayout places component in
components in a rectangular each individual cell in a grid
grid. Allows the component to span
It arranges component in the to multiple columns or rows.
cells and each cell has the same Each GridBagLayout object maintains
2 L1
size. a dynamic, rectangular grid of
Components are placed cells with each component occupying
in columns and rows. one or more
GridLayout(int rows, int cellscalled Component display area
columns) takes two parameters In order to use GridBagLayout, we
that are a column and a row need to create
a GridBagConstraints object and fill
appropriate properties
What is the use of Adapter class?
Java adapter classes provide the default implementation of listener interfaces
3 L1
. If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So, it saves code.
What is an event and event sources?
An event is one of the most important concepts in Java. The change in the
state of an object or behavior by performing actions is referred to as an Event
in Java. Actions include button click, keypress, page scrolling, or cursor
movement.
Event Source :
Button : Generates action events when the button is pressed.
4 L2
Check box : Generates item events when the check box is selected or
deselected.
Choice : Generates item events when the choice is changed.
List : Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
Menu item : Generates action events when a menu item is selected; generates
item events when a checkable menu item is selected or deselected
5 Draw the AWT hierarchy. L1
What is the use of JLabel in java?
The class JLabel can display either text, an image, or both. Label's contents
are aligned by setting the vertical and horizontal alignment in its display
6 L1
area. By default, labels are vertically centered in their display area. Text-only
labels are leading edge aligned, by default; image-only labels are
horizontally centered, by default.
What is the use of Anonymous inner classes?
Java anonymous inner class is an inner class without a name and for which
only a single object is created. An anonymous inner class can be useful when
making an instance of an object with certain "extras" such as overloading
7 L1
methods of a class or interface, without having to actually subclass a class.
In simple words, a class that has no name is known as an anonymous inner
class in Java. It should be used if you have to override a method of class or
interface
What are the four types of containers?
1. Panel: JPanel is the simplest container. It provides space in which any
other component can be placed, including other panels.
2. Frame: A JFrame is a top-level window with a title and a border.
3. Window: A JWindow object is a top-level window with no borders and no
8 L1
menubar.
4. Dialog: The Dialog control represents a top level window with a border
and a title used to take some form of input from the user. It inherits the
Window class. Unlike Frame, it doesn't have maximize and minimize
buttons.
What are the components of the Event delegation model?
The Delegation Event model is defined to handle events in GUI
environment. The GUI programming is inherently event-driven; whenever a
9 user initiates an activity such as a mouse activity, clicks, scrolling, etc., each L1
is known as an event that is mapped to a code to respond to functionality to
the user. This is known as event handling.
Basically, an Event Model is based on the following three components:
Events
Events Sources
Events Listeners
What is the use of Listeners?
Event listeners represent the interfaces responsible to handle events. Java
provides various Event listener classes, however. Every method of an event
10 L1
listener method has a single argument as an object which is the subclass of
EventObject class. For example, mouse event listener methods will accept
instance of MouseEvent, where MouseEvent derives from EventObject.
Part B
Bloom’s
SI.
Question Taxonomy
No.
Level
What is the use of Swing in java? What are the differences between AWT and
Swing? Write a java program to create a frame window that responds to button
event.
Swing in java is part of Java foundation class which is lightweight and platform
independent. It is used for creating window-based applications. It includes
components like button, scroll bar, text field etc. Putting together all these
components makes a graphical user interface
AWT provides
Swing provides more powerful
7. comparatively less
components.
powerful components.
import java.awt.*;
import java.awt.event.*;
public class ButtonExample3 {
public static void main(String[] args) {
Frame f = new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
} });
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }
a. Discuss the limitations of AWT.
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view
Explain the various components of Swing.
Swing components are basic building blocks of an application. Swing has a wide
range of various components, including buttons, check boxes, sliders, and list boxes.
JButton, JLabel, JTextField, JPasswordField. JCheckBox, JRadioButton,
JComboBox, JTextArea, JTable, JList etc.
Class Description
4 L2
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time of
your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart an
applet after it has been stopped. Note that init( ) is called once i.e. when the first time
an applet is loaded whereas start( ) is called each time an applet’s HTML document
is displayed onscreen. So, if a user leaves a web page and comes back, the applet
resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output
must be redrawn. This situation can occur for several reasons. For example, the
window in which the applet is running may be overwritten by another window and
then uncovered. Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example. When
stop( ) is called, the applet is probably running. You should use stop( ) to suspend
threads that don’t need to run when the applet is not visible. You can restart them
when start( ) is called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that
your applet needs to be removed completely from memory. At this point, you should
free up any resources the applet may be using. The stop( ) method is always called
before destroy( ).
Adapter class provides the default implementation of all the methods in an event
listener interface. ... - These classes are useful when you want to process only few of
the events that are handled by a particular event listener interface. - Using adapters, it
helps to reduce the clutter in your code.
Program to use the Window Adapter Class and how we reduce the coding:
// importing the necessary libraries
import java.awt.*;
5 L2
import java.awt.event.*;
// main method
public static void main(String[] args)
{ new AdapterExample();
} }
What are the different types of Even Listeners supported by java?
Description of the
Listener Interface Methods Declared
Interface
windowActivated()
windowDeactivated()
windowOpened() An event which indicates
WindowListener windowClosed() whether a window has
windowClosing() changed its status or not
windowIconified()
windowDeiconified()
Design a program which will print “key pressed” on the status window when you
press the key,”key released “ on status window when you release the key and when
you type a character it should print “Hello”. At co-ordinates(50,50) on frame.
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener {
Label l;
TextArea area;
KeyListenerExample() {
7 l = new Label(); L2
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text
of the label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method to set the text of the label when key is
released
public void keyReleased (KeyEvent e)
{ l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set
the text of the label when a key is typed
public void keyTyped (KeyEvent e)
{ l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample(); } }
In Java, inner class refers to the class that is declared inside class or interface
which were mainly introduced, to sum up, same logically relatable classes as Java
is purely object-oriented so bringing it closer to the real world.
There are certain advantages associated with inner classes are as follows:
8 L2
Making code clean and readable.
Private methods of the outer class can be accessed, so bringing a new
dimension and making it closer to the real world.
Optimizing the code module.
Syntax:
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}}
class OuterClass {
int num;
// inner class
private class InnerClass {
public void print() {
System.out.println("This is an inner class"); } }
// Accessing he inner class from the method within
void display_Inner() {
InnerClass inner = new InnerClass();
Inner.print(); } }
public class MyClass {
public static void main(String args[]) {
// Instantiating the outer class
OuterClass outer = new OuterClass();
// Accessing the display_Inner() method.
outer.display_Inner(); } }
Write a java program that implements Anonymous Inner Class using Class and
Interface
Using Interface
public interface SampInter {
// defining variable and methods
int x = 21;
void getAge();
}
public class SampCla1 implements SampInter {
// overriding getAge() method
public void getAge()
{ // Print statement
System.out.print("Age is " + x);
}}
// anonymous class
public class SampInner {
// main driver
public static void main(String[] args) {
// SampCla1 is implementation class of Age Interface
SampCla1 sin = new SampCla1();
9 L2
//calling getAge() implemented at SampCla1
sin.getAge(); }}
Using Class
class Polygon {
public void display() {
System.out.println("Inside the Polygon class"); } }
class AnonymousDemo {
public void createClass() {
// creation of anonymous class extending class Polygon
Polygon p1 = new Polygon() {
public void display() {
System.out.println("Inside an anonymous class.");
} }; // anonymous class defined inside an expression so “;” must
p1.display(); } }
class Main {
public static void main(String[] args) {
AnonymousDemo an = new AnonymousDemo();
an.createClass();
}}
Write a java program to implement the Border and Flow layouts
// Flow layouts
import java.awt.*;
10 L2
import java.awt.event.*;
import javax.swing.*;
public class SampFl extends JFrame{
// Declaration of objects of JLabel class.
JLabel l1, l2, l3, l4, l5;
public SampFl()
{ FlowLayout layout = new FlowLayout();
// this Keyword refers to current object.// Function to set Layout of JFrame.
this.setLayout(layout);
// Initialization of object "l1" of JLabel class.
l1 = new JLabel("Label 1 ");
// Initialization of object "l2" of JLabel class.
l2 = new JLabel("Label 2 ");
// Initialization of object "l3" of JLabel class.
l3 = new JLabel("Label 3 ");
// Initialization of object "l4" of JLabel class.
l4 = new JLabel("Label 4 ");
// Initialization of object "l5" of JLabel class.
l5 = new JLabel("Label 5 ");
// this Keyword refers to current object.// Adding Jlabel "l1" on JFrame.
this.add(l1);
// Adding Jlabel "l2" on JFrame.
this.add(l2);
// Adding Jlabel "l3" on JFrame.
this.add(l3);
// Adding Jlabel "l4" on JFrame.
this.add(l4);
// Adding Jlabel "l5" on JFrame.
this.add(l5); } }