Sie sind auf Seite 1von 111

Core Java(35 questions)

Q 1. Features of oops?
Class, Encapsulation, Abstraction, Inheritence, Polymorphism
The programming in which data is logically represented in the form of a class and physically represented
in the form an object is called as object oriented programming (OOP)

More reliable software development is possible.


Enhanced form of c programming language.
The most important Feature is that its procedural and object oriented nature.

Q 2. What is encapsulation? How to achieve it?


Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as as single unit. In encapsulation the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class, therefore it is also known as
data hiding.
To achieve encapsulation in Java

Declare the variables of a class as private.

Provide public setter and getter methods to modify and view the variables values.

Example: Below given is an example that demonstrates how to achieve Encapsulation in Java:
/* File name : EncapTest.java */
public class EncapTest{
private String name;
private String idNum;
private int age;
{

public int getAge()


return age;
}

public String getName()


return name;
}

public String getIdNum()


return idNum;
}
public void setAge( int newAge)

age = newAge;

public void setName(String newName)


name = newName;
}

public void setIdNum( String newId)


idNum = newId;
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore any class that
wants to access the variables should access them through these getters and setters.
The variables of the EncapTest class can be accessed as below::
/* File name : RunEncap.java */
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " +
encap.getAge());
}
}

This would produce the following result:


Name : James Age : 20

Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.

A class can have total control over what is stored in its fields.

The users of a class do not know how the class stores its data. A class can change the data
type of a field and users of the class do not need to change any of their code.

Q 3. What is abstraction?

In Object oriented programming Abstraction is a process of hiding the implementation details


from the user, only the functionality will be provided to the user. In other words user will have
the information on what the object does instead of how it does it.

In Java Abstraction is achieved using Abstract classes, and Interfaces.

Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.

Abstract classes may or may not contain abstract methods ie., methods with out body
( public void get(); )

But, if a class have at least one abstract method, then the class must be declared abstract.

If a class is declared abstract it cannot be instantiated.

To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.

If you inherit an abstract class you have to provide implementations to all the abstract
methods in it.

Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as
abstract.

abstract keyword is used to declare the method as abstract.

You have to place the abstract keyword before the method name in the method
declaration.

An abstract method contains a method signature, but no method body.

Instead of curly braces an abstract method will have a semoi colon ( ; ) at the end.

Declaring a method as abstract has two consequences:

The class containing it must be declared as abstract.

Any class inheriting the current class must either override the abstract method or declare
itself as abstract.

Note: Eventually, a descendant class has to implement the abstract method; otherwise, you
would have a hierarchy of abstract classes that cannot be instantiated.
Q 4. What is inheritance?

Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword- extends is the keyword used to inherit the properties of a class.
Below given is the syntax of extends keyword.
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}

Sample Code

Below given is an example demonstrating Java inheritance. In this example you can observe two
classes namely Calculation and My_Calculation.
Using extends keyword the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Copy and paste the program given below in a file with name My_Calculation.java
class Calculation{
int z;
public void addition(int x, int y){
z = x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x,int y){
z = x-y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation{


public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}
}

Compile and execute the above code as shown below


javac My_Calculation.java
java My_Calculation

o/pThe sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200

In the given program when an object to My_Calculation class is created, a copy of the contents
of the super class is made with in it. That is why, using the object of the subclass you can access
the members of a super class.

The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.

If you consider the above program you can instantiate the class as given below as well. But using
the superclass reference variable ( cal in this case ) you cannot call the method multiplication(),
which belongs to the subclass My_Calculation.
Calculation cal = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

Note A subclass inherits all the members (fields, methods, and nested classes) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
The super keyword

The super keyword is similar to this keyword following are the scenarios where the super
keyword is used.

It is used to differentiate the members of superclass from the members of subclass, if


they have same names.

It is used to invoke the superclass constructor from subclass.

Differentiating the members

If a class is inheriting the properties of another class. And if the members of the superclass have
the names same as the sub class, to differentiate these variables we use super keyword as shown
below.
super.variable
super.method();

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both have a
method named display() with different implementations, and a variable named num with
different values. We are invoking display() method of both classes and printing the value of the
variable num of both classes, here you can observe that we have used super keyword to
differentiate the members of super class from sub class.
Copy and paste the program in a file with name Sub_class.java.
class Super_class{
int num = 20;
//display method of superclass

public void display(){


System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
//display method of sub class
public void display(){
System.out.println("This is the display method of subclass");
}
public void my_method(){
//Instantiating subclass
Sub_class sub = new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+
sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+
super.num);
}
public static void main(String args[]){
Sub_class obj = new Sub_class();
obj.my_method();
}
}
javac Super_Demo
java Super

On executing the program you will get the following result


This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the super class. But if you want to call a parametrized constructor of the
super class, you need to use the super keyword as shown below.

super(values);

The program given in this section demonstrates how to use the super keyword to invoke the
parametrized constructor of the superclass. This program contains a super class and a sub class,
where the super class contains a parametrized constructor which accepts a string value, and we
used the super keyword to invoke the parametrized constructor of the super class.
Copy and paste the below given program in a file with name Subclass.java
class Superclass{
int age;
Superclass(int age){
this.age = age;
}
public void getAge(){
System.out.println("The value of the variable named age in super class
is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age){
super(age);
}
public static void main(String argd[]){
Subclass s = new Subclass(24);
s.getAge();
}
}

Compile and execute the above code using the following syntax.
javac Subclass
java Subclass

On executing the program you will get the following result


The value of the variable named age in super class is: 24

IS-A Relationship
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal{
}
public class Mammal extends Animal{
}

public class Reptile extends Animal{


}
public class Dog extends Mammal{
}

Now, based on the above example, In Object Oriented terms, the following are true

Animal is the superclass of Mammal class.

Animal is the superclass of Reptile class.

Mammal and Reptile are subclasses of Animal class.

Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say

Mammal IS-A Animal

Reptile IS-A Animal

Dog IS-A Mammal

Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example
class Animal{
}
class Mammal extends Animal{
}
class Reptile extends Animal{
}
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();

Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);

o/ptrue
true
true

Since we have a good understanding of the extends keyword let us look into how the
implements keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.

Example
public interface Animal {
}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
}

The instanceof Keyword

Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
class Mammal implements Animal{}
public class Dog extends Mammal{
public static void main(String args[]){
Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);

This would produce the following result:

true
true
true

HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class HASA certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to
put the entire code that belongs to speed inside the Van class., which makes it possible to reuse
the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
Types of inheritance

There are various types of inheritance as demonstrated below.

A very important fact to remember is that Java does not support multiple inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal
public class extends Animal, Mammal{}

Q What is method overloading and method overriding?

Method overloading -If a class have multiple methods by same name but different 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
behaviour of the method because its name differs. So, we perform method overloading to figure
out the program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments

2. By changing the data type


In java, Methood Overloading is not possible by changing the return type of the method.
1)Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
1. class Calculation{
2.

void sum(int a,int b){System.out.println(a+b);}

3.

void sum(int a,int b,int c){System.out.println(a+b+c);}

4.
5.

public static void main(String args[]){

6.

Calculation obj=new Calculation();

7.

obj.sum(10,10,10);

8.

obj.sum(20,20);

9.
10. }
11.}

Output:30
40

2)Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
1. class Calculation2{
2.

void sum(int a,int b){System.out.println(a+b);}

3.

void sum(double a,double b){System.out.println(a+b);}

4.
5.

public static void main(String args[]){

6.

Calculation2 obj=new Calculation2();

7.

obj.sum(10.5,10.5);

8.

obj.sum(20,20);

9.
10. }
11.}

Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return type
of method?

