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

Java IMP

The document discusses Java adapter classes and provides examples of commonly used adapter classes in Java. It then discusses the list collection in Java and provides an example. It also explains prepared statements and servlet lifecycle with examples.

Uploaded by

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

Java IMP

The document discusses Java adapter classes and provides examples of commonly used adapter classes in Java. It then discusses the list collection in Java and provides an example. It also explains prepared statements and servlet lifecycle with examples.

Uploaded by

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

Java IMP

1. Explain Adapter Class and Give Example?


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.
Pros of using Adapter classes:
o It assists the unrelated classes to work combinedly.

o It provides ways to use classes in different ways.

o It increases the transparency of classes.

o It provides a way to include related patterns in the class.

o It provides a pluggable kit for developing an application.

o It increases the reusability of the class.

The adapter classes are found in java.awt.event,


java.awt.dnd and javax.swing.event packages.

The Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener
2. Explain List Collection with Example?
The list() method of Java Collections class is used to get an array list containing
the elements returned by the specified enumeration in the order in which they are
returned by the enumeration.

import java.util.*;
public class CollectionsListExample1 {
public static void main(String[] args) {
//Create vector and array list
List<String> arrlist = new ArrayList<String>();
Vector v = new Vector();
//Populate the vector
v.add("A");
v.add("B");
v.add("C");
v.add("D");
v.add("E");
//Create enumeration
Enumeration e = v.elements();
//Get the list
arrlist = Collections.list(e);
System.out.println("Value of returned list: "+arrlist);
}
}

3. Explain Prepared Statement?


The PreparedStatement interface is a subinterface of Statement. It is used to
execute parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set
by calling the setter methods of PreparedStatement.
Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you


use PreparedStatement interface because query is compiled only once.Fullscreen

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the


object of PreparedStatement. Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}


import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();
}catch(Exception e){ System.out.println(e);}
}
}

4. Explain Servlet Life Cycle?


The entire life cycle of a Servlet is managed by the Servlet container which
uses the javax.servlet.Servlet interface to understand the Servlet object and
manage it. So, before creating a Servlet object, let’s first understand the life
cycle of the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through
four stages,
1. Loading a Servlet.
2. Initializing the Servlet.
3. Request handling.
4. Destroying the Servlet.
Loading a Servlet: The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the Servlet container. The Web container or Servlet
Container can load the Servlet at either of the following two stages :
Initializing the context, on configuring the Servlet with a zero or positive
integer value.
If the Servlet is not preceding stage, it may delay the loading process until the
Web container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
Loading : Loads the Servlet class.
Instantiation : Creates an instance of the Servlet. To create a new instance of
the Servlet, the container uses the no-argument constructor.

Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet


container initializes the instantiated Servlet object. The container initializes the
Servlet object by invoking the Servlet.init(ServletConfig) method which
accepts ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only
once, immediately after the Servlet.init(ServletConfig) object is instantiated
successfully. This method is used to initialize the resources, such as JDBC
datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.
Handling request: After initialization, the Servlet instance is ready to serve the
client requests. The Servlet container performs the following operations when
the Servlet instance is located to service a request :
It creates the ServletRequest and ServletResponse objects. In this case, if this
is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the request
and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
Destroying a Servlet: When a Servlet container decides to destroy the Servlet,
it performs the following operations,
 It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
 After currently running threads have completed their jobs, the Servlet
container calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the
references of this Servlet instance so that it becomes eligible for garbage
collection.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
Init ()
Service ()
Destroy ()
Let’s look at each of these methods in details:
init() method: The Servlet.init() method is called by the Servlet container to
indicate that this Servlet instance is instantiated successfully and is about to put
into service.
//init() method

public class MyServlet implements Servlet{


public void init(ServletConfig config) throws ServletException {
//initialization code
}
//rest of code
}
service() method: The service() method of the Servlet is invoked to inform the
Servlet about the client requests.
This method uses ServletRequest object to collect the data requested by the
client.
This method uses ServletResponse object to generate the output content.
// service() method

