Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

2-2 OOP Java QB-Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

2-2 OOP Java QB-Answers

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

GURU NANAK INSTITUE OF TECHNOLOGY

(A UGC Autonomous Institution – Affiliated to JNTUH)


Ibrahimpatnam, Ranga Reddy (District) - 501 506.

Branch: CSE, IT, CSC, CSM & AIDS Year / Sem:


II/ II
Sub: Object Oriented Programming using Java, Java Programming
Subcode: 20PY0CY10/ 20PC0AI11/20PC0AD12 / 20PC0CS10 / 20PC0IT09
QUESTION BANK
BTL L-1: Remembering L-2: Understanding L-3:Applying L-4: Analysing L-5: Evaluating L-6: Creating

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

Define data encapsulation. L1


2 Data Encapsulation in Java is a process of wrapping code and data together
into a single unit, for example, a capsule which is mixed of several medicines
List the components of JVM? L1
The Java Virtual Machine. JVM is the engine that converts Java bytecode
3 into machine language. JVM architecture in Java contains classloader,
method area, heap, JVM language stacks, PC registers, native method stacks,
execution engine, native methods interface, native methods libraries
What do you mean by data abstraction? L1
Data abstraction is the process of hiding certain details and showing only
4
essential information to the user. Abstraction can be achieved with
either abstract classes or interfaces.
What are the access specifiers (or modifiers) in object-oriented L1
programming?
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class
5
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
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.
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.
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
Why java is platform independent? Justify. L1
Java is called Platform Independent because programs written in Java can be
run on multiple platforms without re-writing them individually for a
6
particular platform, i.e., Write Once Run Anywhere. Java program will be
converted into bytecode’ that bytecode is executed in any machine using the
corresponding JVM
What is the use of typecasting? Give an example L2
Type casting is a way of converting data from one data type to another data
type. This process of data conversion is also known as type conversion or
type coercion. In Java, we can cast both reference and primitive data types.
By using casting, data cannot be changed but only the data type is changed
7 Implicit casting
double d = 3; (type widening)

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?

Procedure Oriented Programming Object Oriented Programming


Step by step approach, breaks down the Uses objects and classes for creating
task into a collection of routines (or models based on the real-world
subroutines) and variables by following environment. This model makes it very
sequence of instructions. easy for a user to modify as well as
maintain the existing code.
No concept of data hiding, hence less Hiding of data is possible using
secure abstraction, hence more secure
Procedural Programming divides the Object Oriented Programming divides the
program into small programs and refers to program into small parts and refers to them
them as functions as objects
The Procedural Programming follows a The Object-Oriented Programming follows
Top-Down approach a Bottom-Up approach
No code reusability Code reusability using feature of
inheritance
This programming model does not give This programming model gives importance
importance to data. It prioritizes the to the data rather than functions or
1 functions along with the sequence of procedures. It is because it works based on L2
actions that needs to follow. the real world. Its priorities data over
function.

b. What do you mean by method binding? List the types of binding.


Connecting a method call to the method body is known as
binding.
There are two types of binding
Static Binding (also known as Early Binding).
When type of the object is determined at compile time, is known as static binding. If there
is any private, final or static method in a class, there is static binding.

Dynamic Binding (also known as Late Binding).


When type of the object is determined at run time is known as dynamic binding

Type of instances
variables have a type – - int data=30;

references have a type


class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog } }

objects have a type


class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}}

Static binding

class Dog{
private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();
d1.eat();
} }

Dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
a.eat();
}
}
What are the types of control statements available in java? Write a java program to find the
greatest among three numbers.

Conditional/Selection statements. – if / switch


Iteration/Loop statements. – for, while, do-while, for each
Jump statements. – go to