In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
1. class Calculation3{
2.

int sum(int a,int b){System.out.println(a+b);}

3.

double sum(int a,int b){System.out.println(a+b);}

4.
5.

public static void main(String args[]){

6.

Calculation3 obj=new Calculation3();

7.

int result=obj.sum(20,20); //Compile Time Error

8.
9.

10.}

int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:
1. class Overloading1{
2.

public static void main(int a){

3.

System.out.println(a);

4.

5.
6.

public static void main(String args[]){

7.

System.out.println("main() method invoked");

8.

main(10);

9.

10.}
Output:main() method invoked
10

Method overriding- If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.

In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding

Method overriding is used to provide specific implementation of a method


that is already provided by its super class.

Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.
1. class Vehicle{
2.

void run(){System.out.println("Vehicle is running");}

3. }
4. class Bike extends Vehicle{
5.
6.

public static void main(String args[]){

7.

Bike obj = new Bike();

8.

obj.run();

9.

10.}
Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but
it has some specific implementation. The name and parameter of the method is same and there is
IS-A relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10.}
Output:Bike is running safely

Difference between
overriding in java

method

overloading

and

method

There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:
No
.

1)

Method Overloading

Method overloading is used to increase the


readability of the program.

Method Overriding
Method overriding is used to
provide the specific
implementation of the method
that is already provided by its
super class.

Method overriding occurs in two


2) Method overloading is performed within class. classes that have IS-A
(inheritance) relationship.

3)

In case of method overloading, parameter


must be different.

In case of method overriding,


parameter must be same.

Method overriding is the


Method overloading is the example of compile
4)
example of run time
time polymorphism.
polymorphism.
In java, method overloading can't be
performed by changing return type of the
Return type must be same or
5) method only. Return type can be same or
covariant in method overriding.
different in method overloading. But you must
have to change the parameter.

Java Method Overloading example


1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }

Java Method Overriding example


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
Q List down difference access specifiers available in java?

Access specifiers for classes or interfaces in Java


In Java, methods and data members of a class/interface can have one of the following four access
specifiers. The access specifiers are listed according to their restrictiveness order.

1) private
2) default (when no access specifier is specified)
3) protected
4) public

But, the classes and interfaces themselves can have only two access specifiers.

Public

default (when no access specifier is specified)

Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors. The four access levels are:

Visible to the package. the default. No modifiers are needed.

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Default Access Modifier - No keyword:


Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other class
in the same package. The fields in an interface are implicitly public static final and the methods
in an interface are by default public.
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.

Variables that are declared private can be accessed outside the class if public getter methods are
present in the class.
Using the private modifier is the main way that an object encapsulates itself and hide data from
the outside world.
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class
still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.
Example:

The following function uses public access control:


public static void main(String[] arguments) {
// ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java
interpreter (such as java) to run the class.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed
only by the subclasses in other package or any class within the package of the protected
members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be
declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
Q What is static and instance variable in java?

There are three kinds of variables in Java:

Local variables

Instance variables

Class/static variables

Local variables:

Local variables are declared in methods, constructors, or blocks.

Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.

Access modifiers cannot be used for local variables.

Local variables are visible only within the declared method, constructor or block.

Local variables are implemented at stack level internally.

There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.

Example:

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){

Test test = new Test();


test.pupAge();
}

This would produce the following result:


Puppy age is: 7

Instance variables:

Instance variables are declared in a class, but outside a method, constructor or any block.

When a space is allocated for an object in the heap, a slot for each instance variable value
is created.

Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.

Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.

Instance variables can be declared in class level before or after use.

Access modifiers can be given for instance variables.

The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However
visibility for subclasses can be given for these variables with the use of access modifiers.

Instance variables have default values. For numbers the default value is 0, for Booleans it
is false and for object references it is null. Values can be assigned during the declaration
or within the constructor.

Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) should be called using the fully qualified name .
ObjectReference.VariableName.

Example:
import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.


private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This would produce the following result:


name : Ransika
salary :1000.0

Class/static variables:

Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.

There would only be one copy of each class variable per class, regardless of how many
objects are created from it.

Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never
change from their initial value.

Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program
stops.

Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.

Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally values can be assigned in special
static initializer blocks.

Static variables can be accessed by calling with the class name


ClassName.VariableName.

Q What is package in java, importance of package.

Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.
Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Q What is interface? Difference between abstract class and interface.

Interface- An interface in java is a blueprint of a class. It has static constants and abstract
methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

It is used to achieve fully abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods.


A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviours of an object. And an interface contains behaviours that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

The byte code of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a


directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:

Below given is an example of an interface:


/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.

Methods in an interface are implicitly public.

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
Difference between abstract class and interface
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 and


non-abstract methods.

Interface can have only abstract


methods.

2) Abstract class doesn't support


multiple inheritance.

Interface supports multiple


inheritance.

3) Abstract class can have final, nonfinal, static and non-static variables.

Interface has only static and final


variables.

4) Abstract class can have static


methods, main method and
constructor.

Interface can't have static methods,


main method or constructor.

5) Abstract class can provide the


implementation of interface.

Interface can't provide the


implementation of abstract class.

6) The abstract keyword is used to


declare abstract class.

The interface keyword is used to


declare interface.

7) Example:
public abstract class Shape{
public abstract void draw();
}

Example:
public interface Drawable{
void draw();
}

Q Why multiple inheritance not supported in terms of class but its


supported in terms of Interface?

Q What is abstract class and concrete class?


Abstract Classes and Concrete Classes

1.1 In Java an abstract class is one that does not provide implementations for all its methods. A
class must be declared abstract if any of the methods in that class are abstract.
1.2 An abstract class is meant to be used as the base class from which other classes
are derived. The derived class is expected to provide implementations for the
methods that are not implemented in the base class. A derived class that
implements all the missing functionality is called a concrete class .
2 .1 A concrete class has concrete methods, i.e., with code and other functionality.
This class a may extend an abstract class or implements an interface.
2.2 An abstract class must contain at least one abstract method with zero or more
concrete methods
What is final,finally and finalization in java?

No.

final
Final is used to apply restrictions on
class, method and variable. Final class
1) can't be inherited, final method can't be
overridden and final variable value can't
be changed.
2) Final is a keyword.

finally
Finally is used to place
important code, it will be
executed whether
exception is handled or
not.
Finally is a block.

finalize
Finalize is used to
perform clean up
processing just before
object is garbage
collected.
Finalize is a method.

Java final example

1. class FinalExample{
2. public static void main(String[] args){
3. final int x=100;
4. x=200;//Compile Time Error
5. }}
Java finally example

1. class FinallyExample{
2. public static void main(String[] args){
3. try{
4. int x=300;
5. }catch(Exception e){System.out.println(e);}
6. finally{System.out.println("finally block is executed");}
7. }}
Java finalize example

1. class FinalizeExample{
2. public void finalize(){System.out.println("finalize called");}
3. public static void main(String[] args){
4. FinalizeExample f1=new FinalizeExample();
5. FinalizeExample f2=new FinalizeExample();
6. f1=null;
7. f2=null;
8. System.gc();

9. }}
Q What is Exception handling in java, how to achieve it.

The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and
unchecked exceptions.
What is exception

Dictionary Meaning: Exception is an abnormal condition.


In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Hierarchy of Java Exception classes

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.


1. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

Java try block


Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw exception
3. }finally{}

Java catch block


Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.


1. public class Testtrycatch1{
2.

public static void main(String args[]){

3.

int data=50/0;//may throw exception

4.

System.out.println("rest of the code...");

5. }
6. }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Solution by exception handling

Let's see the solution of above problem by java try-catch block.