public class MyServlet implements Servlet{


public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
destroy() method: The destroy() method runs only once during the lifetime of
a Servlet and signals the end of the Servlet instance.
//destroy() method

public void destroy()


As soon as the destroy() method is activated, the Servlet container releases the
Servlet instance.
Servlet Life Cycle:
Servlet life cycle can be defined as the stages through which the servlet passes
from its creation to its destruction.
The servlet life cycle consists these stages:
 Servlet is borned
 Servlet is initialized
 Servlet is ready to service
 Servlet is servicing
 Servlet is not ready to service
 Servlet is destroyed
Life cycle methods:
Life cycle methods are those methods which are used to control the life cycle of
the servlet. These methods are called in specific order during the servlets’s
entire life cycle.
The class Servlet provides the methods to control and supervise the life cycle of
servlet. There are three life cycle methods in the Servlet interface. There are as
follows:
init() method :
 A servlet’s life begins here .
 This method is called only once to load the servlet.Since it is called only
once in it’s lifetime,therefore “connected architecture” code is written inside
it because we only want once to get connected with the database.
Now Question Arises is that:-
Why can’t we write connected architecture code inside the constructor, since
constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an
exception from init() and the rest of the steps stop executing. But in the
constructor we can’t use, throw in it’s prototype otherwise it is an error.
 This method receives only one parameter, i.e ServletConfig object.
 This method has the possibility to throw the ServletException.
 Once the servlet is initialized, it is ready to handle the client request.
 The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
where con is ServletConfig object
NOTE:- In programs of servlet,we use non parameterized version of init().
Now, Question Arises is that:-
Q. Why it is recommended to use the non parameterized version of init() instead
of parameterized version as seen above?
Ans. To answer this, we have to go into detail. Think like developers,i.e there
must be some valid reason for this and the answer will blow your mind. Coming
to answer:
APPROACH 1
Whenever the lifecycle method of a servlet starts executing,i.e when public void
init(ServletConfig con) throws ServletException gets call then our class public
void init(ServletConfig con) throws ServletException gets called but we have to
run the code which initializes servlet config object which is written inside
“HttpServlet” method public void init(ServletConfig con) throws
ServletException,i.e:
Coding of HttpServlet class be like:
public void init(ServletConfig con) throws ServletException
{
//code to initialise ServletConfig object

init(); //This HttpServlet has 2 init() one which is parameterized and the other
one is non
//parameterized.But this non parameterized version of init() has a blank
body.
//So this call is useless.

}
Now see the coding of our class
public void init(ServletConfig con) throws ServletException
{
super.init(con); //Since,our class init() will run first,but to run HttpServlet init()
we
// have used super keyword.And Database connectivity code will be
their
}
NOTE:- As we can see, total 3 init() calls we have to make.First init() gets
called of our class then of HttpServlet class then non parameterized version of
HttpServlet class.
But now, we will achieve the same thing with less number of calls:
APPROACH 2
Coding of HttpServlet parametrized and non parameterized versions of init()
will remain the same. But in our class instead of overriding parameterized
version of init(), we will override non parameterized version of init().
Let’s see the coding of our class non parameterized version of init():
public void init() throws ServletException
{
//database connectivity code
}
NOTE: Since this method public void init() throws ServletException ,we have
override from HttpServlet class whose coding is like:
public void init() throws ServletException
{
//empty body
}
Since it’s body is blank, therefore it is known as “Helper method” as it is used
for overriding purpose.
Now, as the servlet starts executing its methods, it will call the parameterized
version of init(). Since we have not to override the parameterized version,
therefore it will give a call to the HttpServlet parameterized version of init().
Since coding of a parameterized version of init() of HttpServlet is as same as
above, therefore, from there on it will call init() (i.e non parameterized version
of init). It will give a call to our class non parameterized version of init() and
the code continues.
Now, as you can see, total number of init() calls are 2 which is less than the
first approach. Therefore, execution time is less in 2nd approach and less
headache for CPU for maintaining stack and it’s speed increases as
compared to 1st approach.
Therefore, it is highly recommended to override non parameterized version of
init().Although both will run but due to efficiency first approach is rarely used
and also in first approach we have to use super keyword too.Therefore in below
mentioned program,we have override non parameterized version of init().
service() method :
1. The service() method is the most important method to perform that provides
the connection between client and server.
2. The web server calls the service() method to handle requests coming from the
client( web browsers) and to send response back to the client.
3. This method determines the type of Http request (GET, POST, PUT,
DELETE, etc.) .
4. This method also calls various other methods such as doGet(), doPost(),
doPut(), doDelete(), etc. as required.
5. This method accepts two parameters.
6. The prototype for this method:
7. public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException { }
where
 req is the ServletRequest object which encapsulates the connection from
client to server
 resp is the ServletResponse object which encapsulates the connection from
server back to the client
 destroy() method :
8. The destroy() method is called only once.
9. It is called at the end of the life cycle of the servlet.
10. This method performs various tasks such as closing connection with
the database, releasing memory allocated to the servlet, releasing
resources that are allocated to the servlet and other cleanup activities.
11. When this method is called, the garbage collector comes into action.
12. The prototype for this method is:
public void destroy() { // Finalization code...}
Below is a sample program to illustrate Servlet in Java:

// Java program to show servlet example


// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
// Requesting and printing the output
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

5. What is method overloading with example?

If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because
its name differs.

So, we perform method overloading to figure out the program quickly.

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the
method only.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33

6. Diff Between Method Overloading and method overriding?

No Method Overloading Method Overriding


.

1) Method overloading is used to increase Method overriding is used to


the readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.
2) Method overloading is performed within Method overriding occurs in
class. two classes that have IS-A
(inheritance) relationship.
3) In case of method In case of method
overloading, parameter must be different. overriding, parameter must be
same.
4) Method overloading is the example Method overriding is the
of compile time polymorphism. example of run time
polymorphism.
5) In java, method overloading can't be Return type must be same or
performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
7. Difference Between array list and vector?

Array List Vector

1) ArrayList is not Vector is synchronized.