public class Semester2First {


2. public static void main(String[] args) L3
{ int a,b,c;
Scanner in = new Scanner(System.in);
System.out.println("Enter the value for a");
int a = in.nextInt();
System.out.println("Enter the value for b");
int b = in.nextInt();
System.out.println("Enter the value for
c"); int c = in.nextInt();
if(a<b && a<c)
System.out.println("a is small");
else
if (b<a && b<c)
System.out.println("b is small");
else
System.out.println("c is small"); } }
Write a java program to get two strings from the users and apply the String methods
available in java.
import java.util.Scanner;
public class StringSample {
public static void main(String[] args) {
String message = "Welcome to Java";
System.out.println("The lenght of " + message + " is " + message.length());
System.out.println("The character at 8th position of " + message + " is " +
message.charAt(8));
System.out.println("Upper case" + message.toUpperCase());
System.out.println("Lower case" +
message.toLowerCase()); String message1 = "
3 Programming"; L3
System.out.println("concatenation of msg1 and msg2 "+ message.concat(message1));
String msg = "welcome";
String msg1 = "welcome";
System.out.println("Check the Two Strings are same or not;if same means print true else
print false ");
System.out.println("msg equals msg1 = " + msg.equals(msg1));
msg="WELCOME";
msg1="welcome";
System.out.println("Check the Two Strings are same or not ignore case;if same means print
true else print false ");
System.out.println("msg equals msg1 = " + msg.equalsIgnoreCase(msg1));
System.out.println("The sub string of message is = "+ message.substring(0,7));
}}
Differentiate the method overloading and overriding with suitable example.

Method Overloading Method Overriding


Method overloading is used to Method overriding is used to provide the specific
increase the readability of the implementation of the method that is already provided by
program. its super class.
Method overloading is Method overriding occurs in two classes that have IS-A
4 performed within class. (inheritance) relationship. L2

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); } }

b. Explain dynamic method dispatch with a program (run time polymorphism)

Dynamic method dispatch is the mechanism in which a call to an overridden method is


resolved at run time instead of compile time.

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.
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.
class Bike{
void run() { System.out.println("running");}
}
class Splendor extends Bike{
void run() { System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor(); //upcasting
b.run(); } }
Upcasting, When we need to develop a code that deals with only the parent class.
Downcasting is used when we need to develop a code that accesses behaviors of the child
class
List and discuss about the buzz words of java.
• Java Is Simple
Java is partially modeled on C++, but greatly simplified and improved. Some
people refer to Java as "C++--" because it is like C++ but with more functionality
and fewer negative aspects.

• 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
}
}

What do you mean by operator precedence? Discuss.


8 The expression in the parentheses is evaluated first. (Parentheses can be nested, in which L3
case the expression in the inner parentheses is executed first.) When evaluating an
expression without parentheses, the operators are applied according to the precedence rule
and the associativity rule.
If operators with the same precedence are next to each other, their associativity determines
the order of evaluation. All binary operators except assignment operators are left-
associative.

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

Overloading – Constructor Overloading


The constructor overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different task.
The main advantage of constructor overloading is to allow an instance of a class to be
initialized in various ways

Algorithm / Flow Chart / Pseudo Code / Overview

public class Animal { }

public class Mammal extends Animal{ }

public class Dog extends Mammal{ }

public class Elephant extends Mammal{ }

public class Tiger extends Mammal{ }

public class Dove extends Animal{}

public class Parrot extends Animal{ }

Implementation / Explanation

public class Animal {


Animal(){ System.out.println("This is Animal constructor"); }}

public class Mammal extends Animal{


Mammal(){ System.out.println("This is Mammal constructor"); } }

public class Dog extends Mammal{


Dog(){ super();
System.out.println("This is Dog constructor after accessing Animal data members");
}}

public class Elephant extends Mammal{


Elephant(){
super();
System.out.println("This is Elephant constructor after accessing Animal data members"); }
}

public class Tiger extends Mammal{


Tiger(){ super();
System.out.println("This is Tiger constructor after accessing Animal data members"); } }

public class Dove extends Animal{


Dove()
{ super();
System.out.println("This is Dove constructor after accessing Animal data members"); } }