1. public class Testtrycatch2{
2.
3.
4.

public static void main(String args[]){


try{
int data=50/0;

5.

}catch(ArithmeticException e){System.out.println(e);}

6.

System.out.println("rest of the code...");

7. }
8. }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Let's see a simple example of java multi-catch block.
1. public class TestMultipleCatchBlock{
2.

public static void main(String args[]){

3.

try{

4.

int a[]=new int[5];

5.

a[5]=30/0;

6.

7.

catch(ArithmeticException e){System.out.println("task1 is completed");}

8.

catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 com


pleted");}

9.

catch(Exception e){System.out.println("common task completed");}

10.
11.

System.out.println("rest of the code...");

12. }
13.}
Output:task1 completed
rest of the code..

Java Nested try block

The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
1. ....
2. try
3. {
4.

statement 1;

5.

statement 2;

6.

try

7.

8.

statement 1;

9.

statement 2;

10.

11.

catch(Exception e)

12.

13.

14.

15.

catch(Exception e)

16.

17.

18.

....

Java nested try example


Let's see a simple example of java nested try block.
1. class Excep6{
2. public static void main(String args[]){

3.
4.

try{
try{

5.

System.out.println("going to divide");

6.

int b =39/0;

7.

}catch(ArithmeticException e){System.out.println(e);}

8.
9.

try{

10.

int a[]=new int[5];

11.

a[5]=4;

12.
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
13.
14.
15.

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

16.
17.
18.
19.

System.out.println("normal flow..");
}
}

Java finally block


Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.

Note: If you don't handle exception, before terminating the


program, JVM executes finally block(if any).
Q Why use java finally

Finally block in java can be used to put "cleanup" code such as closing
a file, closing connection etc.

Usage of Java finally


Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2.

public static void main(String args[]){

3.

try{

4.

int data=25/5;

5.

System.out.println(data);

6.

7.

catch(NullPointerException e){System.out.println(e);}

8.

finally{System.out.println("finally block is always executed");}

9.

System.out.println("rest of the code...");

10.

11.

Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2.

public static void main(String args[]){

3.

try{

4.

int data=25/0;

5.

System.out.println(data);

6.

7.

catch(NullPointerException e){System.out.println(e);}

8.

finally{System.out.println("finally block is always executed");}

9.

System.out.println("rest of the code...");

10.
11.

}
}

Output:finally block is always executed


Exception in thread main java.lang.ArithmeticException:/
by zero

Q How to create our own exception?


Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception.
1. class InvalidAgeException extends Exception{
2. InvalidAgeException(String s){
3.

super(s);

4. }
5. }
1. class TestCustomException1{
2.
3.
4.

static void validate(int age)throws InvalidAgeException{


if(age<18)

5.
6.

throw new InvalidAgeException("not valid");


else

7.
8.

System.out.println("welcome to vote");
}

9.
10.

public static void main(String args[]){

11.

try{

12.

validate(13);

13.
"+m);}

}catch(Exception m){System.out.println("Exception occured:

14.
15.
16.
17.

System.out.println("rest of the code...");


}
}

Output:Exception occured: InvalidAgeException:not valid


rest of the code...
Q Difference between throw and throws.
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No
.

throw

throws

1)

Java throw keyword is used to


explicitly throw an exception.

Java throws keyword is used to


declare an exception.

2)

Checked exception cannot be


propagated using throw only.

Checked exception can be


propagated with throws.

3) Throw is followed by an instance.

Throws is followed by class.

4) Throw is used within the method.

Throws is used with the method


signature.

5)

You cannot throw multiple


exceptions.

You can declare multiple exceptions


e.g.
public void method()throws
IOException,SQLException.

Java throw example


1. void m(){
2. throw new ArithmeticException("sorry");
3. }

Java throws example


1. void m()throws ArithmeticException{
2. //method code
3. }
Java throw and throws example
1. void m()throws ArithmeticException{
2. throw new ArithmeticException("sorry");
3. }
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to postpone
the handling of a checked exception and throw is used to invoke an exception explicitly.
Q What is String, Stringbuffer and StringBuilder?
Java String provides a lot of concepts that can be performed on a string
such as compare, concat, equals, split, length, replace, compareTo, intern,
substring etc.
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create String object:
1. By string literal- String s="welcome";
1. By new keyword : String s =
new String("Welcome");//creates two objects and one reference variable
No.

String

1) String class is immutable.

StringBuffer
StringBuffer class is mutable.

String is slow and consumes more memory when


2) you concat too many strings because every time it
creates new instance.
String class overrides the equals() method of Object
3) class. So you can compare the contents of two
strings by equals() method.
No.

StringBuffer
StringBuffer is synchronized i.e. thread safe.
1) It means two threads can't call the methods
of StringBuffer simultaneously.
StringBuffer is less efficient than
2)
StringBuilder.

StringBuffer is fast and consumes less


memory when you concat strings.
StringBuffer class doesn't override the
equals() method of Object class.

StringBuilder
StringBuilder is non-synchronized i.e. not
thread safe. It means two threads can call the
methods of StringBuilder simultaneously.
StringBuilder is more efficient than
StringBuffer.

1) StringBuffer append() method


The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello

6. }
7. }
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){

3. StringBuffer sb=new StringBuffer("Hello");


4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2
)+2
9. }
10.

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");

4. sb.append("Java");//now original string is changed


5. System.out.println(sb);//prints Hello Java
6. }
7. }
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is
16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){

3. StringBuilder sb=new StringBuilder();


4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2
)+2
9. }
10.

Q Why String is immutable in java?