synchronized.
2) ArrayList increments 50% of Vector increments 100% means doubles the
current array size if the number array size if the total number of elements
of elements exceeds from its exceeds than its capacity.
capacity.
3) ArrayList is not a Vector is a legacy class.
legacy class. It is introduced in
JDK 1.2.
4) ArrayList is fast because it is Vector is slow because it is synchronized, i.e.,
non-synchronized. in a multithreading environment, it holds the
other threads in runnable or non-runnable state
until current thread releases the lock of the
object.
5) ArrayList uses A Vector can use the Iterator interface
the Iterator interface to traverse or Enumeration interface to traverse the
the elements. elements.

8. Explain Inheritance with Example?


Java, Inheritance is an important pillar of OOP (Object-Oriented Programming).
It is the mechanism in Java by which one class is allowed to inherit the features
(fields and methods) of another class. In Java, Inheritance means creating new
classes based on existing ones. A class that inherits from another class can reuse
the methods and fields of that class. In addition, you can add new fields and
methods to your current class as well.
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.
Important Terminologies Used in Java Inheritance
 Class: Class is a set of objects which shares common characteristics/
behavior and common properties/ attributes. Class is not a real-world entity.
It is just a template or blueprint or prototype from which objects are created.
 Super Class/Parent Class: The class whose features are inherited is known
as a superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can
add its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends
keyword indicates you are derived from an existing class. In other words,
“extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Inheritance in Java Example
Example: In the below example of inheritance, class Bicycle is a base class,
class MountainBike is a derived class that extends the Bicycle class and class
Test is a driver class to run the program.
// Java program to illustrate the concept of inheritance base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}

// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
in the above program, when an object of MountainBike class is created, a copy
of all methods and fields of the superclass acquires memory in this object. That
is why by using the object of the subclass we can also access the members of a
superclass.
9. Explain Interface with Example?
An Interface in Java programming language is defined as an abstract type used
to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
What are Interfaces in Java?
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not the method body. It is used to
achieve abstraction and multiple inheritances in Java using Interface . In other
words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body. Java Interface also represents the IS-A
relationship.
When we decide on a type of entity by its behavior and not via attribute we
should define it as an interface.
// Java program to demonstrate the
// real-world example of Interfaces

import java.io.*;

interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements Vehicle{

int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements Vehicle {


int speed;
int gear;

// to change gear
@Override
public void changeGear(int newGear){

gear = newGear;
}

// to increase speed
@Override
public void speedUp(int increment){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}

}
class GFG {

public static void main (String[] args) {

// creating an instance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle present state :");
bicycle.printStates();

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}

10. Explain Types of Class?


Different types of classes:
 Static Class.
 Final Class.

 Abstract Class.

 Concrete Class.

 Singleton Class.

 POJO Class.

 Inner Class.

1. Static Class
We can declare a class as static if and only if it is a nested class. We can declare
an inner class with the static modifier, such types of inner classes are called
static nested classes.
2. Final Class
The class can be declared as final by using the keyword ‘final’. If a class is
declared as final we can’t extend the functionality of that class i.e we can’t
create a child class for that class, i.e inheritance is not possible for final classes.
Every method present inside the ultimate class is usually final by default, but
every variable present inside the ultimate class needn’t be final.
3. Abstract Class
We can declare a class as abstract by using the keyword ‘abstract’. For any java
class if we are not allowed to create an object such type of class, we should
declare with the abstract modifier, i.e for abstract classes instantiation is not
possible. If a class contains at least one abstract method then compulsory we
should declare a class as abstract otherwise we get a compilation error.
4. Concrete Class
A concrete class is nothing but a normal or regular class in java. A concrete
class is a class that extends another class or implements an interface.
5. Singleton Class
For any java class if we are allowed to make just one object such sort of class is
claimed to be a singleton class.
6. POJO Class
POJO stands for Plain Old Java Object. If we write a category, then it got to
follow some rules referred to as POJO rules. it’s wont to java to extend
readability and reusability. It provides Encapsulation.
7. Inner Class
Sometimes we can declare a class inside another class such types of classes is
called inner classes. Inner classes concept is introduced to fix GUI bugs as a
part of event handling but because of powerful features and benefits of inner
classes slowly programmers are started using in regular coding also. Without
existing one type of object there is no chance of executing another type of
object then we should go for inner classes.
Anonymous Inner classes:
Sometimes we declare inner classes without a name such types of inner classes
are called anonymous inner classes. The main purpose of anonymous inner
classes is just for instant use. Based on declaration and behavior there are three
types of anonymous inner classes
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
3. Anonymous inner class that defines the inside argument

11. Explain Encapsulation with example?


Encapsulation in Java is a fundamental concept in object-oriented
programming (OOP) that refers to the bundling of data and methods that
operate on that data within a single unit, which is called a class in Java. Java
Encapsulation is a way of hiding the implementation details of a class from
outside access and only exposing a public interface that can be used to
interact with the class.

// Java Program to demonstrate


// Java Encapsulation
// Person Class
class Person {
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }


}
public class Main {
// main function
public static void main(String[] args)
{
// person object created
Person person = new Person();
person.setName("John");
person.setAge(30);

// Using methods to get the values from the


// variables
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
12. Explain Access Modifier in java?

Here are two types of modifiers in Java: access modifiers and non-access
modifiers.
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package
and outside the package through child class. If you do not make the child
class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.

There are many non-access modifiers, such as static, abstract, synchronized,


native, volatile, transient, etc. Here, we are going to learn the access modifiers
only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

13. Explain Object life Time, Garbage Collection.


14. Explain runtime polymorphism?
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and


runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

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


call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

In this example, we are creating two classes Bike and Splendor. Splendor class
extends Bike class and overrides its run() method. We are calling the run method
by the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, the subclass method is
invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as


runtime polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }

Output:

running safely with 60km.

15. Explain Tree set With Example?


Tree Set is one of the most important implementations of the Sorted Set
interface in Java that uses a Tree for storage. The ordering of the elements is
maintained by a set using their natural ordering whether or not an
explicit comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface.

It can also be ordered by a Comparator provided at set creation time, depending


on which constructor is used. The TreeSet implements a NavigableSet
interface by inheriting AbstractSet class.

treeSet is basically an implementation of a self-balancing binary search tree


like a Red-Black Tree. Therefore operations like add, remove, and search
takes O(log(N)) time. The reason is that in a self-balancing tree, it is made
sure that the height of the tree is always O(log(N)) for all the operations.
Therefore, this is considered as one of the most efficient data structures in
order to store the huge sorted data and perform operations on it. However,
operations like printing N elements in the sorted order take O(N) time.

16. Explain super Keywords?


The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of Java super Keyword

super can be used to refer immediate parent class instance variable.

super can be used to invoke immediate parent class method.

super() can be used to invoke immediate parent class constructor.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

17. Explain Import And Static Import In Java?


The import allows the java programmer to access classes of a package without
package qualification whereas the static import feature allows to access the
static members of a class without the class qualification. The import provides
accessibility to classes and interface whereas static import provides
accessibility to static members of the class.
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");

}
}