public class Parrot extends Animal{


Parrot(){ super();
System.out.println("This is Parrot constructor after accessing Animal data members"); } }

public class Test {


public static void main(String[] args)
{ Dog d = new Dog();
Tiger ti= new Tiger();
Elephant el = new Elephant();
Dove dov = new Dove();
Parrot pa = new Parrot();
}}
What do you mean by “diamond problem”? Discuss.

The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an


ambiguity that arises when two classes B and C inherit from A, and class D inherits from
both B and C. If there is a method in A that B and C have overridden, and D does not
override it, then which version of the method does D inherit: that of B, or that of C?
GUI software development, a class Button may inherit from both classes Rectangle (for
appearance) and Clickable (for functionality/input handling), and
classes Rectangle and Clickable both inherit from the Object class. Now if
the equals method is called for a Button object and there is no such method in
the Button class but there is an overridden equals method in Rectangle or Clickable (or
both), which method should be eventually called?
10 L2

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");}

public static void main(String args[]){


Sendil obj = new Sendil();
obj.print();
obj.show();
}}
How to read and write the files in streams-based IO?
FileWriter and print the strings using FileReader.

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";

// attach a file to FileWriter


FileWriter fw=new FileWriter("output.txt");

// read character wise from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

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"); }

// read from FileReader till the end of file


while ((ch=fr.read())!=-1)
System.out.print((char)ch);

// close the file


fr.close();
}
}
Discuss the Serialization? Write a simple java program for serialization and
deserialization.
Serialization is a mechanism of converting the state of an object into a byte stream.
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. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.
The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform.
3 L2
package Serial1;
import java.io.Serializable;
public class Employee implements Serializable{
private static final long serialVersionUID = 1L; /*Serial Version UID attribute to
remember versions of a Serializable class to verify that a loaded class and the serialized
object are compatible*/
int id;
String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}}
package Serial1;
import java.io.*;
class Persist{
public static void main(String args[]){
try{ Employee emp1 =new Employee(2018210,“Anesh");
Employee emp2 =new Employee(2018212,“Bala");
Employee emp3 =new Employee(2018214,"Suresh");
FileOutputStream fout=new FileOutputStream("output.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(emp1); out.writeObject(emp2); out.writeObject(emp3);
out.flush(); out.close();
ObjectInputStream in=new ObjectInputStream(new
FileInputStream(“output.txt"));
Employee e1 = (Employee) in.readObject();
System.out.println(e1.id + “ ” + e1.name);
in.close();
System.out.println("Serialization and Deserialization is been successfully executed");
} catch(Exception e){ System.out.println(e);} }
}
Write a simple java program which uses the IO.RandomAccessFile class methods.
// Java Program illustrating use of io.RandomAccessFile class methods
// read(), read(byte[] b), readBoolean(), readByte(), readInt()
// readFully(byte[] b, int off, int len), readFully(), readFloat()
// readChar(), readDouble(),

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");

// File Pointer at index position - 0


f1.seek(0);

// read() method :
System.out.println("Use of read() method : " + f1.read());

f1.seek(0);
byte[] b = {1, 2, 3};

// Use of .read(byte[] b) method :


System.out.println("Use of .read(byte[] b) : " + f1.read(b));

// 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);

// readFully(byte[] b, int off, int len) :


f1.readFully(arr, 0, 8);

String str2 = new String(arr);


System.out.println("Use of readFully(byte[] b, int off, int len) : " + str2);
}
catch (IOException ex)
{
System.out.println("Something went Wrong");
ex.printStackTrace();
} }}
What is the use of interface? How to implement nested interface? Give an example.

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.");
}

public static void main(String a[])


{
Outer obj1=new NestedInterfaceEx();
obj1.dispOuter();

Outer.Inner obj2=new NestedInterfaceEx(); //inner interface reference


object
obj2.dispInner();
}
}
Write a java program to create your own package mypack.Artih for arithmetic
calculations and use it for arithmetic operations.

package mypack;

public class Arith