In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1 class Testimmutablestring{
2

public static void main(String args[]){

String s="Sachin";

s.concat(" Tendulkar");//concat() method appends the string at the en


d

5
6

System.out.println(s);//will print Sachin because strings are immutabl


e objects
}

7 }
Output:Sachin
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
1 class Testimmutablestring1{
2

public static void main(String args[]){

String s="Sachin";

s=s.concat(" Tendulkar");

System.out.println(s);

7 }
Output:Sachin Tendulkar
Reason- Because java uses the concept of string literal.Suppose there are 5
reference variables,all referes to one object "sachin".If one reference variable
changes the value of the object, it will be affected to all the reference
variables. That is why string objects are immutable in java.
Q Difference between == and .equals in java.
Before discussing the difference between == and the equals() method, its important to
understand that an object has both a location in memory and a specific state depending on the
values that are inside the object.
The == operator
In Java, when the == operator is used to compare 2 objects, it checks to see if the objects refer
to the same place in memory. In other words, it checks to see if the 2 object names are basically
references to the same memory location. A very simple example will help clarify this:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
System.out.println("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");

Take a guess at what the code above will output. Did you guess that it will output obj1==obj2 is
TRUE? Well, if you did, then you are actually wrong. Even though the strings have the same
exact characters (xyz), The code above will actually output:
obj1==obj2 is FALSE
The == operator compares the objects location(s) in memory
Are you confused? Well, let us explain further: as we mentioned earlier, the == operator is
actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory
location. In other words, if both obj1 and obj2 are just different names for the same object then
the == operator will return true when comparing the 2 objects. Another example will help
clarify this:
String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;
if(obj1 == obj2)
System.out.printlln("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
Note in the code above that obj2 and obj1 both reference the same place in memory because of
this line: String obj2 = obj1;. And because the == compares the memory reference for each
object, it will return true. And, the output of the code above will be:
obj1==obj2 is TRUE
The equals() method
Now that weve gone over the == operator, lets discuss the equals() method and how that
compares to the == operator. The equals method is defined in the Object class, from which
every class is either a direct or indirect descendant. By default, the equals() method actually
behaves the same as the == operator meaning it checks to see if both objects reference the
same place in memory. But, the equals method is actually meant to compare the contents of 2
objects, and not their location in memory.

So, how is that behavior actually accomplished? Simple the equals class is overridden to get
the desired functionality whereby the object contents are compared instead of the object
locations. This is the Java best practice for overriding the equals method you should compare
the values inside the object to determine equality. What value you compare is pretty much up to
you. This is important to understand so we will repeat it: by default equals() will behave the
same as the == operator and compare object locations. But, when overriding the equals()
method, you should compare the values of the object instead.
An example of the equals() method being overriden
The Java String class actually overrides the default equals() implementation in the Object class
and it overrides the method so that it checks only the values of the strings, not their locations in
memory. This means that if you call the equals() method to compare 2 String objects, then as
long as the actual sequence of characters is equal, both objects are considered equal. Here is an
example that will help clarify this:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
System.out.printlln("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");
This code will output the following:
obj1==obj2 is TRUE
New ans- As we discussed, Javas String class overrides the equals() method to compare the
characters in a string. This means that the comparison between the 2 String objects returns true
since they both hold the string xyz. It should now be clear what the difference is between the
equals() method and the == operator.
The == (double equals) returns true, if the variable reference points to the same object in
memory. This is called shallow comparison.
The equals() method calls the user implemented equals() method, which compares the object
attribute values. The equals() method provides deep comparison by checking if two objects are
logically equal as opposed to the shallow comparison provided by the operator ==.
If equals() method does not exist in a user supplied class then the inherited Object class's
equals() method will be called which evaluates if the references point to the same object in
memory. In this case, the object.equals() works just like the "==" operator.

Q What are differenrt collections provided by java.


Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Q What is Collection in java
Collection represents a single unit of objects i.e. a group.
What is framework in java

provides readymade architecture.

represents set of classes and interface.

is optional.

Q What is Collection framework


Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
Q What is list,set,map in collection and how they differs from each
other.
1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted
into the list without affecting the same existing values and their indexes.
Set doesnt allow duplicates. Set and all of the classes which implements Set interface should
have unique elements.
Map stored the elements as key & value pair. Map doesnt allow duplicate keys while it allows
duplicate values.

2) Null values: List allows any number of null values.


Set allows single null value at most.
Map can have single null key at most and any number of null values.
3) Order: List and all of its implementation classes maintains the insertion order.
Set doesnt maintain any order; still few of its classes sort the elements in an order such as
LinkedHashSet maintains the elements in insertion order.
Similar to Set Map also doesnt stores the elements in an order, however few of its classes does
the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap
sorts the elements in the insertion order, the order in which the elements got added to the
LinkedHashMap.
4) Commonly used classes:
List: ArrayList, LinkedList etc.
Set: HashSet, LinkedHashSet, TreeSet, SortedSet etc.
Map: HashMap, TreeMap, WeakHashMap, LinkedHashMap, IdentityHashMap etc.
Q When to use List, Set and Map in Java?
1) If you do not want to have duplicate values in the database then Set should be your first choice
as all of its classes do not allow duplicates.
2) If there is a need of frequent search operations based on the index values then List (ArrayList)
is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a preferred collection
interface.
4) If the requirement is to have the key & value mappings in the database then Map is your best
bet.
List Vs Set
List and Set both are interfaces. They both extends Collection interface. In this post we are
discussing the differences between List and Set interfaces in java.
1) List is an ordered collection it maintains the insertion order, which means upon displaying the
list content it will display the elements in the same order in which they got inserted into the list.
Set is an unordered collection, it doesnt maintain any order. There are few implementations of
Set which maintains the order such as LinkedHashSet (It maintains the elements in insertion
order).

2) List allows duplicates while Set doesnt allow duplicate elements. All the elements of a Set
should be unique if you try to insert the duplicate element in Set it would replace the existing
value.
3) List implementations: ArrayList, LinkedList etc.
Set implementations: HashSet, LinkedHashSet, TreeSet etc.
4) List allows any number of null values. Set can have only a single null value at most.
5) ListIterator can be used to traverse a List in both the directions(forward and backward)
However it can not be used to traverse a Set. We can use Iterator (It works with List too) to
traverse a Set.
6) List interface has one legacy class called Vector whereas Set interface does not have any
legacy class.
When to use Set and When to use List?
The usage is purely depends on the requirement:
If the requirement is to have only unique values then Set is your best bet as any implementation
of Set maintains unique values only.
If there is a need to maintain the insertion order irrespective of the duplicity then List is a best
option. Both the implementations of List interface ArrayList and LinkedList sorts the elements
in their insertion order.
List Example
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListExample {
public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("Chaitanya");
al.add("Rahul");
al.add("Ajeet");
System.out.println("ArrayList Elements: ");
System.out.print(al);
List<String> ll = new LinkedList<String>();

ll.add("Kevin");
ll.add("Peter");
ll.add("Kate");
System.out.println("\nLinkedList Elements: ");
System.out.print(ll);
}
}
Output:
ArrayList Elements:
[Chaitanya, Rahul, Ajeet]
LinkedList Elements:
[Kevin, Peter, Kate]
Set Example
import java.util.Set;
import java.util.HashSet;
import java.util.TreeSet;
public class SetExample {
public static void main(String args[]) {
int count[] = {11, 22, 33, 44, 55};
Set<Integer> hset = new HashSet<Integer>();
try{
for(int i = 0; i<4; i++){
hset.add(count[i]);
}
System.out.println(hset);
TreeSet<Integer> treeset = new TreeSet<Integer>(hset);
System.out.println("The sorted list is:");
System.out.println(treeset);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Output:
[33, 22, 11, 44]
The sorted list is:
[11, 22, 33, 44]
Q How to iterate over list, map in java.

There are four ways to loop ArrayList:


1. For Loop
2. Advanced for loop
3. While Loop
4. Iterator
Lets have a look at the below example I have used all of the mentioned methods for iterating
list.
import java.util.*;
public class LoopExample {
public static void main(String[] args) {
ArrayList<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(14);
arrlist.add(7);
arrlist.add(39);
arrlist.add(40);
/* For Loop for iterating ArrayList */
System.out.println("For Loop");
for (int counter = 0; counter < arrlist.size(); counter++)
{
System.out.println(arrlist.get(counter));
}
/* Advanced For Loop*/
System.out.println("Advanced For Loop");
for (Integer num : arrlist) {
System.out.println(num);
}
/* While Loop for iterating ArrayList*/
System.out.println("While Loop");
int count = 0;
while (arrlist.size() > count) {
System.out.println(arrlist.get(count));
count++;
}
/*Looping Array List using Iterator*/
System.out.println("Iterator");

Iterator iter = arrlist.iterator();


while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
Output:
For Loop
14
7
39
40
Advanced For Loop
14
7
39
40
While Loop
14
7
39
40
Iterator
14
7
39
40
In the last tutorial we discussed LinkedList and its methods with example. Here we will see how
to loop/iterate a LinkedList. There are four ways in which a LinkedList can be iterated
1. For loop
2. Advanced For loop
3. Iterator
4. While Loop

Example:
In this example we have a LinkedList of String Type and we are looping through it using all the
four mentioned methods.
package beginnersbook.com;
import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {
/*LinkedList declaration*/
LinkedList<String> linkedlist=new LinkedList<String>();
linkedlist.add("Apple");
linkedlist.add("Orange");
linkedlist.add("Mango");
/*for loop*/
System.out.println("**For loop**");
for(int num=0; num<linkedlist.size(); num++)
{
System.out.println(linkedlist.get(num));
}
/*Advanced for loop*/
System.out.println("**Advanced For loop**");
for(String str: linkedlist)
{
System.out.println(str);
}
/*Using Iterator*/
System.out.println("**Iterator**");
Iterator i = linkedlist.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
/* Using While Loop*/
System.out.println("**While Loop**");
int num = 0;
while (linkedlist.size() > num) {
System.out.println(linkedlist.get(num));
num++;
}
}

}
Output:
**For loop**
Apple
Orange
Mango
**Advanced For loop**
Apple
Orange
Mango
**Iterator**
Apple
Orange
Mango
**While Loop**
Apple
Orange
Mango
Q Difference between hashmap and hashtable.
HashMap and Hashtable both classes implements java.util.Map interface, however there are
differences in the way they work and their usage.
HashMap vs Hashtable
1) HashMap is non-synchronized. This means if its used in multithread environment then more
than one thread can access and process the HashMap simultaneously.
Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a
given moment of time. The thread which works on Hashtable acquires a lock on it to make the
other threads wait till its work gets completed.
2) HashMap allows one null key and any number of null values.
Hashtable doesnt allow null keys and null values.
3) HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts
the mappings based on the ascending order of keys.
Hashtable doesnt guarantee any kind of order. It doesnt maintain the mappings in any particular
order.

4) Initially Hashtable was not the part of collection framework it has been made a collection
framework member later after being retrofitted to implement the Map interface.
HashMap implements Map interface and is a part of collection framework since the beginning.
5) Another difference between these classes is that the Iterator of the HashMap is a fail-fast and it
throws ConcurrentModificationException if any other Thread modifies the map structurally by
adding or removing any element except iterators own remove() method. In Simple words failfast means: When calling iterator.next(), if any modification has been made between the moment
the iterator was created and the moment next() is called, a ConcurrentModificationException is
immediately thrown.
Enumerator for the Hashtable is not fail-fast.
For e.g.
HashMap:
HashMap hm= new HashMap();
....
....
Set keys = hm.keySet();
for (Object key : keys) {
//it will throw the ConcurrentModificationException here
hm.put(object & value pair here);
}
Hashtable:
Hashtable ht= new Hashtable();
....
.....
Enumeration keys = ht.keys();
for (Enumeration en = ht.elements() ; en.hasMoreElements() ;
en.nextElement()) {
//No exception would be thrown here
ht.put(key & value pair here);
}
Q When to use HashMap and Hashtable?
1) As stated above the main difference between HashMap & Hashtable is synchronization. If
there is a need of thread-safe operation then Hashtable can be used as all its methods are
synchronized but its a legacy class and should be avoided as there is nothing about it, which
cannot be done by HashMap. For multi-thread environment I would recommend you to use