18. Explain Exception Handling Also Explain All Types Of exception in


detail with suitable example?
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of
the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions.The
java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException
and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked


exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Keyword Description

try The "try" keyword is used to specify a block where we should


place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It
specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method
signature.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

19. Explain Arrays In Java, What are the types of array In java ?

Normally, an array is a collection of similar type of elements which has


contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store only
a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java: arrayRefVar=new datatype[size];

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop

class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Example of Multidimensional Java Array
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
20. Explain Regular Expressions In Java With Example?

The Java Regex or Regular Expression is an API to define a pattern for


searching or manipulating strings.

It is widely used to define the constraint on strings such as password and email
validation. After learning Java regex tutorial, you will be able to test your regular
expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.

The . (dot) represents a single character.

import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)
}}

21. Explain Input And Output Operation in java ?


Java brings various Streams with its I/O package that helps the user to perform
all the input-output operations. These streams support all the types of objects,
data-types, characters, files etc to fully execute the I/O operations.
Before exploring various input and output streams lets look at 3 standard or
default streams that Java has to provide which are also most common in use:

Types of Streams:
1. Input Stream: These streams are used to read data that must be taken as an
input from a source array or file or any peripheral device. For eg.,
FileInputStream, BufferedInputStream, ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as outputs into an array
or file or any output peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.

3. ByteStream: This is used to process data byte by byte (8 bits). Though it has
many classes, the FileInputStream and the FileOutputStream are the most
popular ones. The FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination. Here is the list of
various ByteStream Classes:
Stream class Description
Stream class Description
BufferedReader It is used to handle buffered input stream.
BufferedInputStream It is used for Buffered Input Stream.
FileReader This is an input stream that reads from file.
It contains method for reading java standard
DataInputStream
datatypes.
InputStreamReader This input stream is used to translate byte to character.

FileInputStream This is used to reads from a file


OutputStreamReader This output stream is used to translate character to byte.

InputStream This is an abstract class that describes stream input.


This is an abstract class that define character stream
Reader
input.
This contains the most used print() and println()
PrintStream
method
This contains the most used print() and println()
PrintWriter
method
BufferedOutputStream This is used for Buffered Output Stream.
This is an abstract class that define character stream
Writer
output.
This contains method for writing java standard data
DataOutputStream
types.
BufferedWriter This is used to handle buffered output stream.
FileOutputStream This is used to write to a file.
FileWriter This is used to output stream that writes to file.
OutputStream This is an abstract class that describe stream output.

4. CharacterStream: In Java, characters are stored using Unicode conventions


(Refer this for details). Character stream automatically allows us to
read/write data character by character. Though it has many classes, the
FileReader and the FileWriter are the most popular ones. FileReader and
FileWriter are character streams used to read from the source and write to the
destination respectively. Here is the list of various CharacterStream Classes:

22. Explain Event Driven Programming with example ?


Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
import javax.swing.*;
import java.awt.*;
public class StudentRegistrationForm {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("Student Registration Form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel to hold the form components


JPanel panel = new JPanel();
panel.setLayout(new GridLayout(7, 2));

// Add labels and text fields for student information


panel.add(new JLabel("First Name:"));
JTextField firstNameField = new JTextField(20);
panel.add(firstNameField);

panel.add(new JLabel("Last Name:"));


JTextField lastNameField = new JTextField(20);
panel.add(lastNameField);

panel.add(new JLabel("Email Address:"));


JTextField emailField = new JTextField(20);
panel.add(emailField);
panel.add(new JLabel("Phone Number:"));
JTextField phoneField = new JTextField(20);
panel.add(phoneField);

panel.add(new JLabel("Course:"));
JTextField courseField = new JTextField(20);
panel.add(courseField);

panel.add(new JLabel("Year Level:"));


JTextField yearLevelField = new JTextField(20);
panel.add(yearLevelField);

// Create a button to submit the registration form


JButton submitButton = new JButton("Submit");
submitButton.addActionListener(e -> {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String email = emailField.getText();
String phone = phoneField.getText();
String course = courseField.getText();
String yearLevel = yearLevelField.getText();

// Display a confirmation message


JOptionPane.showMessageDialog(frame, "Registration successful!\n" +
"First Name: " + firstName + "\n" +
"Last Name: " + lastName + "\n" +
"Email Address: " + email + "\n" +
"Phone Number: " + phone + "\n" +
"Course: " + course + "\n" +
"Year Level: " + yearLevel);
});

panel.add(submitButton);

frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
23. Explain Architecture Of Web Application with Challenges?
24. Major Difference Between Developing and Deployment
Servelet?
25. What Is JSP With Example?
Java Server Pages technology (JSP) is a server-side programming language used
to create a dynamic web page in the form of HyperText Markup Language
(HTML). It is an extension to the servlet technology.

A JSP page is internally converted into the servlet. JSP has access to the entire
family of the Java API including JDBC API to access enterprise database. Hence,
Java language syntax has been used in the java server pages (JSP). The JSP pages
are more accessible to maintain than Servlet because we can separate designing
and development. It provides some additional features such as Expression
Language, Custom Tags, etc.

26. Explain Different Types of constructor in Thread class.


Thread a line of execution within a program. Each program can have multiple
associated threads. Each thread has a priority which is used by the thread
scheduler to determine which thread must run first. Java provides a thread class
that has various method calls in order to manage the behavior of threads by
providing constructors and methods to perform operations on threads.
Constructor Action Performed

Thread() Allocates a new Thread object.

Thread(Runnable target) Allocates a new Thread object.

Thread(Runnable target, String


Allocates a new Thread object.
name)

Thread(String name) Allocates a new Thread object.

Thread(ThreadGroup group,
Allocates a new Thread object.
Runnable target)

Allocates a new Thread object so that it has


Thread(ThreadGroup group, targeted as its run object, has the specified
Runnable target, String name) name as its name, and belongs to the thread
group referred to by a group.

Allocates a new Thread object so that it has


Thread(ThreadGroup group, targeted as its run object, has the specified
Runnable target, String name, name as its name, and belongs to the thread
long stackSize) group referred to by group, and has the
specified stack size.

Thread(ThreadGroup group,
Allocates a new Thread object.
String name)

Methods of Thread class:

Now let us do discuss all the methods of this class are illustrated as follows:
Methods Action Performed

Returns an estimate of the number


of active threads in the current
activeCount()
thread’s thread group and its
subgroups

Determines if the currently running


checkAccess() thread has permission to modify
this thread

Throws
CloneNotSupportedException as a
clone()
Thread can not be meaningfully
cloned

Returns a reference to the currently


currentThread()
executing thread object

Prints a stack trace of the current


dumpStack()
thread to the standard error stream

getId() Returns the identifier of this Thread

getName() Returns this thread’s name

getPriority() Returns this thread’s priority

Returns an array of stack trace


getStackTrace() elements representing the stack
dump of this thread

getState() Returns the state of this thread


Methods Action Performed

Returns the thread group to which


getThreadGroup()
this thread belongs

Returns the handler invoked when


getUncaughtExceptionHandler() this thread abruptly terminates due
to an uncaught exception

interrupt() Interrupts this thread

Tests whether the current thread has


interrupted()
been interrupted

isAlive() Tests if this thread is alive

Tests if this thread is a daemon


isDaemon()
thread

Tests whether this thread has been


isInterrupted()
interrupted

join() Waits for this thread to die

Waits at most millis milliseconds


join(long millis)
for this thread to die

If this thread was constructed using


a separate Runnable run object, then
run() that Runnable object’s run method
is called; otherwise, this method
does nothing and returns
Methods Action Performed

Sets the context ClassLoader for


setContextClassLoader(ClassLoader cl)
this Thread

Marks this thread as either a


setDaemon(boolean on)
daemon thread or a user thread

Set the default handler invoked


when a thread abruptly terminates
setDefaultUncaughtExceptionHandler(
due to an uncaught exception, and
Thread.UncaughtExceptionHandler eh)
no other handler has been defined
for that thread

Changes the name of this thread to


setName(String name)
be equal to the argument name.

Set the handler invoked when this


setUncaughtExceptionHandler( Thread.
thread abruptly terminates due to an
UncaughtExceptionHandler eh)
uncaught exception

setPriority(int newPriority) Changes the priority of this thread

Causes the currently executing


thread to sleep (temporarily cease
execution) for the specified number
sleep(long millis)
of milliseconds, subject to the
precision and accuracy of system
timers and schedulers

Causes this thread to begin


start() execution; the Java Virtual Machine
calls the run method of this thread
Methods Action Performed

Returns a string representation of


toString() this thread, including the thread’s
name, priority, and thread group

A hint to the scheduler that the


yield() current thread is willing to yield its
current use of a processor

27. Differentiate character stream and Byte Stream?

Aspect Character Streams Byte Streams

Data Handling Handle character-based Handle raw binary data


data
Representation Classes end with "Reader" Classes end with
or "Writer" "InputStream" or
"OutputStream"
Suitable for Textual data, strings, Non-textual data, binary
human-readable info files, multimedia
Character Encoding Automatic encoding and No encoding or decoding
decoding
Text vs non-Text data Text-based data, strings Binary data, images, audio,
video
Performance Additional conversion Efficient for handling large
may impact performance binary data

Handle Large Text May impact performance Efficient, no encoding


Files due to encoding overhead

String Operations Convenient methods for Not specifically designed


string operations for string operations
Convenience Methods Higher-level abstractions Low-level interface for
for text data byte data

Reading Line by Line Convenient methods for Byte-oriented, no built-in


reading lines line-reading methods
File Handling Read/write text files Read/write binary files
Network Sending/receiving text Sending/receiving binary
Communication data data
Handling Not designed for handling Suitable for handling
Images/Audio/Video binary data directly binary multimedia data

Text Encoding Supports various character No specific text encoding


encodings support

28. Explain Nested Classes?

Java inner class or nested class is a class that is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.

Additionally, it can access all the members of the outer class, including private
data members and methods.

class Outer_Demo {
int num;

// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}

29. Explain Synchronized keyword.


Java Synchronization is used to make sure by some synchronization method that
only one thread can access the resource at a given point in time. Java provides a
way of creating threads and synchronizing their tasks using synchronized
blocks.
A synchronized block in Java is synchronized on some object. All synchronized
blocks synchronize on the same object and can only have one thread executed
inside them at a time. All other threads attempting to enter the synchronized
block are blocked until the thread inside the synchronized block exits the block.
Types of Synchronization
There are two synchronizations in Java mentioned below:
1. Process Synchronization
2. Thread Synchronization
1. Process Synchronization in Java

Process Synchronization is a technique used to coordinate the execution of


multiple processes. It ensures that the shared resources are safe and in order.

2. Thread Synchronization in Java

Thread Synchronization is used to coordinate and ordering of the execution of


the threads in a multi-threaded program. There are two types of thread
synchronization are mentioned below:
 Mutual Exclusive
 Cooperation (Inter-thread communication in Java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while
sharing data. There are three types of Mutual Exclusive mentioned below:
 Synchronized method.
 Synchronized block.
 Static synchronization.
Example of Synchronization
Below is the implementation of the Java Synchronization:

 Java
// A Java program to demonstrate working of
// synchronized.

import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender {
public void send(String msg)
{
System.out.println("Sending\t" + msg);
try {
Thread.sleep(1000);
}
catch (Exception e) {
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread {
private String msg;
Sender sender;

// Receives a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized (sender)
{
// synchronizing the send object
sender.send(msg);
}
}
}

// Driver class
class SyncDemo {
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 = new ThreadedSend(" Hi ", send);
ThreadedSend S2 = new ThreadedSend(" Bye ", send);

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try {
S1.join();
S2.join();
}
catch (Exception e) {
System.out.println("Interrupted");
}
}
}

Output
Sending Hi

Hi Sent
Sending Bye

Bye Sent
The output is the same every time we run the program.

30. Explain Scanner .


in Java, Scanner is a class in java.util package used for obtaining the input of
the primitive types like int, double, etc. and strings. Using the Scanner class in
Java is the easiest way to read input in a Java program, though not very efficient
if you want an input method for scenarios where time is a constraint like in
competitive programming.
Scanner class helps to take the standard input stream in Java. So, we need some
methods to extract data from the stream.
 To create an object of Scanner class, we usually pass the predefined object
System.in, which represents the standard input stream. We may pass an
object of class File if we want to read input from a file.
 To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use
nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function returns
the next token/word in the input as a string and charAt(0) function returns
the first character in that string.
 The Scanner class reads an entire line and divides the line into tokens.
Tokens are small elements that have some meaning to the Java compiler.
For example, Suppose there is an input string: How are you
In this case, the scanner object will read the entire line and divides the
string into tokens: “How”, “are” and “you”. The object then iterates over
each token and reads each token using its different methods.
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;

public class ScannerDemo2 {


public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// Initialize sum and count of input elements


int sum = 0, count = 0;

// Check if an int value is available


while (sc.hasNextInt()) {
// Read an int value
int num = sc.nextInt();
sum += num;
count++;
}
if (count > 0) {
int mean = sum / count;
System.out.println("Mean: " + mean);
}
else {
System.out.println(
"No integers were input. Mean cannot be calculated.");
}
}
}
31. Explain wrapper classes in java
The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic conversion of
primitive into an object is known as autoboxing and vice-versa unboxing.

Primitive Type Wrapper class


boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character

public class WrapperExample1{


public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) i
nternally

System.out.println(a+" "+i+" "+j);


}}

Output:

20 20 20

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type
is known as unboxing. It is the reverse process of autoboxing.
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}

Output:

333

32. Different types of layout managers with examples


Java LayoutManagers

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

Example of BorderLayout class: Using BorderLayout() constructor


FileName: Border.java

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

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Output:: 3.30%Fullscreen

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.
33. Explain Action Listener class
The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found
in java.awt.event package. It has only one method: actionPerformed().

The actionPerformed() method is invoked automatically whenever you click on


the registered component.

public abstract void actionPerformed(ActionEvent e);

example
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}