{
6 L3
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{ return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{r
eturn x%y;
}
}

import mypack.*;

class Test
{
public static void main(String as[])
{

Arith m=new Arith();

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

Using Console to input data from user


public class Sample {
public static void main(String[] args) {
String name =
System.console().readLine();
System.out.println("You entered string " + name); } }
OR
Using Scanner for Getting Input from User

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));

// Reading data using readLine


String name =
reader.readLine();

// Printing the read line


System.out.println(name); }
}
Implement the enumerations with a suitable example

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.

// A simple enum example where enum is declared


// outside any class (Note enum keyword instead of class keyword)
8 L2
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Discuss the java wrapper class with an example.
Wrapper classes are used to convert any data type into an object. The 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
Applications:
1) To convert simple data types into objects, that is, to give object form to a data type;
here constructors are used.
2) To convert strings into data types (known as parsing operations), here methods of
9 L2
type parseXXX() are used.

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);

if(aObj instanceof Integer) {


System.out.println("An object of Integer is created.");
}

if(bObj instanceof Double) {


System.out.println("An object of Double is created."); } }}
Explain auto boxing and unboxing with a program.

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

Integer a2=new Integer(a);//Boxing


Integer a3=5;//Boxing
System.out.println(a2+" "+a3); } }
// Output:50 5

//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"); } } }

What is exception? Discuss the different types of exceptions.


Write a simple java program for exception handling.

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 (or Runtime-Exceptions)

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

Discuss the key differences between process and thread in java.


1. A process is an executing program whereas, the thread is a small part of a process.
2. Each process has its own address space whereas, the threads of the same process share
the address space as that of the process.
3. In process based multitasking, more than two processes can run at the same time
whereas, in thread-based multitasking, more than two thread can run at the same time.
4. Inter-process communication between two processes is costlier than inter-thread
communication.
5. Context switching between two processes is expensive and limited as compared to
context switching between two threads.
6. A process is also called the heavyweight task whereas, the thread is called lightweight
task.
7. Multitasking over a process is not under the control of Java whereas, the Multitasking
over multithreading is under the control of Java.
8. Components contained by a process its own address space, global variables, signal
handlers, open files, child processes, accounting information. On the other hand, a
thread contains its own register, state, stack, program counter.

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");
}

// the main method


public static void main(String argvs[]) {
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();

// We did not mention the priority of the thread.


// Therefore, the priorities of the thread is 5, the default value

// 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());

System.out.println("Priority of the main thread is : " + Thread.currenthread().getPriority());


// Priority of the main thread is 10 now
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}}

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.

1) New (Ready to run)


A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended
A thread is in the Suspended state when it is temporarily inactive or under execution.
4) Blocked
A thread is in the Blocked state when it is waiting for resources.
5) Terminated
A thread comes in this state when at any given time, it halts its execution immediately

Write a simple program to start a thread by implementing Runnable interface