ConcurrentHashMap (Almost similar to Hashtable) or even you can make the HashMap
synchronized explicitly (Read here..).
2) Synchronized operation gives poor performance so it should be avoided until unless required.
Hence for non-thread environment HashMap should be used without any doubt.
List Down some methods used in collection and iterator.
There are many methods declared in the Collection interface. They are as follows:
No
.

Method

Description

public boolean add(Object


is used to insert an element in this collection.
element)

public boolean
addAll(Collection c)

is used to insert the specified collection


elements in the invoking collection.

public boolean
remove(Object element)

is used to delete an element from this


collection.

public boolean
removeAll(Collection c)

is used to delete all the elements of specified


collection from the invoking collection.

public boolean
retainAll(Collection c)

is used to delete all the elements of invoking


collection except the specified collection.

public int size()

return the total number of elements in the


collection.

public void clear()

removes the total no of element from the


collection.

public boolean
contains(Object element)

is used to search an element.

public boolean
containsAll(Collection c)

is used to search the specified collection in


this collection.

10 public Iterator iterator()

returns an iterator.

11 public Object[] toArray()

converts collection into array.

12 public boolean isEmpty()

checks if collection is empty.

13

public boolean
equals(Object element)

14 public int hashCode()

matches two collection.


returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward
direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more
elements.
2. public object next() it returns the element and moves the cursor
pointer to the next element.
3. public void remove() it removes the last elements returned by the
iterator. It is rarely used.
What is comparable and Comparator and where it is used.
Comparable interface
Comparable interface is used to order the objects of user-defined class.This interface is found in
java.lang package and contains only one method named compareTo(Object).It provide only
single sorting sequence i.e. you can sort the elements on based on single datamember only.For
instance it may be either rollno,name,age or anything else.
Syntax:
public int compareTo(Object obj): is used to compare the current object
with the specified object.
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects

Collections class provides static methods for sorting the elements of


collection.If collection elements are of Set type, we can use TreeSet.But We
cannot sort the elements of List.Collections class provides methods for
sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List.List
elements must be of Comparable type.
Example of Sorting the elements of List that contains user-defined
class objects on age basis
Student.java
1. class Student implements Comparable{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11.

public int compareTo(Object obj){

12.

Student st=(Student)obj;

13.

if(age==st.age)

14.

return 0;

15.

else if(age>st.age)

16.

return 1;

17.

else

18.

return -1;

19.

20.
21.

Simple.java
1. import java.util.*;
2. import java.io.*;
3.
4. class TestSort3{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10.

al.add(new Student(105,"Jai",21));

11.
12.

Collections.sort(al);

13.

Iterator itr=al.iterator();

14.

while(itr.hasNext()){

15.

Student st=(Student)itr.next();

16.

System.out.println(st.rollno+""+st.name+""+st.age);

17.

18.

19.

Output:105 Jai 21
101 Vijay 23
106 Ajay 27
Comparator interface
Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements based on any data member.
For instance it may be on rollno, name, age or anything else.
Syntax of compare method
public int compare(Object obj1,Object obj2): compares the first object with second object.
Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set type, we can use TreeSet. But We cannot sort the elements of List.
Collections class provides methods for sorting the elements of List type elements.
Method of Collections class for sorting List elements
public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.
Example of sorting the elements of List that contains user-defined
class objects on the basis of age and name
In this example, we have created 4 java classes:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java

Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.

AgeComparator.java
This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;

9. else if(s1.age>s2.age)
10.

return 1;

11.

else

12.

return -1;

13.

14.

NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int Compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{

5. public static void main(String args[]){


6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10.

al.add(new Student(105,"Jai",21));

11.
12.

System.out.println("Sorting by Name...");

13.
14.

Collections.sort(al,new NameComparator());

15.

Iterator itr=al.iterator();

16.

while(itr.hasNext()){

17.

Student st=(Student)itr.next();

18.

System.out.println(st.rollno+" "+st.name+" "+st.age);

19.

20.
21.

System.out.println("sorting by age...");

22.
23.

Collections.sort(al,new AgeComparator());

24.

Iterator itr2=al.iterator();

25.

while(itr2.hasNext()){

26.

Student st=(Student)itr2.next();

27.

System.out.println(st.rollno+" "+st.name+" "+st.age);

28.

29.
30.
31.

32.

Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Comparable
1) Comparable provides single sorting
sequence. In other words, we can sort the
collection on the basis of single element
such as id or name or price etc.
2) Comparable affects the original class
i.e. actual class is modified.
3) Comparable provides compareTo()
method to sort elements.
4) Comparable is found in java.lang
package.
5) We can sort the list elements of
Comparable type by
Collections.sort(List) method.

Comparator
Comparator provides multiple sorting sequence. In
other words, we can sort the collection on the basis of
multiple elements such as id, name and price etc.
Comparator doesn't affect the original class i.e.
actual class is not modified.
Comparator provides compare() method to sort
elements.
Comparator is found in java.util package.
We can sort the list elements of Comparator type by
Collections.sort(List,Comparator) method.

Q What is generics ? significance of generics.

Q What is multithreading in java?


Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
How to create thread in java?
How to create thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
Commonly used Constructors of Thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently
executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the
thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the
thread.
10.
public Thread currentThread(): returns the reference of
currently executing thread.
11.

public int getId(): returns the id of the thread.

12.
public Thread.State getState(): returns the state of the
thread.
13.

public boolean isAlive(): tests if the thread is alive.

14.
public void yield(): causes the currently executing thread
object to temporarily pause and allow other threads to execute.
15.
public void suspend(): is used to suspend the
thread(depricated).
16.
public void resume(): is used to resume the suspended
thread(depricated).

17.

public void stop(): is used to stop the thread(depricated).

18.
public boolean isDaemon(): tests if the thread is a daemon
thread.
19.
public void setDaemon(boolean b): marks the thread as
daemon or user thread.
20.

public void interrupt(): interrupts the thread.

21.
public boolean isInterrupted(): tests if the thread has been
interrupted.
22.
public static boolean interrupted(): tests if the current
thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

1. public void run(): is used to perform action for a thread.


Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:

A new thread starts(with new callstack).

The thread moves from New state to the Runnable state.

When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:


1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }

5. public static void main(String args[]){


6. Multi t1=new Multi();
7. t1.start();
8.

9. }
Output:thread is running...

2)By implementing the Runnable interface:


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11.}
Output:thread is running...