Output:
34. What is Request Dispatcher?
The RequestDispatcher interface provides the facility of dispatching the request
to another resource it may be html, servlet or jsp. This interface can also be
used to include the content of another resource also. It is one of the way of
servlet collaboration.
There are two methods defined in the RequestDispatcher interface.The
RequestDispatcher interface provides two methods. They are:
1. public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.

in the above figure, response of second servlet is sent to the client. Response
of the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in
the response of the first servlet that is being sent to the client.

35. Write servlet to accept student information from HTML page, and
store the details in a database. [Note: Take suitable fields.]
CREATE TABLE "REGISTERUSER"
( "NAME" VARCHAR2(4000),
"PASS" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"COUNTRY" VARCHAR2(4000)
)
/
To create the registration page in servlet, we can separate the database logic
from the servlet. But here, we are mixing the database logic in the servlet only
for simplicity of the program. We will develop this page in JSP following
DAO, DTO and Singleton design pattern later.

In this example, we have created the three pages.

o register.html
o Register.java
o web.xml

register.html
In this page, we have getting input from the user using text fields and combobox.
The information entered by the user is forwarded to Register servlet, which is
responsible to store the data into the database.

<html>
<body>
<form action="servlet/Register" method="post">

Name:<input type="text" name="userName"/><br/><br/>


Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>