class NewThread implements Runnable {


String name;
4 L2
Thread thread;
NewThread (String name){
this.name = name;
thread = new Thread(this, name);
System.out.println( "A New thread: " + thread+ "is created\n" );
thread.start();
}
public void run() {
try {
for(int j = 5; j > 0; j--) {
System.out.println(name + ": " +
j); Thread.sleep(1000);
} }
catch (InterruptedException e) {
System.out.println(name + " thread Interrupted");
}
System.out.println(name + " thread exiting.");
}}
class ThreadExample2 {
public static void main(String args[])
{ new NewThread("1st");
new NewThread("2nd");
new NewThread("3rd");
try {
Thread.sleep(8000);
} catch (InterruptedException excetion) {
System.out.println("Inturruption occurs in Main
Thread");
}
System.out.println("We are exiting from Main Thread");
}
}
Output:
A New Thread: Thread[1st,5,main] is created
A New Thread: Thread[2nd,5,main] is created
A New Thread: Thread[3rd,5,main] is created
3rd: 5
1st : 5
2nd : 5
3rd: 4
2nd : 4
1st : 4
1st : 3
3rd: 3
2nd : 3
1st : 2
3rd: 2
2nd : 2
3rd: 1
1st : 1
2nd : 1
3rd thread exiting.
1st thread exiting.
2nd thread exiting.
We are exiting from Main Thread
Write a java program to demonstrate inter thread communication.
import java.util.Random;
class FirstThread extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
5 SecondThread sThread = new SecondThread(randomInteger); L2
sThread.start();
}
else {
ThirdThread cThread = new ThirdThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
} }} }
class SecondThread extends Thread {
int number;
SecondThread(int randomNumbern) {
number = randomNumbern;
}
public void run() {
System.out.println("Square of " + number + " = " + (number * number));
}}
class ThirdThread extends Thread {
int number;
ThirdThread(int randomNumber) {
number = randomNumber;
}
public void run() {
System.out.println("Cube of " + number + " = " + number * number * number);
}}
public class ThreeThreads {
public static void main(String[] args) {
// TODO Auto-generated method stub
FirstThread rnThread = new FirstThread();
rnThread.start();
}}

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) {}
}
});

Thread t2 = new Thread(new Runnable()


{
public void run()
{
try { pc.consume();}
catch (Exception e) {}
}
});
t1.start();
t2.start();
}
}

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

Refer thee 5th question for answer

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.

//Write a program to re-throw exception package rethrowexception;


public class RethrowExceptionEx
{
public static void main(String args[])
{
Int x,y,z;
try
{ x=6; y=0; z = x/y ; System.out.println(x + "/"+ y +" = " + z); }
catch(ArithmeticException e)
{ System.out.println("Rethrown Exception Caught in main()");
System.out.println(e);
throw e; // Rethrows an exception
}
} }
Unit 4 Part A
Bloom’s
SI. No. Question Taxonomy
Level
Q1 What are the advantages of Collection framework in java? L1
Ans 1  Reduces programming effort: By providing useful data structures and
algorithms, the Collections Framework frees you to concentrate on the
important parts of your program rather than on the low-level "plumbing"
required to make it work
 Increases program speed and quality: This Collections Framework
provides high-performance, high-quality implementations of useful data
structures and algorithms.
 Allows interoperability among unrelated APIs: The collection
interfaces are the vernacular by which APIs pass collections back and
forth. If my network administration API furnishes a collection of node
names and if your GUI toolkit expects a collection of column headings, our
APIs will interoperate seamlessly, even though they were written
independently.
 Reduces effort to learn and to use new APIs: Many APIs naturally take
collections on input and furnish them as output
 Reduces effort to design new APIs: This is the flip side of the previous
advantage. Designers and implementers don't have to reinvent the wheel
each time they create an API that relies on collections; instead, they can
use standard collection interfaces.
 Fosters software reuse: New data structures that conform to the standard
collection interfaces are by nature reusable. The same goes for new
algorithms that operate on objects that implement these interfaces
Q2 What is the use of Hashtable class? L1
Ans 2 In Java, the Hashtable class is used to store and retrieve key-value pairs in a hash
table, similar to a dictionary or map. It is a legacy class that has been available
since the early versions of Java and is part of the Java Collections Framework.
However, neither keys nor values can be null. When using a Hashtable, you specify an
object that is used as a key, and the value that you want linked to that key. The key is then
hashed, and the resulting hash code is used as the index at which the value is stored within
the table.Also Hashtable is synchronized
The primary use of the Hashtable class in Java is as follows:
 Key-value storage
 Fast retrieval
 Thread-safe operations
 Integration with legacy code
Q3 What is the main difference between Iterator and ListIterator? L2

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( ).

Q9 What is legacy class? L1