What is sleep method?

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:

public static void sleep(long miliseconds)throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java


1. class TestSleepMethod1 extends Thread{
2.

public void run(){

3.

for(int i=1;i<5;i++){

4.

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}

5.

System.out.println(i);

6.

7.

8.

public static void main(String args[]){

9.

TestSleepMethod1 t1=new TestSleepMethod1();

10. TestSleepMethod1 t2=new TestSleepMethod1();


11.
12. t1.start();
13. t2.start();
14. }
15. }
Output:
1
1
2
2
3
3
4
4

Q Lifecycle of thread in java?

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

Q Difference between sleep and wait method?

sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable"
state for specified amount of time. During this time, the thread keeps the lock (monitors) it has
acquired. wait(): It is a method on Object class. It makes the current thread into the "Not
Runnable" state. Wait is called on a object, not a thread. Before calling wait() method, the object

should be synchronized, means the object should be inside synchronized block. The call to wait()
releases the acquired lock.
wait()
sleep()
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) wait() method releases the lock.
The sleep() method doesn't releases the lock.
Q What is wait,notify and notifyall?

wait() tell the thread to give up the moniter and go to sleep state until another thread will enter
the moniter and cal notiy() or notifyAall()
public final void wait(long timeout)
notify(): it wakes up the thread that called wait() on the same object.
public final void notify()
notifyAll() : wakes up all the threads that are waiting for this object .
public final void notifyAll()

Q What is join method in multithreading?

The join() method:


The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
1. class TestJoinMethod1 extends Thread{
2.
3.
4.
5.

public void run(){


for(int i=1;i<=5;i++){
try{
Thread.sleep(500);

6.

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

7.

System.out.println(i);

8.

9.

10.public static void main(String args[]){


11. TestJoinMethod1 t1=new TestJoinMethod1();
12. TestJoinMethod1 t2=new TestJoinMethod1();
13. TestJoinMethod1 t3=new TestJoinMethod1();
14. t1.start();
15. try{
16. t1.join();
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }
22.}

Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

As you can see in the above example,when t1 completes its task then t2 and t3
starts executing.
Example of join(long miliseconds) method
1. class TestJoinMethod2 extends Thread{
2.
3.

public void run(){


for(int i=1;i<=5;i++){

4.

try{

5.

Thread.sleep(500);

6.

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

7.

System.out.println(i);

8.

9.

10.public static void main(String args[]){


11. TestJoinMethod2 t1=new TestJoinMethod2();
12. TestJoinMethod2 t2=new TestJoinMethod2();
13. TestJoinMethod2 t3=new TestJoinMethod2();
14. t1.start();
15. try{
16. t1.join(1500);
17. }catch(Exception e){System.out.println(e);}
18.
19. t2.start();
20. t3.start();
21. }

22.}

Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5

In the above example,when t1 is completes its task for 1500 miliseconds(3 times)
then t2 and t3 starts executing.
Q What is synchronization in multithreading? How to achieve it.

Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Why use Synchronization

The synchronization is mainly used to


1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization

There are two types of synchronization


1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.


Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
1. //example of java synchronized method
2. class Table{
3.
4.

synchronized void printTable(int n){//synchronized method


for(int i=1;i<=5;i++){

5.

System.out.println(n*i);

6.

try{

7.
8.

Thread.sleep(400);
}catch(Exception e){System.out.println(e);}

9.

10.
11. }
12.}
13.
14.class MyThread1 extends Thread{
15.Table t;
16.MyThread1(Table t){
17.this.t=t;
18.}
19.public void run(){
20.t.printTable(5);
21.}
22.
23.}
24.class MyThread2 extends Thread{
25.Table t;
26.MyThread2(Table t){
27.this.t=t;
28.}
29.public void run(){
30.t.printTable(100);
31.}
32.}

33.
34.public class TestSynchronization2{
35.public static void main(String args[]){
36.Table obj = new Table();//only one object
37.MyThread1 t1=new MyThread1(obj);
38.MyThread2 t2=new MyThread2(obj);
39.t1.start();
40.t2.start();
41.}
42.}
Output: 5
10
15
20
25
100
200
300
400
500

What is serialization in java?

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marsha

Importance of serial version uid in serialization?

Servlet & Jsp (9 questions)


What is servlet, lifecycle of servlet?

Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
Servlet technology is robust and scalable because of java language.

What is a Servlet?

Servlet is a technology i.e. used to create web application.

Servlet is an API that provides many interfaces and classes including documentations.

Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.

Servlet is a web component that is deployed on the server to create dynamic web page.

What is web application?

A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter etc. and other components such as HTML. The web
components typically execute in Web Server and respond to HTTP request.
The basic benefits of servlet are as follows:
1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage
collection etc.
4. Secure: because it uses java language..
LIFE CYCLE OF SERVLET-

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. 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.
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:
1. public void destroy()

Difference between doGet and doPost?

- When you use GET, the entire form submission gets encapsulated in one URL. The query
length is limited to 260 characters, not secure, faster, quick and easy.
- When you use POST your name/value pairs inside the body of the HTTP request, which makes
a cleaner URL. It imposes no size limitations on the form's output. It is used to send a large
amount of data to the server to be processed. It is comparatively more versatile and secure.
When should you prefer to use doGet() over doPost()?GET is preferred over POST in most of
the situations except for the following:
- When the data is sensitive.
- When the data is greater than 1024 characters.
What is the difference between Get and Post?

There are many differences between the Get and Post request. Let's see these differences:
GET
1) In case of Get request, only limited
amount of data can be sent because
data is sent in header.

POST
In case of post request, large amount
of data can be sent because data is
sent in body.

2) Get request is not secured because


data is exposed in URL bar.

Post request is secured because data is


not exposed in URL bar.

3) Get request can be bookmarked

Post request cannot be bookmarked

4) Get request is idempotent. It means


second request will be ignored until
response of first request is delivered.

Post request is non-idempotent

5) Get request is more efficient and used Post request is less efficient and used
more than Post
less than get.

Q What is servletFilter, how to configure it?

A filter is an object that is invoked at the preprocessing and postprocessing of a request.


It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption
and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the
entry of filter from the web.xml file, filter will be removed automatically and we don't need to
change the servlet. So maintenance cost will be less.

Usage of Filter

recording all incoming requests

logs the IP addresses of the computers from which the requests originate

conversion

data compression

encryption and decryption

input validation etc.

Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Filter API

Like servlet filter have its own API. The javax.servlet package contains the three interfaces of
Filter API.
1. Filter
2. FilterChain
3. FilterConfig

Configuring the Servlet Filter in web.xml


You need to configure the servlet filter in the web.xml file of your web application, before it
works. Here is how you do that:
<filter>
<filter-name>myFilter</filter-name>
<filter-class>servlets.SimpleServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>*.simple</url-pattern>
</filter-mapping>

With this configuration all requests with URL's ending in .simple will be intercepted by the
servlet filter. All others will be left untouched.
Q List Down different tags of jsp.

In JSP tags can be divided into 4 different types. These are:


Directives: In the directives we can import packages, define error handling pages or the session
information of the JSP page.
Declarations: This tag is used for defining the functions and variables to be used in the JSP.
Scriplets: In this tag we can insert any amount of valid java code and these codes are placed in

_jspService method by the JSP engine.


Expressions: We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
Now we will examine each tags in details with examples.
Lifecycle of Jsp.

The JSP pages follows these phases:

Translation of JSP Page

Compilation of JSP Page

Classloading (class file is loaded by the classloader)

Instantiation (Object of the Generated Servlet is created).

Initialization ( jspInit() method is invoked by the container).

Reqeust processing ( _jspService() method is invoked by the container).

Destroy ( jspDestroy() method is invoked by the container).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into servlet by the help of JSP translator.
The JSP translator is a part of webserver that is responsible to translate the JSP page into servlet.
Afterthat Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happens in servlet is performed on JSP later like initialization,
committing response to the browser and destroy.
Q Lifecycle of JSP

A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle consists of following steps.
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method
Q What are different directives available in jsp.

The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
Syntax of JSP Directive
1. <%@ directive attribute="value" %>

There are three types of directives:

page directive

include directive

taglib directive

JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


1. <%@ page attribute="value" %>
Attributes of JSP page directive

import

contentType

extends

info

buffer

language

isELIgnored

isThreadSafe

autoFlush

session

pageEncoding

errorPage

isErrorPage

Jsp Include Directive


The include directive is used to include the contents of any resource it may be jsp file, html file
or text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static
resource).
Advantage of Include directive

Code Reusability
Syntax of include directive
1. <%@ include file="resourceName" %>

Example of include directive

In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>

JSP Taglib directive


The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD
(Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it
will be better to learn it in custom tag.
Syntax JSP Taglib directive
1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example of JSP Taglib directive

In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.

6. <mytag:currentDate/>
7.
8. </body>
9. </html>

Q What are Jsp Actions.

There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
JSP Action Tags

Description

jsp:forward

forwards the request and response to another resource.

jsp:include

includes another resource.

jsp:useBean

creates or locates bean object.

jsp:setProperty

sets the value of property in bean object.

jsp:getProperty

prints the value of property of the bean.

jsp:plugin

embeds another components such as applet.

jsp:param

sets the parameter value. It is used in forward and include mostly.

jsp:fallback

can be used to print the message if plugin is working. It is used in


jsp:plugin.

Action elements are basically predefined functions and there are following JSP actions available:
Syntax

Purpose

jsp:include

Includes a file at the time the page is requested

jsp:useBean

Finds or instantiates a JavaBean

jsp:setProperty

Sets the property of a JavaBean

jsp:getProperty

Inserts the property of a JavaBean into the output

jsp:forward

Forwards the requester to a new page

jsp:plugin

Generates browser-specific code that makes an OBJECT or

jsp:element

EMBED tag for the Java plugin


Defines XML elements dynamically.

jsp:attribute

Defines dynamically defined XML element's attribute.

jsp:body

Defines dynamically defined XML element's body.

jsp:text

Use to write template text in JSP pages and documents.

Difference between response.sendRedirect and forward.


Forward()

SendRediret()

When we use forward method request is


transfer to other resource within the same
server for further processing.

In case of sendRedirect request is transfer to


another resource to different domain or
different server for futher processing.

In case of forward Web container handle all


process internally and client or browser is not
involved.

When you use SendRedirect container


transfers the request to client or browser so
url given inside the sendRedirect method is
visible as a new request to the client.

When forward is called on requestdispather


object we pass request and response object
so our old request object is present on new
resource which is going to process our
request

In case of SendRedirect call old request and


response object is lost because its treated as
new request by the browser.

Visually we are not able to see the forwarded


address, its is transparent

In address bar we are able to see the new


redirected address its not transparent.

Using forward () method is faster then send


redirect.

SendRedirect is slower because one extra


round trip is required beasue completely new
request is created and old request object is
lost.Two browser request requird.

When we redirect using forward and we want


to use same data in new resource we can use
request.setAttribute () as we have request
object available.

But in sendRedirect if we want to use we have


to store the data in session or pass along with
the URL.

The sendRedirect() method of HttpServletResponse interface can be used to redirect response


to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.
There are many differences between the forward() method of RequestDispatcher and
sendRedirect() method of HttpServletResponse interface. They are given below:
forward() method
The forward() method works at server side.

sendRedirect() method
The sendRedirect() method works at
client side.

It sends the same request and response objects to another


It always sends a new request.
servlet.
It can be used within and outside the
It can work within the server only.
server.
Example:
Example:
request.getRequestDispacher("servlet2").forward(request
response.sendRedirect("servlet2");
,response);
Q Difference between include directive and include action

Advantages of JSP:
Following is the list of other advantages of using JSP over other technologies:

vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic
part is written in Java, not Visual Basic or other MS specific language, so it is more
powerful and easier to use. Second, it is portable to other operating systems and nonMicrosoft Web servers.

vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.

vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.

vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.

vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet

JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
Q Servlet Config and aServlet Context
ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet. This object can be
used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from
time to time.
Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information
is modified from the web.xml file.
Methods of ServletConfig interface
1. public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.

2. public Enumeration getInitParameterNames():Returns an enumeration


of all the initialization parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of
ServletContext.
ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This
object can be used to get configuration information from web.xml file. There is only one
ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using
the <context-param> element.
Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available
for all the servlet. We provide this information from the web.xml file, so if the information is
changed, we don't need to modify the servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:
1. The object of ServletContext provides an interface between the container and
servlet.
2. The ServletContext object can be used to get configuration information from
the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from
the web.xml file.
4. The ServletContext object can be used to provide inter-application
communication.

Commonly used methods of ServletContext interface


There is given some commonly used methods of ServletContext interface.
1. public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters.
3. public void setAttribute(String name,Object object):sets the given
object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the
specified name.
5. public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters as an Enumeration of String objects.

6. public void removeAttribute(String name):Removes the attribute with


the given name from the servlet context.

Q Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.

Types of Cookie

There are 2 types of cookies in servlets.


1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Struts (5 questions)
Q Advantages of struts framework.
The struts 2 framework is used to develop MVC (Model View Controller)-based
web application.

Advantages
1. Takes a lot of complexity out of building your own MVC framework.
2. Good design practice and modeling.
3. Easy to learn and use.
4. Feature rich, supported 3rd-party tools.
5. Flexible and extensible.
6. Large user community.
7. Stable and mature.
8. Open source.
Q What are the disadvantages of Struts 2 ?
A. The disadvantages of Struts 2 are given below:
Compatibility:Its difficult to move the applications from Struts 1 to Struts 2 because Struts 2 is totally different
from Struts1.
Limited Documentation:Due to the poorly managed documentation by Apache, new users find it difficult to understand
its concepts. As the documentation is limited also.
Less Transparent:- It is less transparent and hides the details that are internal which makes code
hard to understand.
List down components of struts framework.

five core components:

Actions

Interceptors

Value Stack / OGNL

Results / Result types

View technologies

Q Importance of struts.xml file


The struts.xml file contains the configuration information that you will be
modifying as actions are developed. This file can be used to override default
settings for an application, for example struts.devMode = false and other settings
which are defined in property file. This file can be created under the folder WEBINF/classes.
What is struts Action class.
- An Action class in the struts application is used to handle the request.
- It acts as interface or communication medium between the HTTP request coming
to it and business logic used to develop the application.
- Action class consists of RequestProcessor which act as controller. This controller
will choose the best action for each incoming request, generate the instance of that
action and execute that action.
- This should be in thread-safe manner, because RequestProcessor uses the same
instance for numbar of requests at same time.
Q What is interceptor in struts. List down some interceptors of struts
framework.
Interceptor is an object that is invoked at the preprocessing and postprocessing of a
request. In Struts 2, interceptor is used to perform operations such as validation,
exception handling, internationalization, displaying intermediate result etc.
Advantage of interceptors
Pluggable If we need to remove any concern such as validation, exception
handling, logging etc. from the application, we don't need to redeploy the
application. We only need to remove the entry from the struts.xml file
Q Struts 2 default interceptors

There are many interceptors provided by struts 2 framework. We have option to create our own
interceptors. The struts 2 default interceptors are as follows:

1) alias It converts similar parameters that have different names between requests.
2) autowiring
3) chain If it is used with chain result type, it makes the properties of previous action available in
the current action.
4) checkbox It is used to handle the check boxes in the form. By this, we can detect the
unchecked checkboxes.
5) cookie It adds a cookie to the current action.
6) conversionError It adds conversion errors to the action's field errors.
7) createSession It creates and HttpSession object if it doesn't exists.
8) clearSession It unbinds the HttpSession object.
9) debugging It provides support of debugging.
10) externalRef
11) execAndWait It sends an intermediate waiting page for the result.
12) exception It maps exception to a result.
13) fileUpload It provides support to file upload in struts 2.
14) i18n It provides support to internationalization and localization.
15) jsonValidation It provides support to asynchronous validation.
16) logger It outputs the action name.
17) store It stores and retrieves action messages, action errors or field errors for action that
implements ValidationAware interface.
18) modelDriven It makes other model object as the default object of valuestack.
19) scopedModelDriven It is similar to ModelDriven but works for action that implements
ScopedModelDriven.
20) params It populates the action properties with the request parameters.