<br/><br/>
<input type="submit" value="register"/>

</form>
</body>
</html>

Register.java

This servlet class receives all the data entered by user and stores it into the
database. Here, we are performing the database logic. But you may separate it,
which will be better for the web application.

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Register extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");

try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");

ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);

int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");

}catch (Exception e2) {System.out.println(e2);}

out.close();
}

web.xml file

The is the configuration file, providing information about the servlet.

<web-app>

<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>

</web-app>
36. Explain servlet life - cycle.
1. Servlet instance is created.
2. init method is invoked.
3. service method is invoked.
4. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it
shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.Backward Skip
10sPlay VideoForward Skip 10s

3) init method is invoked


The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle
method of the javax.servlet.Servlet interface. Syntax of the init method is
given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls the
service method. Notice that servlet is initialized only once. The syntax of the
service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
public void destroy()

37. What is the difference between the Enumeration and Iterator


interface?

Iterator Enumeration

Iterator is a universal cursor as it is


Enumeration is not a universal cursor as
applicable for all the collection
it applies only to legacy classes.
classes.

Enumeration does not have the remove()


Iterator has the remove() method.
method.

Iterator can do modifications (e.g Enumeration interface acts as a read only


using remove() method it removes the interface, one can not do any
element from the Collection during modifications to Collection while
traversal). traversing the elements of the Collection.

Iterator is not a legacy interface.


Iterator can be used for the traversal Enumeration is a legacy interface which
of HashMap, LinkedList, ArrayList, is used for traversing Vector, Hashtable.
HashSet, TreeMap, TreeSet .

38. Differentiate between method and constructor.

Constructors Methods

A Method is a collection of statements


A Constructor is a block of code that
which returns a value upon its
initializes a newly created object.
execution.

A Constructor can be used to initialize A Method consists of Java code to be


an object. executed.

A Constructor is invoked implicitly by A Method is invoked by the


the system. programmer.

A Constructor is invoked when a A Method is invoked through method


Constructors Methods

object is created using the


calls.
keyword new.

A Constructor doesn’t have a return


A Method must have a return type.
type.

A Constructor initializes a object that A Method does operations on an


doesn’t exist. already created object.

A Constructor’s name must be same as


A Method’s name can be anything.
the name of the class.

A class can have many Constructors A class can have many methods but
but must not have the same parameters. must not have the same parameters.

A Constructor cannot be inherited by A Method can be inherited by


subclasses. subclasses.

39. What is difference between Iterator and List Iterator?

Iterator ListIterator

Can traverse elements present in


Can traverse elements present in
Collection both in forward and
Collection only in the forward direction.
backward directions.

Can only traverse List and not the


Helps to traverse Map, List and Set.
other two.

It has methods like nextIndex()


Indexes cannot be obtained by using and previousIndex() to obtain
Iterator. indexes of elements at any time
while traversing List.