Ans 9 Early versions of java.util did not include the Collections Framework. Instead, it
defined several classes and an interface that provided an ad hoc method of storing
objects. When collections were added (by J2SE 1.2), several of the original classes
were reengineered to support the collection interfaces. Thus, they are now
technically part of the Collections Framework. However, where a modern
collection duplicates the functionality of a legacy class, you will usually want to
use the newer collection class. One other point: none of the modern collection
classes are synchronized, but all the legacy classes are synchronized.
The legacy classes defined by java.util are :
 Dictionary
 Hashtable
 Properties
 Stack
 Vector

Q10 What is the use of Vector class? L1


Ans 10 The Vector class in Java is a legacy class that is part of the Java Collections
Framework. It is similar to an ArrayList but provides additional features related to
thread-safety and synchronization. The primary use of the Vector class is as
follows:
Thread-safe operations: The Vector class is designed to be thread-safe, meaning
it can be safely used in multi-threaded environments without causing data
corruption or synchronization issues. All methods in the Vector class are
synchronized by default.
Dynamic array-like functionality: The Vector class provides dynamic array-like
functionality, similar to ArrayList. It allows you to add, retrieve, and remove
elements from the collection. The size of the Vector automatically expands or
shrinks as elements are added or removed, respectively.
Compatibility with legacy code: The Vector class has been available since the
early versions of Java and is a legacy class. It is often used in existing codebases
and libraries that were developed before the introduction of newer collection
classes like ArrayList and LinkedList. If you are working with legacy code or need
to maintain compatibility with older systems, using Vector can be a suitable choice.
Part B
Bloom’s
SI. No. Question
Taxonomy Level
Write a program to create an ArrayList and add all months of year and
Q1 L3
print them using an Iterator.
Ans 1 import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MonthArrayListExample {
public static void main(String[] args)
{
// Create an ArrayList to store the months of the year
List<String> months = new ArrayList<>();
// Add all the months to the ArrayList
months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
// Print the months using an Iterator
Iterator<String> iterator = months.iterator();
while (iterator.hasNext()) {
String month = iterator.next();
System.out.println(month);
}
}
}
Output of the program:
January
February
March
April
May
June
July
August
September
October
November
December
In the above program, an ArrayList named months is created to store the
names of the months. The add() method is used to add all the months to the
list. Then, an iterator is obtained using the iterator() method of the ArrayList.
The hasNext() method is used to check if there are more elements, and the
next() method is used to retrieve the next element from the iterator. The loop
continues until there are no more elements in the list, and each month is
printed using System.out.println()
Write a java program to perform queue operations, i.e., adding,
Q2. L3
deleting, and displaying the elements using PriorityQueue class.
Ans 2 import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// Create a PriorityQueue to store elements
PriorityQueue<String> queue = new PriorityQueue<>();
// Adding elements to the queue
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Orange");
queue.offer("Mango");
// Displaying the elements in the queue
System.out.println("Elements in the queue: " + queue);
// Deleting elements from the queue (FIFO order)
String removedElement = queue.poll();
System.out.println("Removed element: " + removedElement);
// Displaying the updated elements in the queue
System.out.println("Elements in the queue after removal: " + queue);
}
}
Output of the program
Elements in the queue: [Apple, Banana, Orange, Mango]
Removed element: Apple
Elements in the queue after removal: [Banana, Mango, Orange]
In the above program, a PriorityQueue named queue is created to store
elements. The offer() method is used to add elements to the queue. The poll()
method is used to remove and retrieve the head of the queue (the element
with the highest priority). The removed element is stored in the
removedElement variable.
The program then displays the initial elements in the queue using
System.out.println(). After removing an element, it displays the removed
element and the updated elements in the queue.
Q3 Discuss the Collection algorithms used in java. L2
Ans 3 In Java, the java.util.Collections class provides various utility methods that
operate on collections, commonly referred to as collection algorithms. These
algorithms offer convenient and efficient ways to perform operations such as
sorting, searching, shuffling, and more. Here are some of the commonly used
collection algorithms provided by the Collections class:
Sorting: The Collections class provides methods for sorting collections. The
sort() method can be used to sort a list in natural or custom order. There is
also a sort() method that accepts a custom comparator for sorting based on
specific criteria.
Searching: The Collections class includes methods for searching elements in
collections. The binarySearch() method allows you to perform a binary
search on a sorted list to find a specific element. Note that the list must be
sorted before using this method.
Shuffling: The shuffle() method can be used to randomly reorder the
elements in a list. It uses a random number generator to shuffle the elements.
Max and Min: The max() and min() methods provide a convenient way to
find the maximum and minimum elements, respectively, in a collection.
These methods require the collection to be non-empty and the elements to be
comparable.
Synchronizing: The synchronizedCollection(), synchronizedList(), and
synchronizedSet() methods allow you to create synchronized (thread-safe)
versions of collections. These methods wrap the original collection with
synchronized wrappers, ensuring safe concurrent access.
Creating Immutable Collections: The unmodifiableCollection(),
unmodifiableList(), and unmodifiableSet() methods can be used to create
read-only (immutable) versions of collections. These methods wrap the
original collection, preventing any modifications to the collection.
Checking Frequency: The frequency() method allows you to count the
number of occurrences of a specific element in a collection.
Finding Sublist: The subList() method allows you to create a view (sublist)
of a portion of a list based on specified indices.

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