21) actionMappingParams
22) prepare It performs preparation logic if action implements Preparable interface.
23) profiling It supports action profiling.
24) roles It supports role-based action.
25) scope It is used to store the action state in the session or application scope.
26) servletConfig It provides access to maps representing HttpServletRequest and
HttpServletResponse.
27) sessionAutowiring
28) staticParams It maps static properties to action properties.
29) timer It outputs the time needed to execute an action.
30) token It prevents duplication submission of request.
31) tokenSession It prevents duplication submission of request.
32) validation It provides support to input validation.
33) workflow It calls the validate method of action class if action class implements Validateable
interface.
34) annotationWorkflow
35) multiselect

Q Struts MVC ArchitectureModel View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following three
parts:

Model - The lowest level of the pattern which is responsible for maintaining data.

View - This is responsible for displaying all or a portion of the data to the user.

Controller - Software Code that controls the interactions between the Model and View.

MVC is popular as it isolates the application logic from the user interface layer and supports
separation of concerns. Here the Controller receives all requests for the application and then
works with the Model to prepare any data needed by the View. The View then uses the data
prepared by the Controller to generate a final presentable response. The MVC abstraction can be
graphically represented as follows.

The model
The model is responsible for managing the data of the application. It responds to the request
from the view and it also responds to instructions from the controller to update itself.

The view
A presentation of data in a particular format, triggered by a controller's decision to present the
data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate
with AJAX technology.
The controller
The controller is responsible for responding to user input and perform interactions on the data
model objects. The controller receives the input, it validates the input and then performs the
business operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC
methodology within Struts2.

Spring: (7 questions)
Q What is dependency injection in spring?
Dependency Injection (DI) is a design pattern that removes the dependency from
the programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled and easier for
testing. The Dependency Injection is a design pattern that removes the dependency
of the programs. In such case we provide the information from the external source
such as XML file.
Q Two ways to perform (Achieve)Dependency Injection in Spring
framework

Spring framework provides two ways to inject dependency

By Constructor

By Setter method

Q How to achieve dependency injection?

Q What is spring bean lifecycle?

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be
required to perform some initialization to get it into a usable state. Similarly, when the bean is no
longer required and is removed from the container, some cleanup may be required.
Though, there is lists of the activities that take place behind the scenes between the time of bean
Instantiation and its destruction, but this chapter will discuss only two important bean lifecycle
callback methods which are required at the time of bean initialization and its destruction.
To define setup and teardown for a bean, we simply declare the <bean> with init-method and/or
destroy-method parameters. The init-method attribute specifies a method that is to be called on
the bean immediately upon instantiation. Similarly, destroy-method specifies a method that is
called just before a bean is removed from the container.
Q Significance of FilterDispatcher in spring.

Q What is Spring MVC architecture?

The Spring web MVC framework provides model-view-controller architecture and ready
components that can be used to develop flexible and loosely coupled web applications. The

MVC pattern results in separating the different aspects of the application (input logic, business
logic, and UI logic), while providing a loose coupling between these elements.

The Model encapsulates the application data and in general they will consist of POJO.

The View is responsible for rendering the model data and in general it generates HTML
output that the client's browser can interpret.

The Controller is responsible for processing user requests and building appropriate
model and passes it to the view for rendering.

Q What is the roll of controller class in spring.

Q List down some annotations used in spring MVC.


Spring Annotations: Contents:
Annotation

Package Detail/Import statement

@Service

import org.springframework.stereotype.Service;

@Repository

import org.springframework.stereotype.Repository;

@Component

import org.springframework.stereotype.Component;

@Autowired

import
org.springframework.beans.factory.annotation.Autowired;

@Transactional

import
org.springframework.transaction.annotation.Transactional;

@Scope

import org.springframework.context.annotation.Scope;
Spring MVC Annotations

@Controller

import org.springframework.stereotype.Controller;

@RequestMapping

import
org.springframework.web.bind.annotation.RequestMapping;

@PathVariable

import org.springframework.web.bind.annotation.PathVariable;

@RequestParam

import
org.springframework.web.bind.annotation.RequestParam;

@ModelAttribute

import
org.springframework.web.bind.annotation.ModelAttribute;

@SessionAttribute import
s
org.springframework.web.bind.annotation.SessionAttributes;
Spring Security Annotations
@PreAuthorize

import
org.springframework.security.access.prepost.PreAuthorize;

***********************************************************************

Hibernate ( 7 questions)
Advantages of Hibernate Framework.
Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-toMany, Many-To-One
In jdbc all exceptions are checked exceptions, so we must write code in try, catch
and throws, but in hibernate we only have Un-checked exceptions, so no need to
write try, catch, or no need to write throws. Actually in hibernate we have
the translator which converts checked to Un-checked

Hibernate has capability to generate primary keys automatically while we are storing the
records into database
Hibernate has its own query language, i.e hibernate query language which is database
independent
So if we change the database, then also our application will works as HQL is database
independent
HQL contains database independent commands
While we are inserting any record, if we dont have any particular table in the database,
JDBC will rises an error like View not exist, and throws exception, but in case of hibernate, if
it not found any table in the database this will create the table for us
It's provides HQL (Hibernate Query Language), which is compatible with any
database server. You just need to write queries in HQL, at the end hibernate
converts HQL to underlying database and executes it.

List down the components of hiberante framework.

Lifecycle of object in hibernate.

Difference between get and load method.

What is HQL? Advantages of HQL.

Significance of criteria queries in hibernate. How to get object of Criteria?

Significance of native queries in hibernate.

Das könnte Ihnen auch gefallen