Cannot modify or replace elements We can modify or replace


present in Collection elements with the help of set(E e)
Iterator ListIterator

Cannot add elements and it throws Can easily add elements to a


ConcurrentModificationException. collection at any time.

Certain methods of ListIterator


Certain methods of Iterator are next(),
are next(), previous(), hasNext(),
remove() and hasNext().
hasPrevious(), add(E e).

40. Explain ‘this’ keyword

There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

111 ankit 5000.0


112 sumit 6000.0

41. Explain thread life cycle

In Java, a thread always exists in any one of the following states. These states
are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not begun its
execution.

Active: When a thread invokes the start() method, it moves from the new state to
the active state. The active state contains two states within it: one is runnable,
and the other is running.

Runnable: A thread, that is ready to run is then moved to the runnable


state. In the runnable state, the thread may be running or may be ready to
run at any given instant of time. It is the duty of the thread scheduler to
provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to
each individual thread. Each and every thread runs for a short span of time
and when that allocated time slice is over, the thread voluntarily gives up
the CPU to the other thread, so that the other threads can also run for their
slice of time. Whenever such a scenario occurs, all those threads that are
willing to run, waiting for their turn to run, lie in the runnable state. In the
runnable state, there is a queue where the threads lie.

o Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not


permanently) then, either the thread is in the blocked state or is in the waiting
state.

For example, a thread (let's say its name is A) may want to print some data from
the printer. However, at the same time, the other thread (let's say its name is B) is
using the printer to print some data. Therefore, thread A has to wait for thread B
to use the printer. Thus, thread A is in the blocked state. A thread in the blocked
state is unable to perform any execution and thus never consume any cycle of the
Central Processing Unit (CPU). Hence, we can say that thread A remains idle
until the thread scheduler reactivates thread A, which is in the waiting or blocked
state.

When the main thread invokes the join() method then, it is said that the main
thread is in the waiting state. The main thread then waits for the child threads to
complete their tasks. When the child threads complete their job, a notification is
sent to the main thread, which again moves the thread from waiting to the active
state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of
the thread scheduler to determine which thread to choose and which one to reject,
and the chosen thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a


thread (its name is A) has entered the critical section of a code and is not willing
to leave that critical section. In such a scenario, another thread (its name is B) has
to wait forever, which leads to starvation. To avoid such scenario, a timed
waiting state is given to thread B. Thus, thread lies in the waiting state for a
specific span of time, and not forever. A real example of timed waiting is when
we invoke the sleep() method on a specific thread. The sleep() method puts the
thread in the timed wait state. After the time runs out, the thread wakes up and
start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following


reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words,
the thread is dead, and there is no way one can respawn (active after kill) the
dead thread.

The following diagram shows the different states involved in the life cycle of a
thread.

42. List any four methods of file class


Return
Method Description Type

Tests whether the application can


canExecute() execute the file denoted by this boolean
abstract pathname.

Tests whether the application can


canRead() read the file denoted by this abstract boolean
pathname.

Tests whether the application can


canWrite() modify the file denoted by this boolean
abstract pathname.

Compares two abstract pathnames


compareTo(File pathname) int
lexicographically.

Atomically creates a new, empty file


createNewFile() boolean
named by this abstract pathname.

createTempFile(String prefix, Creates an empty file in the default


File
String suffix) temporary-file directory.

Deletes the file or directory denoted


delete() boolean
by this abstract pathname.

Tests this abstract pathname for


equals(Object obj) boolean
equality with the given object.

Tests whether the file or directory


exists() denoted by this abstract pathname boolean
exists.

Returns the absolute pathname


getAbsolutePath() String
string of this abstract pathname.
Java File class is Java’s representation of a file or directory pathname.
Because file and directory names have different formats on different platforms,
a simple string is not adequate to name them. Java File class contains several
methods for working with the pathname, deleting and renaming files, creating
new directories, listing the contents of a directory, and determining several
common attributes of files and directories.

43. Explain Abstract class and Interfaces


Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.
But there are many differences between abstract class and interface that are
given below.

Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and
static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend An interface can extend another Java
another Java class and implement interface only.
multiple Java interfaces.
7) An abstract class can be extended An interface can be implemented using
using keyword "extends". keyword "implements".
8) A Java abstract class can have Members of a Java interface are public by
class members like private, protected, default.
etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

44. Explain InputstreamReader and OutputStream Writer


An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes them into characters using a specified charset. The
charset that it uses may be specified by name or may be given explicitly, or the
platform's default charset may be accepted.
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
1. }

Output:

I love my country

The file.txt contains text "I love my country" the InputStreamReader


reads Character by character from the file

OutputStreamWriter is a class which is used to convert character stream to


byte stream, the characters are encoded into byte using a specified charset.
write() method calls the encoding converter which converts the character into
bytes. The resulting bytes are then accumulated in a buffer before being
written into the underlying output stream. The characters passed to write()
methods are not buffered.
public class OutputStreamWriterExample {
public static void main(String[] args) {

try {
OutputStream outputStream = new FileOutputStream("output.txt");
Writer outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");

outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}

You might also like