S.NO AWT Swing

Java AWT is an API to Swing is a part of Java Foundation


1. develop GUI applications Classes and is used to create various
in Java applications.

1 The components of Java The components of Java Swing are L2


2.
AWT are heavy weighted. light weighted.

Java AWT has


comparatively less Java Swing has more functionality as
3.
functionality as compared compared to AWT.
to Swing.

The execution time of The execution time of Swing is less


4.
AWT is more than Swing. than AWT.

The components of Java


The components of Java Swing are
5. AWT are platform
platform independent.
dependent.
MVC pattern is not
6. MVC pattern is supported by Swing.
supported by AWT.

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.

The buttons of AWT does not support


pictures. It is heavyweight in nature.
Two very important components trees and tables are not
present. Extensibility is not possible as it is platform dependent.

b. Explain the MVC Architecture.


2. The Model-View-Controller (MVC) is a well-known design pattern in the web L2
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as different
objects
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software
using model designs.

The MVC pattern architecture consists of three layers


Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
View: It represents the presentation layer of application. It is used to visualize the
data that the model contains.
Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data
is changed.

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.

What are the different types of Even Listeners supported by java?

Class Description

A Component is the Abstract base class for


3 about the non menu user-interface controls of L2
Component
SWING. Components are represents an object
with a graphical representation

A Container is a component that can


Container
container SWING Components

A JComponent is a base class for all swing UI


Components In order to use a swing component that
JComponent inherits from JComponent, component must be in a
containment hierarchy whose root is a top-level
Swing container
A JLabel is an object component for placing text in
JLabel
a container

JButton This class creates a labeled button

A JColorChooser provides a pane of controls


JColorChooser designed to allow the user to manipulate and select
a color

A JCheckBox is a graphical(GUI) component


JCheckBox
that can be in either an on-(true) or off-(false)
state

The JRadioButton class is a graphical(GUI)


JRadioButton component that can be in either an on-(true) or off-
(false) state. in the group

A JList component represents the user with


JList
the scrolling list of text items

A JTextField object is a text component that


JTextField
will allow for the editing of a single line of text

A JPasswordField object it is a text component


JPasswordField
specialized for password entry

A JTextArea object is a text component that allows


JTextArea
for the editing of multiple lines of text

A JScrollbar control represents a scroll bar


JScrollbar component in order to enable users to Select from
range values

Explain the life cycle of Applet.

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( ).

What are the various layout managers used in java?


The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc
What is the use of Adapter class? What is their role in event handling?
Java adapter classes provide the default implementation of listener interfaces. 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.
The adapter classes are found in
List of adapter classes defined in java.awt.event :
1. Endow Adapter 2. Key Adapter 3. Mouse Adapter 4. Mouse Motion
Adapter 5. Focus Adapter 6. Componenet Adapter 7. Container
Adapter

List of adapter classes defined in java.awt.dnd:


1. DragSource Adapter 2. Drag Target Adapter

List of adapter classes defined in javax.swing.event:


1. MouseInputAdapter 2. InernalFrameAdapter

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.*;

public class AdapterExample {


// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
} });
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true); }

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

An event that indicates


that a component-defined
action occurred like a
ActionListener actionerformed()
button click or selecting
an item from the menu-
item list.

The adjustment event is


AdjustmentListener adjustmentValueChanged() emitted by an Adjustable
object like Scrollbar.

componentResized() An event that indicates


componentShown() that a component moved,
ComponentListener
componentMoved() the size changed or
componentHidden() changed its visibility.
6 L2
When a component is
added to (or) removed
componentAdded()
ContainerListener then this event is
componentRemoved()
generated by a container
object.

These are focus-related


focusGained() events, which include
FocusListener
focusLost() focus, focusin,
focusout, and blur.

An event that indicates


ItemListener itemStateChanged() whether an item was
selected or not.

An event that occurs due


keyTyped()
to a sequence of
KeyListener keyPressed()
keypresses on the
keyReleased()
keyboard.

MouseListener mousePressed() The events that occur due


MouseMotionListener mouseClicked() to the user interaction
mouseEntered() with the mouse (Pointing
mouseExited() Device).
mouseReleased()

An event that specifies


mouseMoved()
MouseWheelListener that the mouse wheel was
mouseDragged()
rotated in a component.

An event that occurs


TextListener textChanged() when an object’s text
changes.

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(); } }

Explain the Inner Class and its types.

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.

There are basically four types of inner classes in java.


1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes

Type 1: Nested Inner Class


It can access any private instance variable of the outer class. Like any other
instance variable, we can have access modifier private, protected, public, and
default modifier. Like class, an interface can also be nested and can have access
specifiers.
Type 2: Method Local Inner Classes
Inner class can be declared within a method of an outer class which we will be
illustrating in the below example where Inner is an inner class in outerMethod().

Type 3: Static Nested Classes


Static nested classes are not technically inner classes. They are like a static member
of outer class.
Type 4: Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created in
two ways.
 As a subclass of the specified type
 As an implementer of the specified interface

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); } }

public class SampFlow {


public static void main(String[] args)
{
SampFl f = new SampFl(); // create new object
// Function to set title of JFrame.
f.setTitle("Example of FlowLayout");
// Function to set Bounds of JFrame.
f.setBounds(200, 100, 600, 400);
// Function to set visible status of JFrame.
f.setVisible(true);}
}}
//Border Layout

import java.awt.*; import java.awt.event.*; import javax.swing.*;


public class SampBord extends JFrame{
SampBord(){
// Creating Object of Jpanel class
JPanel pa = new JPanel();
// set the layout
pa.setLayout(new BorderLayout());
// add a new JButton with name "wel" and it is
// lie top of the container
pa.add(new JButton("Wel"), BorderLayout.NORTH);
// add a new JButton with name "come" and it is
// lie button of the container
pa.add(new JButton(“Come"), BorderLayout.SOUTH);
// add a new JButton with name "Layout" and it is
// lie left of the container
pa.add(new JButton("Layout"), BorderLayout.EAST);
// add a new JButton with name "Border" and it is
// lie right of the container
pa.add(new JButton("Border"), BorderLayout.WEST);
// add a new JButton with name "hello everybody" and it is
// lie center of the container
pa.add(new JButton("Cyber Security"), BorderLayout.CENTER);
// add the pa object which refer to the Jpanel
add(pa);
// Function to close the operation of JFrame.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Function to set size of JFrame.
setSize(300, 300);
// Function to set visible status of
JFrame. setVisible(true); }}

public class SampBorder {


public static void main(String[] args) {
// TODO Auto-generated method stub
new SampBord(); // calling the constructor
}
}

You might also like