0% found this document useful (0 votes)
11 views132 pages

AnswerList Interview

The document contains an interview transcript with questions and answers related to Java, Spring Boot, and object-oriented programming concepts. Key topics include transaction management, annotations like @PostConstruct and @PreDestroy, OOP principles such as encapsulation, inheritance, polymorphism, and the differences between implementing Runnable vs extending Thread. Additionally, it discusses concepts like race conditions, thread safety, and associations in Java.

Uploaded by

Bl Gocher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views132 pages

AnswerList Interview

The document contains an interview transcript with questions and answers related to Java, Spring Boot, and object-oriented programming concepts. Key topics include transaction management, annotations like @PostConstruct and @PreDestroy, OOP principles such as encapsulation, inheritance, polymorphism, and the differences between implementing Runnable vs extending Thread. Additionally, it discusses concepts like race conditions, thread safety, and associations in Java.

Uploaded by

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

***07/09/18 : TMW *********************

----- NARENDRA KLI INTERVIEW ------------------

1 proj exp
2 db - connectivity flow
3 db link
4 database cursor
5 spring boot
6 core java
7 java 8 [stream , default method, optional ]
7 microservice deploye
Q : Diff bw HttpClient vs RestTemplate ?
Q : how to communicate 2 service ?

Q : What is race condition?


ans :-
Two or more threads compete together to get certain shared resources.
For example, if thread A is reading data from the linked list and another thread B
is trying to delete the same data.
This process leads to a race condition that may result in run time error.

> How to avoid race condition?


There are the following two solutions to avoid race conditions.

1 Mutual exclusion
2 Synchronize the process [see Syncronized_Account example]

------

Q- what is Transaction management in Spring Boot?


ans:
Transaction is a sequence of actions that are treated as a single unit of work.
These actions should either complete entirely or take no effect at all.

transactions can be described with the following four key properties described as
ACID -

Atomicity - A transaction should be treated as a single unit of operation, which


means either the entire sequence of operations is successful or unsuccessful.
Consistency - This represents the consistency of the referential integrity of the
database, unique primary keys in tables, etc.
Isolation - There may be many transaction processing with the same data set at the
same time. Each transaction should be isolated from others to prevent data
corruption.
Durability - Once a transaction has completed, the results of this transaction have
to be made permanent and cannot be erased from the database due to system failure.

Q - what mean by @PostConstruct in Spring Boot ?


ans:
�PostConstruct� - Annotation is used to create methods that spring will call
automatically (even the static ones) after the bean is initialized.
it call only once, and it run if there is nothing to initialize
we use this annotation in ServiceIMPL classes with init() method to call procedures
---------------------------
Q - what mean by @PostDestroy in Spring Boot ?
ans
@PreDestroy runs only once, just before Spring removes our bean from the
application context.

Same as with @PostConstruct, the methods annotated with @PreDestroy can have any
access level, but can�t be static.
or
it gets called when bean instance is getting removed from the context.
Note-if your spring bean scope is �prototype� then it�s not completely managed by
the spring container and
PreDestroy method won�t get called.

----------------------------
Q - Component life cycle ?
ans:
public void init() [initialization code, loading configuration file , Connection
code , webservice]
public void destroy()

-----------------------------

Q: in class and interface implements,extend, how to order ?


ans:- Note: in at time extends and implemts condition, first use extends then
implements. else get error.
EXTENDS Vs IMPLEMENTS:
----------------------
Extends : used b/w class to class or interface to interface.
Implements: used b/w interface to class

Note 1:
-------
>a class can extends only a class at a time,
but
>a interface can extends any no. of interface simultansouly
and
>a class can implement any no. of interface at a time.
mean a class can extends only one class at a time but can implement any no of
interface at a time.
Ex : class A extends B // not more than one .
{
}
class A implements B,C,D // can implement more than one.
{
}
OR
diff
Java Extends vs Implements: In short, extends is for extending a class and
implements are for implementing an interface.
first write extends then implements or
implements must always be written after extends in class declaration .

Q: what is oops features ? what is polymorphism ? give example ?


----------------------------------------------------------------
OOPS:-
>it is a technics or methodology that provide or suggestion to design and develop
object in programming language with security.

it allow more clarity , and simplicity, reduce redudancy and keep data confidencial

** OOPS PRINCIPLE:
------------------
1 ENCAPSULAITON:
2 INHERITANCE
3 POLYMORPHYSIM
4 ABSTRACTION

1 ENCAPSULAITON: [data hiding]


----------------
>hiding internal data from outside accessing, exposing public method to access.
how to achive?
--------------
by declaring variables as private, and accessing by public setters and getters
methods to access private vars.

why setter and getters used ?


ans: to validate the data befor storing the data in var.
like we not allowed negative or less values.

2 INHERITANCE:
--------------
> its a process of reusing one object properties to another object.

3 POLYMORPHYSIM:
----------------
>defining multiple methods with same name with diff impl

4 ABSTRACTION:-
---------------
> Process of defining a class by necessary details to call operation by hiding its
impl details.

Note: java does not support multiple inheritance, but it provides alternative to
support it with interfaces.

*TYPE OF INHERITANCE:
======================
1 single level : if only two classes or interface participating
2 multi level : if more than two class are particapating relation vertically.
3 hierarchical : if we drive multiple subclasses from one super class or
more than one class extends one super class.
4 hybrid : (mixing all type inheritances) or combining other type inheritances

5 multple interface inheritance : implementing more than interfaces by one class.

Note: we can stop multi level inheritance by declaring our sub class as final.

Note: in at time extends and implemts condition


first use extends then implements. else get error.

Note: if a class driving or implementing a interface , then its also driving by


from object indirectally.

Note : => we can call class method by using interface ref var also. and that method
is executed from subclass of that interface.

conclusion:=> every interface subclass is a subclass of object class by default.


so we can cast object class ref var to interface var.

and also we can call object class method by using interface ref var.

CASE : if two interface has method with same protype then subclass should impl only
one method.

CASE : if two interface has method with same name but diff param then subclass
should impl both methods.
because they are overloading method.

CASE : if two interface has 2 method with same signature but diff return type then
inheritance not possible.

CASE : if two interface has method with diff return type like object and String
type then subclass should impl String type(covariant type) method allowed.

CASE : every method should be impl with public kw.

CASE : after declaring a method static, we can not override static method as non
static and non static as static.

Note:- we can access interface var from subclass by using var name directally
because var are static final in interface.

Note: if two interface var has same name then we diff it using interface name with
var name.

**POLYMORPHISM :
----------------
it can be develop by using
1 method overriding [it occures in parent and child class]
2 method overloading. [it occures in same class]

* COMPILETIME POLYMORPHISM:- if a method is invoked , and its definition bind at


compilation time by compiler and executed by
jvm at runtime.
* RUNTIME POLYMORPHISM:- when a method is invoked, the method definition is bind at
compilation time but not executed at runtime
executed from subclass based on object stored in ref var.

Note:- only non static overriden methods comes under runtime polymorphsim
and
private non static methods and default non static methods comes under
compiler time polymorephism.

** DEFINITION FOR INTERVIEW -RUNTIME POLYMORPHISM ?


ANS: the process of executing mehtod from diff class based on obj stored in ref var
is called runtime polymorphism.

Note: => To develop runtime polymorphism, we must call method by using super class
ref var , then only we can store all subcalss objects.

Q HOW TO IMPLEMENTED RUNTIME POLYMORPHISM


ans: using

1-UPCASTING :- to store subclass objects.


2-MEHTOD OVERRIDING

ex: imp programm


----------------
interface Sim
{
public void dialCall();
public void sendSms();
}

class Airtel implements Sim


{
public void dialCall()
{
System.out.println("airtel number called ");
}
public void sendSms()
{
System.out.println("sms sent to airtel number successfully ");
}
}

class Docomo implements Sim


{
public void dialCall()
{
System.out.println("Docomo number called ");
}
public void sendSms()
{
System.out.println("sms sent to Docomo number successfully ");
}
}

class Mobile
{
void insertSim(Sim s)
{
s.dialCall();
s.sendSms();
}
}
class OOPSConceptMobileUser
{
public static void main(String[] args)
{
Mobile nokia = new Mobile();
nokia.insertSim(new Docomo());
}
}

or

Note : REAL TIME EXAMPLE ON POLYMORPHISM ?


ans:

1 :Compile time Polymorphism (or Static polymorphism)


Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same
name, if the parameters of methods are different in number, sequence and data types
of parameters.

Different ways to overload the method

There are two ways to overload the method in java

By changing number of arguments


By changing the data type

class Adder{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

or

class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

Compile Time Polymorphism Example Program


class ClassMain{
void disp(int number)
{
System.out.println ("method:" + number);
}
void disp(int number1, int number2)
{
System.out.println ("method:" + number1 + "," + number2);
}
double disp(double number)
{
System.out.println("method:" + number);
return num;
}
}

class CompileTimePolymorphismDemo
{
public static void main (String args [])
{
ClassMain obj = new ClassMain();
double result;
obj.disp(40);
obj.disp(50, 30);
result = obj.disp(5.1);
System.out.println("Answer is:" + result);
}
}

2 RUNTIME POLYMORPHISM
EX 1:
interface vehicle
{
public void engine();
public void breaks();
}

abstract class Bus implements vehicle


{
public void breaks()
{
System.out.println("bus has 2 breaks");
}
}

class RedBus extends Bus


{
public void engine()
{
System.out.println("Redbus engine capacity 40 kmph");
}
}

class volvo extends Bus


{
public void engine()
{
System.out.println("volvo engine capacity 180 kmph");
}
}

// runtime polymorphism class to use all vehicle operations


class Driver
{
public void assignVehicle(vehicle v)
{
v.engine();
v.breaks();
}
}

class ClassesType
{
public static void main(String[] args)
{
Driver d=new Driver();
d.assignVehicle(new volvo());

Driver d1=new Driver();


d1.assignVehicle(new RedBus());
}
}

op:
volvo engine capacity 180 kmph
bus has 2 breaks
Redbus engine capacity 40 kmph
bus has 2 breaks

EX2:

Java Runtime Polymorphism Example: Bank


------------------------------------------

class Bank
{
float getRateOfInterest()
{
return 0;
}
}

class SBI extends Bank


{
float getRateOfInterest()
{
return 8.4f;
}
}

class ICICI extends Bank


{
float getRateOfInterest()
{
return 7.3f;
}
}
class AXIS extends Bank
{
float getRateOfInterest()
{
return 9.7f;
}
}
class TestPolymorphism
{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

OR
abstraction, encapsulation, inheritance, and polymorphism.

1 Abstraction:
Abstraction is the concept of hiding the internal details and describing things in
simple terms.
ways to achieve abstraction in object oriented programming, such as encapsulation
and inheritance.

2 Encapsulation :
Encapsulation is used for access restriction to a class members and methods.

3 Polymorphism :
Polymorphism is the concept where an object behaves differently in different
situations. There are two types of polymorphism � compile time polymorphism and
runtime polymorphism.
Compile time polymorphism is achieved by method overloading.

4 Inheritance is the mechanism of code reuse.

Q: volatile , transient, static kw ?


-------------------------------------
Volatile variable: [ not to modify var value concurrentally by multiple
threads]
------------------
>it has at class level var
>local var can not be declared as volatile
>tells to jvm that we do not want to modify var value concurrentally by multiple
threads.
or multiple thread are allowd to change its value in sequence one after one.

Transient variable : [to ignore serealization]


--------------------
>class level var that has Transient kw .
>local var can not be declared as Transient
>it tells to jvm that we dont want to store var value in a file in object
serialization.

STATIC MODIFIER:
----------------
>applicable for var , method, block, inner-class, but not allowed for top class
>we can access static members directally from both area's static and instance
but we can not directally access instance(non-static) member from static area,
require class obj ref.

>we can access directally instance(non-static) members from instance(non-static)


area.

>instance and static var with same name not allowed but local and static var may be
with same name

>inheritance concept is applicable for static methods including main() but while
executing child
class mm then parent class mm will be executed.
it seems overriding concept for static members but its not overriding its method
hiding.

> if we r not using any instance var inside a method then we should declare static
but if we r using any instance var inside a method then declare that method as
instance method.

Q: which one is better to thread Implemnting Runnable interface or extending Thread


class ?
-----------------------------------------------------------------------------------
---------
ans:
When there is a need to extend a superclass, then implementing the Runnable
interface is more appropriate than using the Thread class. Because we can extend
another class while implementing Runnable interface to make a thread.
But if we just extend the Thread class we can't inherit from any other class.

Java doesn't support multiple inheritance, so if your class already extends an


object, you can't also extend Thread.
By implementing Runnable, multiple threads can share an instance of your work.
or
extending Thread and implementing Runnable comes from the fact that a class can
only extend one class in Java.
So if you extend the Thread class then your class lose that option and it cannot
extend another class,
but if you implement Runnable then your Thread class can still extend another
class.
or
In object oriented programming, extending a class means modifying or improving the
existing class. If you are not improving the class, then it is not a good practice
to extend it. So, implementing Runnable will be the best object oriented design
practice.
�Implements Runnable� makes your code loosely coupled. Because it separates the
task from the runner. �Extends Thread� will make your code tightly coupled.
Because, single class will act as both task container as well as runner.
Implementing Runnable improves the reusability of your code. Because, Runnable
contains only the task and you can use it wherever and whenever you want.

Q: what is ASSOCIATION , Aggrigation , Composition in java?


----------------------------------------------------------

1 ASSOCIATION : -[IS-A] - is relationship , it is relation between 2 classes,


it has 2 type 1 Aggrigation , 2 Composition

2 Aggrigation : in this relation object are loose couply, both class can exist
indepedentally, both have seperate life cycle.
ex: Team <->Cricket player

3 Composition : in this relation object are tight couply, both class can not exist
indepedentally, both not have seperate life cycle
ex: Car <-> Engine

------------------------------------------

diagram : ( association (aggregation (composition) ) )

1 Association: [ indepedent classes and var used in another classes and It


joins two entirely separate entities.]

We call association those relationships whose objects have an independent lifecycle


and where there is no ownership between the objects.
Ex:- Multiple students can associate with a single teacher, and a single student
can associate with multiple teachers, but both have their own lifecycles (both can
be create and delete independently
so when a teacher leaves the school, we don�t need to delete any students, and when
a student leaves the school, we don�t need to delete any teachers.

or
Association is a relationship between two separate classes and the association can
be of any type say one to one, one to many etc.
It joins two entirely separate entities.

2 aggregation : [objects have an independent lifecycle, but there is ownership, and


child objects cannot belong to another parent object.]

objects have an independent lifecycle, but there is ownership, and


child objects cannot belong to another parent object.
Ex:-a cell phone and phone battery. A single battery can belong to a phone, but if
the phone stops working, and we delete it from our database, the phone battery will
not be deleted because it may still be functional. So in aggregation, while there
is ownership, objects have their own lifecycle.
or
Aggregation can be considered as a �has-a� relationship. The parent object contains
(has) child objects, but the child object can also survive or exist without the
enclosing class.

Example: Room has a table, but the table can exist without the room.
or
Aggregation is a special form of association which is a unidirectional one way
relationship between classes (or entities), for e.g. Wallet and Money classes.
Wallet has Money but money doesn�t need to have Wallet necessarily so its a one
directional relationship. In this relationship both the entries can survive if
other one ends. In our example if Wallet class is not present, it does not mean
that the Money class cannot exist.

3 Composition: [child fully depend on parent / objects don�t have an independent


lifecycle,]
We use the term composition to refer to relationships whose objects don�t have an
independent lifecycle, and
if the parent object is deleted, all child objects will also be deleted.
ex: relationship between questions and answers. Single questions can have multiple
answers, and answers cannot belong to multiple questions. If we delete questions,
answers will automatically be deleted.
or
Composition is also known as a �is a part of� relationship. The part may also be
created and destroyed by the whole. The member object (part) cannot exist without
the containing class.
Example: A department is part of a college and it cannot exist or has no meaning
after the lifetime of the college. Another example is rooms in a house, which
cannot exist after the lifetime of the house.

Composition is again specialised form of Aggregation and we can call this as a


�death� relationship. It is a strong type of Aggregation. Child object does not
have its lifecycle and if parent object is deleted, all child objects will also be
deleted.

Q : what mean by loosly coupling and tight coupling?


-----------------------------------------------------
Tight Coupling:-
usually highly dependent on each other's interfaces. Changing one object in a
tightly coupled application often requires changes to a number of other objects.
Tight coupling means the two classes often change together.
// Java program to illustrate
// tight coupling concept
class Subject {
Topic t = new Topic();
public void startReading()
{
t.understand();
}
}
class Topic {
public void understand()
{
System.out.println("Tight coupling concept");
}
}

Explanation: In the above program the Subject class is dependents on Topic class.
In the above program Subject class is tightly coupled with Topic class it means if
any change in the Topic class requires Subject class to change. For example, if
Topic class understand() method change to gotit() method then you have to change
the startReading() method will call gotit() method instead of calling understand()
method.

or

See below code is for tight coupling.

public class Journey {


Car car = new Car();
public void startJourney() {
car.travel();
}
}

public class Car {


public void travel () {
System.out.println("Travel by Car");
}
}

In the above code the Journey class is dependents on Car class to provide
service to the end user(main class to call this Journey class).
In the above case Journey class is tightly coupled with Car class it means
if any change in the Car class requires Journey class to change. For example if Car
class travel() method change to journey() method then you have to change the
startJourney() method will call journey() method instead of calling travel()
method.

See below code,

public class Journey {


Car car = new Car();
public void startJourney() {
car.journey();
}
}

public class Car {


public void journey () {
System.out.println("Travel by Car");
}
}

The best example of tight coupling is RMI(Remote Method Invocation)(Now a


days every where using web services and SOAP instead of using RMI, it has some
disadvantages).

or

class Traveler
{
Car c=new Car();
void startJourney()
{
c.move();
}
}

class Car
{
void move()
{
// logic...
}
}

Loose Coupling:- In simple words, loose coupling means they are mostly independent.
----------------
only a few parts of the application should be affected when requirements change.
It's highly changeable. One module doesn't break other modules in unpredictable
ways.

to reduce the inter-dependencies between components of a system with the goal of


reducing the risk that changes in one component will require changes in any other
component. Loose coupling is much more generic concept intended to increase the
flexibility of system,

In the below example, Journey and Car objects are loosely coupled. It means Vehicle
is an interface and we can inject any of the implemented classes at run time and we
can provide service to the end user.

The examples of Loose coupling are Interface, JMS, Spring IOC(Dependency Injection,
it can reduce the tight coupling).
ex:
Below code is an example of loose coupling,

public interface Vehicle{


void start();
}

public class Car implements Vehicle {


@Override
public void start() {
System.out.println("Travel by Car");
}
}

public class Bike implements Vehicle {


@Override
public void start() {
System.out.println("Travel by Bike");
}
}

// create main class Journey


public class Journey {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
}
}

or

best ex:
class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

void startJourney()
{
v.move();
}
}
//=========================Interface====================================

Interface Vehicle
{
void move();
}

class Car implements Vehicle


{
public void move()
{
// logic
}
}

class Bike implements Vehicle


{
public void move()
{
// logic
}
}

Q: string s='abc' then s='xyz' what is output ? and why ?


ans: xyz
or
String s="Badri";
s="Lal";
System.out.println(s); op: Lal // changing the ref
or
String s="hello";
s="india";
System.out.println(s); // india

and
String s="hello";
s=s+"india";
System.out.println(s); // helloindia
or
String s="hello";
String s2=s+"india";
System.out.println(s2);// helloindia

and
String s1="java1";
String s2=new String("java2");
s1.concat("java-1 is added");
s2.concat("java-2 is added");
System.out.println(s1); //java1
System.out.println(s2); //java2

and

String s1="java1";
s1="hello";
System.out.println(s1); //hello
and
String s="hello";
s.concat("BL");
System.out.println(s); // hello

and
String s=new String("java");
s.concat("jee");
System.out.println(s);// java
and
String s=new String("java");
String s2=s.concat("jee");
System.out.println(s2); //javajee
--------------------------------
String s=�java�;
s=s+�j2ee�;
System.out.println(s); //javaj2ee here the reference changes.

and
String s=new String("java");
String s2=s.concat("jee");
s2=s2.concat("spring");
System.out.println(s2);//javajeespring
------------------------------

Q-
String s1 = new String(�JAVA�);
System.out.println(s1); //Output : JAVA
s1.concat(�J2EE�);
System.out.println(s1); //Output : JAVA
s1 = s1 + �J2EE�;
System.out.println(s1); //Output : JAVAJ2EE
s1.concat(�wwee�);
System.out.println(s1); // Output : JAVA
System.out.println(s1.concat(�wwee�)); // Output : JAVAwwee

Q
String s1 = �JAVA�, s2 = �JAVA�;
System.out.println(s1==s2); //true
Q
String s1 = �Hello�;
s1 = �helloWorld�;
S.o.p(s1); // o/p- helloworld.

Q
String s1 = "Hel" + "lo";
String s2 = "Hello";
System.out.println(s1 == s2);
The code above will return true

Q what is syncronized ?
-----------------------
ans:-
Java Synchronization is to allow only one thread to access the shared resource and
to control the access of multiple threads to any shared resource.
--
Synchronized blocks in Java are marked with the synchronized keyword. A
synchronized block in Java is synchronized on some object
Concurrent access of shared objects in Java introduces to kind of errors: thread
interference and memory consistency errors and to avoid these errors you need to
properly synchronize

synchronization is mainly used to


1-To prevent thread interference.
2-To prevent consistency problem.
This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization

ex:
public class Counter{

long count = 0;

public synchronized void add(long value){


this.count += value;
}
}

or

Important points of synchronized keyword in Java:


-------------------------------------------------
1 Synchronization in Java guarantees that no two threads can execute a
synchronized method which requires the same lock simultaneously or concurrently.

2. You can use java synchronized keyword only on synchronized method or


synchronized block.

3. Whenever a thread enters into java synchronized method or blocks it acquires a


lock and whenever it leaves java synchronized method or block it releases the lock.
The lock is released even if thread leaves synchronized method after completion or
due to any Error or Exception

4. Java Thread acquires an object level lock when it enters into an instance
synchronized java method and
acquires a class level lock when it enters into static synchronized
java method.

6. Java Synchronization will throw NullPointerException if object used in java


synchronized block is null e.g. synchronized (myInstance) will throw
java.lang.NullPointerException if myInstance is null

10. Java synchronized block is better than java synchronized method in Java because
by using synchronized block you can only lock critical section of code and avoid
locking the whole method which can possibly degrade performance. A good example of
java synchronization around this concept is getting Instance() method Singleton
class.

Q: how to write syncronized method or block ?


----------------------------------------------
ans:
syncronized method:
public class Counter
{
private static int count = 0;

public static synchronized int getCount()


{
return count;
}
public synchoronized setCount(int count)
{
this.count = count;
}

or
synchronized method by using annonymous class

In this program, we have created the two threads by annonymous class, so less
coding is required.

//Program of synchronized method by using annonymous class


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

for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}

}
}

public class TestSynchronization3{


public static void main(String args[]){
final Table obj = new Table();//only one object

Thread t1=new Thread(){


public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};

t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500

Java Synchronized Example


Here is an example that starts 2 threads and have both of them call the add method
on the same instance of Counter. Only one thread at a time will be able to call the
add method on the same instance, because the method is synchronized on the instance
it belongs to.

public class Counter{

long count = 0;

public synchronized void add(long value){


this.count += value;
}
}
public class CounterThread extends Thread{

protected Counter counter = null;

public CounterThread(Counter counter){


this.counter = counter;
}

public void run() {


for(int i=0; i<10; i++){
counter.add(i);
}
}
}
public class Example {

public static void main(String[] args){


Counter counter = new Counter();
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);

threadA.start();
threadB.start();
}
}

or
Need of Synchronization:
ex:1st thread fetches the value of i. (Currently value i is 0) and increases it by
one, so value of variable i becomes 1.
Now 2nd thread accesses the value of i that would be 0 as 1st thread did not store
it back to its location.
And 2nd thread also increment it and store it back to its location. And 1st also
store it.
Finally value of variable i is 1. But it should be 2 by the effect of both threads.
That�s why we need to synchronize the access to shared variable i.

Example: Synchronized access to getLine() method on the same Object

// Example that shows multiple threads


// can execute the same method but in
// synchronized way.
class Line
{

// if multiple threads(trains) trying to access


// this synchronized method on the same Object
// but only one thread will be able
// to execute it at a time.
synchronized public void getLine()
{
for (int i = 0; i < 3; i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}

class Train extends Thread


{
// Reference variable of type Line.
Line line;

Train(Line line)
{
this.line = line;
}

@Override
public void run()
{
line.getLine();
}
}

class GFG
{
public static void main(String[] args)
{
Line obj = new Line();

// we are creating two threads which share


// same Object.
Train train1 = new Train(obj);
Train train2 = new Train(obj);

// both threads start executing .


train1.start();
train2.start();
}
}
Run on IDE
Output:

0
1
2
0
1
2

BLOCK:

Block Synchronization

If we only need to execute some subsequent lines of code not all lines
(instructions) of code within a method, then we should synchronize only block of
the code within which required instructions are exists.
For example, lets suppose there is a method that contains 100 lines of code but
there are only 10 lines (one after one) of code which contain critical section of
code i.e. these lines can modify (change) the Object�s state. So we only need to
synchronize these 10 lines of code method to avoid any modification in state of the
Object and to ensure that other threads can execute rest of the lines within the
same method without any interruption.

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

public class Geek


{
String name = "";
public int count = 0;

public void geekName(String geek, List<String> list)


{
// Only one thread is permitted
// to change geek's name at a time.
synchronized(this)
{
name = geek;
count++; // how many threads change geek's name.
}

// All other threads are permitted


// to add geek name into list.
list.add(geek);
}
}

class GFG
{
public static void main (String[] args)
{
Geek gk = new Geek();
List<String> list = new ArrayList<String>();
gk.geekName("mohit", list);
System.out.println(gk.name);

}
}
Run on IDE
Output :

1
Important points:

When a thread enters into synchronized method or block, it acquires lock and once
it completes its task and exits from the synchronized method, it releases the lock.
When thread enters into synchronized instance method or block, it acquires Object
level lock and when it enters into synchronized static method or block it acquires
class level lock.
Java synchronization will throw null pointer exception if Object used in
synchronized block is null. For example, If in synchronized(instance) , instance is
null then it will throw null pointer exception.
In Java, wait(), notify() and notifyAll() are the important methods that are used
in synchronization.

or

public class Singleton


{
private static volatile Singleton instance;

public static Singleton getInstance()


{
if(instance == null)
{
synchronized(Singleton.class)
{
if(instance == null)
instance = new Singleton();
}
}
return instance;
}

or
Synchronized block can be used to perform synchronization on any specific resource
of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same
as the synchronized method.

Points to remember for Synchronized block


Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.

Q what is thread safe ?


------------------------
==> Thread safe is concept of multi threading.
==> when we execute a thread .other thread will not allowed access the same object.
==> It is possible when the object is synchronized. It will lock the object until
the operation completes.
==> Best example is immutable class like String.
==> We can also execute the method,variable with Synchronized.
The concept of thread safe is simply that the program state
(fields/objects/variables) behaves correctly when multiple simultaneous threads are
using a resource.

Q: how to create multiple threads ?


------------------------------------
ans:

Q: Creating Multiple Threads ?


ans:-
class MyThread extends Thread {

public MyThread (String s) {


super(s);
}

public void run() {


System.out.println("Run: "+ getName());
}
}

class TestThread {
public static void main (String arg[]) {

Scanner input = new Scanner(System.in);


System.out.println("Please input the number of Threads you want to create: ");
int n = input.nextInt();
System.out.println("You selected " + n + " Threads");

for (int x=0; x<n; x++)


{
MyThread temp= new MyThread("Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}
}
}

or

Creating Multiple Threads


class MyThread implements Runnable {
String name;
Thread t;
MyThread String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

or

Creating Multiple Threads

class MyThread implements Runnable {


String name;
Thread t;
MyThread String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}

public void run() {


try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

Q: how to allow multiple access to singleton class by duoble checking ?


-----------------------------------------------------------------------
ans:

* 2nd version : this definitely thread-safe and only * creates one instance of
Singleton on concurrent environment * but unnecessarily expensive due to cost of
synchronization * at every call. */

public static synchronized Singleton getInstanceTS()


{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}

or
/* * 3rd version : An implementation of double checked locking of Singleton. *
Intention is to minimize cost of synchronization and improve performance, * by only
locking critical section of code, the code which creates instance of Singleton
class. * By the way this is still broken, if we don't make _instance volatile, as
another thread can * see a half initialized instance of Singleton. */

public static Singleton getInstanceDC()


{
if (instance == null) // Single Checked
{

synchronized (Singleton.class)
{
if (instance == null) // Double checked
{

instance = new Singleton();

}
}
}
return instance;
}

Q: how to manage/solve out of memory error ?


---------------------------------------------
ans:
1) An easy way to solve OutOfMemoryError in java is to increase the maximum heap
size by using JVM options "-Xmx512M", this will immediately solve your
OutOfMemoryError.
2) The second way to resolve OutOfMemoryError in Java is You can use Eclipse Memory
Analyzer to examine your heap dump

Q: if Byte a=10; Byte b=10; then sop(a+b); ?


----------------------------------------------
ans: 20

extra reading
AUTOMATIC TYPE PROMOTION IN EXPRESSION:
-----------------------------------------
> both operand should be compatible type else we get error
ex boolean b
int i
int res=b+i ; // errore
>in arthimatic operation , result always comes in highest data type
int=byte+byte

ex: int i=10;


float f=15;
//float res=i+f; // if res type is int then error
System.out.println("Result : "+(i+f));

> we can store in int also but type cast-


int res=i+(int)f;
or
System.out.println("Result : "+(i+(int)f));

> if two float are there then u want to cast then


ex: float f1=15.0f;
float f2=17.25f;
int i=(int)(f1+f2);

IMP-NOTE: in expression, byte, short, char -> automatically converted to int ,


bcoz minimum memory location req for calculate exp is 4 byte.

case1: byte b1=25;


byte b2=30;
int b3=b1+b2; // if u try to hold in byte or short then error

sol: byte b3=(byte)(b1+b2);

case2:
>if you hold char in a char data and print
char ch='a';
System.out.println("Result : "+ch); //97
>char ch=98; sop(ch); //b

>char ch='A'+'a'; // Result : � symbol

---------------------------------------------------------

** Expressions in :- System.out.Println();
---------------------------------------------
> System.out.println(10); /10
> System.out.println('a'); /a
> System.out.println("a"); /a
> System.out.println(10.0); /10.0
> System.out.println(30L); /30
> System.out.println(10.12l); /error
> System.out.println(50+30); /80

>int a=20,b=15;
System.out.println(a+b); /35

>int a=20,b=15;
System.out.println("a+b"+a+b); / ab2015

>int a=20,b=15;
System.out.println("a+b"+(a+b)); / ab35

>int a=20,b=15;
System.out.println("a+b"+a-b); /error

>int a=20,b=15;
System.out.println("a-b"+(a-b)); /a-b5

>int a=20,b=15;
System.out.println("a*b"+a*b); /a*b300

>int a=20,b=15;
System.out.println("a*b"+(a*b)); /a*b300

>System.out.println(" "+10+20); / 1020

>System.out.println(10+""+20); //1020

>System.out.println(10+20+""); /30

>System.out.println(10/5*5*5); /50

>System.out.println(10/0); /run time erro divi by zero....

>System.out.println(10.0/0) //infinity

>System.out.println(-10.0/0);/-infinity

> System.out.println(0/0);/ run time erro divi by zero....

> System.out.println(0.0/0); /NAN


>System.out.println(-0.0/0);

>sop("the result of "+a+"and "+b+" +"is"+ c)//

int a=20;
String s="a"+a; //a20

Imp Note:
---------
1- we can not divide integer number by zero, if then get errore-
java.lang.ArthimaticException
ex:10/0 - java.lang.ArthimaticException.
but
we can devide float by zero - it output is-> INFINITY
ex:10.0/0 - infinity

2- we can not divide Integer (wrapper) by zero , if then get error-


java.lang.ArthimaticException
but
we can devide float point zero by zero - op NAN
0.0/0 : NAN

Q try , catch finally ? execution flow ?


------------------------------------------
try ->finally
try ->catch ->finally
try ->finally

Q what is diff bw clone and clonable interface ?


------------------------------------------------
The Cloneable interface defines no members.
It is used to indicate that a class allows a bitwise copy of an object (clone).
If you try to call clone( ) on a class that does not implement Cloneable, a
CloneNotSupportedException is thrown.
When a clone is made, the constructor for the object being cloned is not called.
A clone is simply an exact copy of the original.

The object cloning is the exact copy of an object. and clone() method of Object
class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object


clone we want to create.
If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.

Why use clone() method ?


The clone() method saves the extra processing task for creating the exact copy of
an object.
If we perform it by using the new keyword, it will take a lot of processing to be
performed that is why we use object cloning.
An object which is returned by the clone() method is known as a clone of original
instance

Q why we need string immutailbity in java?


------------------------------------------
=> single String instance can be shared across different threads
=>string objects are immutable. means unchangeable.
Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object
Once string object is created its data or state can't be changed but a new string
object is created.
different String variables can refer to same String variable in the pool.

Security:
String is immutable is that it is used by the class loading mechanism
parameters are represented as String in network connections, database connection
urls, usernames/passwords etc. If it were mutable, these parameters could be easily
changed

Caching :
being immutable String in Java caches its hashcode, and do not calculate every time
we call hashcode method of String, which makes it very fast as hashmap key to be
used in hashmap in Java
String is immutable, its hashcode is cached at the time of creation and it doesn�t
need to be calculated again.

Thread Safety:
it is safe for multithreading and a single String instance can be shared across
different threads. This avoid the usage of synchronization for thread safety,
Strings are implicitly thread safe.
thread-safe in Java, means you don't need to synchronize String operation
externally.
to avoid any synchronization issues in Java,
Synchronization and concurrency: making String immutable automatically makes them
thread safe thereby solving the synchronization issues.

Q: can we use class as staic ?


------------------------------
ans:
top class can not use , but inner class can be used static.

Q why string is immutaible ?


---------------------------
String is immutable for several reasons, here is a summary:
String is Immutable in Java because String objects are cached in String pool. Since
cached String literals are shared between multiple clients there is always a risk,
where one client's action would affect all another client.

or
Security:
parameters are typically represented as String in network connections, database
connection urls, usernames/passwords etc. If it were mutable, these parameters
could be easily changed.
Main reason is about security
Many passwords, db connection infos and important parameters are sending using
"String".

Synchronization and concurrency:


making String immutable automatically makes them thread safe thereby solving the
synchronization issues.
Caching:
when compiler optimizes your String objects, it sees that if two objects have same
value (a="test", and b="test") and thus you need only one string object (for both a
and b, these two will point to the same object).
ex:
hashcode of string is frequently used in Java. For example, in a HashMap. Being
immutable guarantees that hashcode will always the same, so that it can be cached
without worrying the changes.That means, there is no need to calculate hashcode
every time it is used.

or

String Constant Pool ... If string is mutable, changing the string with one
reference will lead to the wrong value for the other references.

Security:
String is widely used as parameter for many java classes, e.g. network connection,
opening files, etc. Were String not immutable, a connection or file would be
changed and lead to serious security threat. ...

Q String s="MH"; then s="INDIA"; what is finally output ?


----------------------------------------------------------
ans:- INDIA
immutable in the sense of memory. It creates new objects every time you create
strings or assign a new string/change the value.
When you called s = "INDIA", you are actually changing the reference of s to a new
object created by the String literal "INDIA".
but u can not concate new value to a reference.
both hashcode are different.
here s pointing both values with diff hascode method, now again if we assign MH to
s then first ref s hold it.

Q Why and how to override toString method ?


-------------------------------------------
=>So overriding the toString() method, returns the desired output,
noramally The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on
the object. it can be the state of an object etc. depends on your implementation.

ex:
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
Output:Student@1fee6fc
Student@1eed786

printing s1 and s2 prints the hashcode values of the objects but I want to print
the values of these objects. Since java compiler internally calls toString()
method, overriding this method will return the specified values. Let's understand
it with the example given below:

how to override:-
public String toString()
{
//overriding the toString() method
return rollno+" "+name+" "+city;
}
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()

Output:101 Raj lucknow


102 Vijay ghaziabad

or

public String toString() {


return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '"
+ this.bDay + "'";
}

or

public String toString(){


return id+" "+name+" "+address;
}
Q what marker interface ?
-------------------------
Marker interface in Java
It is an empty interface (no field or methods).
Ex: Serializable, Clonnable and Remote interface. All these interfaces are empty
interfaces.

like-Cloneable interface is present in java.lang package. Cloneable interface is


used to mark cloning operation and Serializable interface is used to mark
serialization and deserialization of an object.

like-Marker interfaces in java are interfaces with no members declared in them.


They are just an empty interfaces used to mark or identify a special operation. For
example, Marker interfaces give instructions to JVM that classes implementing them
will have special behavior and must be handled with care.

Serializable interface :
Serializable interface is present in java.io package. It is used to make an object
eligible for saving its state into a file. This is called Serialization.
This interface is used to mark serialization and deserialization of an object.
Serialization is a process in which an object state is read from memory and written
into a file or a database. Deserialization is a process in which an object state is
read from a file or a database and written back into memory. Any class which wants
it�s object to be eligible for serialization and deserialization must implement
Serializable interface.
Classes that do not implement this interface will not have any of their state
serialized or deserialized.
All subtypes of a serializable class are themselves serializable.

1) java.lang.Cloneable Interface :
This interface is used to mark the cloning operation. An object of a class which
implements Cloneable interface is eligible for field-by-field copying of an object.
Invoking Object�s clone method on an instance of the class that does not implement
the Cloneable interface results in an exception CloneNotSupportedException being
thrown.

2) java.io.Serializable Interface :
ex:-
interface Cash
{

interface Checque
{

class PaymentOne implements Cash


{
static void paymentByCash()
{
System.out.println("Payment is done by cash");
}
}

class PaymentTwo implements Checque


{
static void paymentByChecque()
{
System.out.println("Payment is done by checque");
}
}

public class MainClass


{
public static void main(String[] args)
{
PaymentOne.paymentByCash();

PaymentTwo.paymentByChecque();
}
}

why use marker interface


You can create marker interface to logically divide your code and if you have your
own tool than you can perform some pre-processing operation on those classes.
a marker interface called Thread Safe can be used to communicate other developers
that classes implementing this marker interface gives thread-safe guarantee and any
modification should not violate that. Marker interface can also help code coverage
or code review tool to find bugs based on specified behavior of marker interfaces.
A marker interface can be replaced by an annotation

Q can we create obj of abstract class and marker interface ?


-------------------------------------------------------------
NO we cant create an object of an Interface ,
You cannot create object of a marker interface that will have meaning to the JVM,
like the java.io.Serializable interface does
we use an Interface to hide the implementations from user.
Interface contains only abstract methods and as abstract methods do not have a body
(of implementation code) we can not create an object without constructor also .
--
Abstract classes:-
cannot be instantiated, means we can't create an object to Abstract class.
We can create Subclasses to Abstract classes. ... So JVM will not able to allocate
memory for the abstract methods when the time of creating instance to Abstract
class. So JVM unable to create the instance to Abstract class.
It's because an abstract class isn't complete
Because an abstract class is an incomplete class (incomplete in the sense it
contains abstract methods without body and output) we cannot create an instance or
object; the same way you say for an interface.

Q which/how many access modifer are used to class level ?


---------------------------------------------------------
MODIFIERS FOR TOP CLASS LEVEL ARE:
----------------------------------
1 Public
2 Default
3 Final
4 Abstract
5 Strictfp

>if we use other modifier then we get C.E


But

MODIFERS ALLOWED FOR INNER CLASSES ARE:


---------------------------------------
1 Public
2 Default
3 Final
4 Abstract
5 Strictfp
+
6 private
7 protected
8 static
Q What is shallow cloning and deep cloning?
-------------------------------------------

Cloning is a process of creating an exact copy of an existing object in the memory.


In java, clone() method of java.lang.Object class is used for cloning process. This
method creates an exact copy of an object .
Not all the objects in java are eligible for cloning process. The objects which
implement Cloneable interface are only eligible for cloning process.
Cloneable interface is a marker interface which is used to provide the marker to
cloning process. Click here to see more info on clone() method in java.
The default version of clone() method creates the shallow copy of an object.
To create the deep copy of an object, you have to override the clone() method.
** SHALLOW CLONING VS DEEP CLONING:

SHALLOW CLONING:
----------------
> the process of creating depedent copy of an object is called shallow cloning.
if main object contains any primitive vars then exactaly duplicate copies will be
created in cloned object.
if main object contains any reference var then same object will not be created
just ref var will be created by pointing to old contained object.

> by using main ref if we perform any changes to contained object then changes will
be reflected automatically to cloned object.
> by default object class clone() meant for shallow cloning.

Note:- shallow cloning is the best choice , if object contains only primitive
values.
in shallow cloning by using main object ref , if we perform any changes to
contained object then changes reflected automaticaly to cloned copy.

To overcome this prob we go for deep cloning.

** DEEP CLONING:
-----------------
The process of creating exactaly indepedent duplicate object, is called deep
cloning.
> in deep cloning, if main object contain any ref var then correspondence object
copy also will be created in cloned object.

> Object class clone() mehtod mean for shallow cloning , if we want deep cloning
then prog is responsible to impl by overriding clone() method.

Note:- in deep cloning by using main object ref if we perform any changes to
contained object those changes will not be reflected to cloned object.

Q- which cloning is best ?


ans:
if object contains only primitive vars then shallow cloning is the best choice.

if object contains reference vars then deep cloning is the best choice.
What is Shallow Copy:-
Shallow copy is a bit-wise copy of an object. A new object is created that has an
exact copy of the values in the original object.
If any of the fields of the object are references to other objects, just the
reference addresses are copied i.e., only the memory address is copied.
The shallow copy of an object will have exact copy of all the fields of original
object.
If original object has any references to other objects as fields, then only
references of those objects are copied into clone object, copy of those objects are
not created.
That means any changes made to those objects through clone object will be reflected
in original object or vice-versa.
Shallow copy is not 100% disjoint from original object. Shallow copy is not 100%
independent of original object.
Shallow copy:Generally clone method of an object, creates a new instance of the
same class and copies all the fields to the new instance and returns it. This is
called shallow copy. Object class provides a clone method and provides support for
the shallow copy. It returns �Object� as type and you need to explicitly cast back
to your original object. Since the Object class has the clone method, you cannot
use it in all your classes. The class which you want to be cloned should implement
clone method and overwrite it. It should provide its own meaning for copy or to the
least it should invoke the super.clone(). Also you have to implement Cloneable
marker interface or else you will get CloneNotSupportedException. When you invoke
the super.clone() then you are dependent on the Object class�s implementation and
what you get is a shallow copy.

Deep copy:-
When you need a deep copy then you need to implement it yourself. When the copied
object contains some other object its references are copied recursively in deep
copy.
A deep copy copies all fields, and makes copies of dynamically allocated memory
pointed to by the fields. A deep copy occurs when an object is copied along with
the objects to which it refers.
Deep copy of an object will have exact copy of all the fields of original object
just like shallow copy. But in additional, if original object has any references to
other objects as fields, then copy of those objects are also created by calling
clone() method on them. That means clone object and original object will be 100%
disjoint. They will be 100% independent of each other. Any changes made to clone
object will not be reflected in original object or vice-versa.
To create a deep copy of an object, you have to override the clone() method.
deep copy is a fully independent copy of an object. If we copied our Person object,
we would copy the entire object structure.

diff Shallow Copy Deep Copy


Cloned Object and original object are not 100% disjoint. Cloned Object and
original object are 100% disjoint.
Any changes made to cloned object will be reflected in original object or vice
versa.
Any changes made to cloned object
will not be reflected in original object
or vice versa.
Default version of clone method creates the shallow copy of an object.
To create the deep copy of an
object, you have to override clone
method.
Shallow copy is preferred if an object has only primitive fields.
Deep copy is preferred if an object
has references to other objects as
fields.
Shallow copy is fast and also less expensive. Deep copy is slow
and very expensive.

Q: how to seriealize and deserialize object in java ?


or
Q what is Serialization, when we go it ? which method use read AND write ?
---------------------------------------------------------------------------
java.io.Serializable

Serializable Objects:
To serialize an object means to convert its state to a byte stream so that the byte
stream can be reverted back into a copy of the object.
Serialization:- in java is a mechanism of writing the state of an object [java
support form] into a byte stream [network supported form].
Deserialization:- the process of reading state of a object from a file is called
De-Serialization.
It is mainly used to travel object's state on the network (known as marshaling).
A Java object is serializable if its class or any of its superclasses implements
either the java.io.Serializable interface

Deserialization is the process of converting the serialized form of an object back


into a copy of the object.

=>usage of readObject(), writeObject(), readExternal() and writeExternal() or not.


=>Java Serialization is done by java.io.ObjectOutputStream class. That class is a
filter stream which is wrapped around a lower-level byte stream to handle the
serialization mechanism. To store any object via serialization mechanism we call
ObjectOutputStream.writeObject(saveThisobject) and
=>to deserialize that object we call ObjectInputStream.readObject() method. Call to
writeObject() method trigger serialization process in java. one important thing to
note about readObject() method is that it is used to read bytes from the
persistence and to create object from those bytes and its return an Object which
needs to be type cast to correct type.

by using FileOutPutStream and ObjectOutPutStream classes we can achive


serialization

ex: Product p = new Product();


Serialize:- FileOutPutStream fos = new FileOutPutStream("filename.ser");
ObjectOutPutStream oos = new ObjectOutPutStream( fos );
oos.writeObject(p);

By using FileInputStream and ObjectInputStream classes we can achive De-


Serialization.

De-Serialize :- FileInputStream fis = new FileInputStream("filename.ser");


ObjectInputStream ois = new ObjectInputStream(fis);

Product p2 =(Product)ois.readObject();
Q While serializing you want some of the members not to serialize? How do you
achieve it?
-----------------------------------------------------------------------------------
------
transient keyword.

Q What is immutable and can u write your own immutable class?


--------------------------------------------------------------
CASE 1:
-------
ex:1
String s = new String("bhaskar");
s.concate("software")

sop(s); op// bhasker

Note:- once we create a string object, we can not perform any chages in existing
object.
if we try to change then a new object is created, this behaviour is called
Immutable of string object.

CASE 2:
-------
ex:1
String s1 = new String("bhaskar");
String s2 = new String("bhaskar");
Note:- after using New keyword , every time creating new object so-
sop(s1==s2); // false-> both are pointing diff obj
sop(s1.equals(s2)); // true-> contents are same

IMP_Note:- In String, .equals() method is overriden for content comparision so if


content is same .equals mehtod returns true
even though object are diff.

CASE 3:
-------
Ex: String s = new String("bhaskar");

IMP_NOTE:=> in this case, two object will be created , one is on heap and other one
is SCP- string constant pool and s is always pointing to heap object.

ex: String s="bhaskar";


IMP_NOTE:=>in this case, only one object will be created in SCP and s is always
pointing to that scp object.

**IMP- POINTS:
--------------
1: Object creation in SCP is always optional, first jvm will check is any object
already created with req content or not in SCP.
if is already availble then it will reuse existing instead of creating new.
if it is not there then only new object will created.
so there is no chance of existing two objects with same content on scp or
duplicate obj are not allowed in SCP.
2 Garbage collector can not access SCP area , even though object do not have any
ref[not usable long time] still that obj is not
eligible for GC if it is present in SCP.
All scp objects will be destroyed at the time of jvm shutdown automatically.

IMP-Q-in below how many objects will be created ? :

String s1 = new String("bhaskar");


String s2 = new String("bhaskar");

String s3="bhaskar";
String s4="bhaskar";

ans: total 3 object will created, 2 object with each new kw , 1 in scp with bhaskar
content
[other object content is same so point to same scp]
Explanatin:=>
s1-> create two obj , one in heap , and one in scp for futur.
s2-> create one obj in heap, and in scp its point to old content, not create new
object.
s3-> not create any object , only point to old content already availble in scp

Note: Each new kw create every time new object.


Note: above all object ref pointing to scp bhaskar content

Imp-note:=> whever we are using new operator compulsory a new object will be
created on heap. and there may be chance of existing two object with same content
on heap, but there is no chance of existing two objects with same content on scp.
or duplicate object possible in heap but not in scp.

** IMPORTANCY OF SCP-[STRING CONSTANT POOL]: [CONSIDER ON VOTER FORM EXAMPLE]


------------------------------------------------------------------------------
1 in our prog, if any string object is req to use repeataly then it is not
recomnded to create multiple obj with same content,
it reduce performance and effects mem utilization.

2 we can create one copy and we can reuse same obj for every req. this improve
performance and mem utilization,
we can achive this by using scp.

3 Disadavntage in scp, several refs pointing to same obj , so by using one ref if
we perform any change the remaining refs will be effected. to overcome this
problum sun implemented immutability concept for string objects.

4 once we creats a string obj , we can not perform any changes in existing obj if
we try to perform any changes with changes a new string obj will be created so
immutaiblility is the main disadvantage of SCP.
----------------------------------------------------------------------------------

diff bw
String s = new String("Durga");
and
String s="Durga"; ?
ans: in case of - String s = new String("Durga"); two obj created , one in scp and
one in heap.
in case of - String s="Durga"; only one obj is created in scp.

SCP :
ans: string constant pool is specially designed memory area for string object to
reuse .

advantage of SCP ?
ans: memory utilizataion , and performance improved.

disadvantage of SCP ?
ans: immutaibility

why string objects are req immutaible whereas stringbuffer obj are imutaible?
ans:
in case of string as several refs pointing to same object, and by using one ref if
we allowed perform changes then the remaining ref will be effect. so to prevent ,
once we created a string obj we can not perform changes in existing object that is
immutaibility.

diff bw final and immutable ?


ans :1 final applicable is applicabe for vars and immutaible for objects.
2 if we declare class/object , then we can make changes but not possible in
immutaible.

** INTERNING OF STRING OBJECTS:


-------------------------------
by using heap obj ref , if want to get corresponding scp object, then we should use
intern() method.
ex:
String s1 = new String("bhasker");
String s2 = s1.intern();

Note:- if the corresponding obj is not there in scp then intern() method itself
will create that obj and return it.

**** IMMUTAIBLE PROGRAMME:-


ex: by nareshit
rules:-
1-final class
2-all var's declare private
3-try to inilize throw constructor.
4-dont allow setter method [these are used to set/change in var]

programme-
public class Immutable
{
private final int a;
public Immutable(int a)
{
this.a=a;
}

public int getA()


{
return this.a;
}
}
Note:- if we try to perform any changes with those changes a new object will be
created. and
if no changes in content then existing object will be used . this is called
immutaiblity.
ex:

final class CreateImmutable


{
private int i;

CreateImmutable(int i)
{
this.i=i;
}

public CreateImmutable modify(int i)


{
if(this.i==i)
return this;

else
return (new CreateImmutable(i));
}

Public Static Void Main(String[] args)


{
CreateImmutable c1 = new CreateImmutable(10);
CreateImmutable c2=c1.modify(100);
CreateImmutable c3=c1.modify(10);

SOP(c1==c2); // false

}
}

**or
To create immutable class in java, you have to do following steps.

Declare the class as final so it can�t be extended.


Make all fields private so that direct access is not allowed.
Don�t provide setter methods for variables
Make all mutable fields final so that it�s value can be assigned only once.
Initialize all the fields via a constructor performing deep copy.
Perform cloning of objects in the getter methods to return a copy rather than
returning the actual object reference.

or

How to create an immutable class?

Ans) To create an immutable class following steps should be followed:

Create a final class.


Set the values of properties using constructor only.
Make the properties of the class final and private
Do not provide any setters for these properties.
If the instance fields include references to mutable objects, don't allow those
objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external,
mutable objects passed to the constructor; if necessary, create copies, and store
references to the copies. Similarly, create copies of your internal mutable objects
when necessary to avoid returning the originals in your methods.

Q ClassNotFoundException vs NoClassDef FoundError ?


-------------------------------------------------
ans:
DIFF BW ClassNotFoundException and NoClassDefFound Exception
----------------------------------------------------------
NoClassDefFoundError:
---------------------
>if hard coded class .class file not availble at runtime then we get runtime this
exception,
> which is unchecked.
ex : Test t = new Test();
at runtime, if test.class file is not availble then we get -NoClassDefFoundError

ClassNotFoundException:
-----------------------
if dynamically provided class name is not availble at runtime then we get runtime
exception - ClassNotFoundException
ex: Object o = Class.forName("Test").newInstance();
then at runtime if this Test class file not availble so we get
ClassNotFoundException error.

Q Explain singleton design pattern, write code to make class as a singleton ?


-----------------------------------------------------------------------------
or
Q: what is design patterns and how many you used ? what is singleton design
pattern?
write a program to make a singleton?

ans:-
In Java the Singleton pattern will ensure that there is only one instance of a
class is created in the Java Virtual Machine. It is used to provide global point of
access to the object. In terms of practical use Singleton patterns are used in
logging, caches, thread pools, configuration settings, device driver objects.
Singleton Class:
Static member : This contains the instance of the singleton class.
Private constructor : This will prevent anybody else to instantiate the Singleton
class.
Static public method : This provides the global point of access to the Singleton
object and returns the instance to the client calling class.
or
Some basics rules required to implement a singleton class

Constructor should be private


Declare a static variable object of the class
Declare a static method to return the instance
or
To design a singleton class:

Make constructor as private.


Write a static method that has return type object of this singleton class. Here,
the concept of Lazy initialization in used to write this static method.

Java Singleton Sample Code


Code:
package com.myjava.constructors;

public class MySingleTon {

private static MySingleTon myObj;


/**
* Create private constructor
*/
private MySingleTon(){

}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}

public void getSomeThing(){


// do something here
System.out.println("I am here....");
}

public static void main(String a[]){


MySingleTon st = MySingleTon.getInstance();
st.getSomeThing();
}
}

//or

// File Name: Singleton.java


public class Singleton {

private static Singleton singleton = new Singleton( );

/* A private Constructor prevents any other


* class from instantiating.
*/
private Singleton() { }

/* Static 'instance' method */


public static Singleton getInstance( ) {
return singleton;
}

/* Other methods protected by singleton-ness */


protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Here is the main program file where we will create a singleton object -

// File Name: SingletonDemo.java


public class SingletonDemo {

public static void main(String[] args) {


Singleton tmp = Singleton.getInstance( );
tmp.demoMethod( );
}
}
This will produce the following result -

Output
demoMethod for singleton
Example 2
Following implementation shows a classic Singleton design pattern -

public class ClassicSingleton {

private static ClassicSingleton instance = null;


private ClassicSingleton() {
// Exists only to defeat instantiation.
}

public static ClassicSingleton getInstance() {


if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}

Create a Singleton Class.

SingleObject.java

public class SingleObject {

//create an object of SingleObject


private static SingleObject instance = new SingleObject();

//make the constructor private so that this class cannot be


//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}

public void showMessage(){


System.out.println("Hello World!");
}
}
Step 2
Get the only object from the singleton class.

SingletonPatternDemo.java

public class SingletonPatternDemo {


public static void main(String[] args) {

//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();

//Get the only object available


SingleObject object = SingleObject.getInstance();

//show the message


object.showMessage();
}
}

or

The classic singleton

public class ClassicSingleton {


private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}

or

Early initialization of class variable


public class Singleton {
private final static Singleton obj = new Singleton() ; //early init
private Singleton () {}; //private constructor
public static Singleton getInstance() {
return obj;
}
}
Lazy initialization of class variable
public class Singleton {
private static Singleton obj = null ;
private Singleton () {}; //private constructor
public static Singleton getInstance() {
if (null == obj) {
obj = new Singleton();
}
return obj;
}
}

Q how to read a file in java ?


-------------------------------
classic BufferedReader:- to read content from a file

ex:
BufferedReader br = null;
FileReader fr = null;

try {

br = new BufferedReader(new FileReader(FILENAME));


fr = new FileReader(FILENAME);
br = new BufferedReader(fr);

Q finalize method ?
-------------------
finalize is a method, always invoked by Garbage collector just befor destroying an
object to perform cleanup activities.
The java.lang.Object.finalize() is called by the garbage collector on an object
when garbage collection determines that there are no more references to the object.

A subclass overrides the finalize method to dispose of system resources or to


perform other cleanup.

Q what mean final class ?


--------------------------
ans:-
Final keyword has a numerous way to use:
A final class cannot be subclassed/ inherited
A final method cannot be overridden by subclasses
A final variable can only be initialized once
Q diff checked and unchecked ? example ?
---------------------------------------

** Exception Hierarchy:
-----------------------

Objcet
|
Throwable

Note:-Throwable acts as root for Exception Hierarchy


Throwable class contain two child classes - Exception , Error.

Objcet
|
Throwable
|

-----------------------------------------------------------------------------------
-----------------------------
|
|
Exception
Error
|_____________________
_________________________________|____________
| |
| |
--------------------------------------------------------
VMError LinkageError AssertationError
| | | _______|___________
| RuntimeException
IOException SQLException ServletException
| |
| | OutOfMemoryError
StackOverflowError
| |_________
| |--EOFException
|--ArthimeticException |
| |--FileNotFoundException
|--NullPointerException |
| |--InterrptedIOException
|--IndexOutBoundException
| |
| |-ArrayIndexOutOfBoundException
| |-StringIndexOutOfBoundException
|
|--IllegalArgumentException
| |
| |--NumberFormatException
|
|--ClassCastException
|
|--IllegalStateException
Unchecked: �Error� and its subclasses,�RunTimeException� and its subclasses
Checked:- except -Error� and its subclasses,�RunTimeException� and its subclasses ,
remaining all are checked.
or
*** CHECKED Vs UNCHECKED EXCEPTION:
-----------------------------------

CHECKED : - Exception which are checked by compiler for smooth execution of


programm at runtime are called checked Exception.
[whether programmer handling or not].
or
classes that extend Throwable class [except RuntimeException and Error]
are known as checked exceptions
e.g.
IOException,
SQLException etc,
ServletException,
ClassNotFoundException

Note:- Checked exceptions are checked at compile-time.


ex: FileNotFoundException

UNCHECKED EXCEPTION:-
classes that extend RuntimeException are known as unchecked exceptions
e.g.
ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException
IllegalArgumentException
IllegalStateException
Note:- Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.

Note:-Runtime and its childs+ Errors and its child are un checked and
remaining all are checked Exceptions

Note:- whether Exception is checked or uncheked compulsory it should occurs at


runtime only.
and there is no chance of occuring any Exception at compile time.

Q multithreading ?
-------------------
executing several tasks simultaneously where each task is seprate indepedent part
of same program.
and each part is called a "Thread".
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.
ex: its best sutaible for programatic level.
and its easy in java, becouse java provide in built support for multithreading
through a API [Thread, Runnable, ThreadGroup,ThreadLocal, etc.]
Advantages 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.
What is Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a
separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.

Q how to override to equals() and hashCode method ?


---------------------------------------------------
Note:-first learn basics
what is hashCode?
ans:
For every object jvm generates a unique number which is nothing but hashCode
jvm use hashcode while saving object into hashing related data structur like
hashSet, HashMap, Hashtable.
if object stored according to hashcode , then searching will become very easy.

Note: the most powerfull search algorithm is hashing which will work based on
hashCode().

Note: overriding hashCode() mehtod is said proper if , for every object we have to
generate a [diff] unique number as hashCode.

ex: for every object we are generating a diff hashcode.


class Student
{
int rollno;
public int hashCode()
{
return rollno;
}
}
Note:- if we are calling to Object toString() method , its internally calls
hashCode() method.
but if override toString() mehtod then it may call or may not call to
hashCode() mehtod.

Diff
----
toString(): use to print object ref or in meaningfull string representation of
object.
hashCode(): use to saving objects into HashSet or Hashtable or HashMap.

1.3 equals() Method: [ref/add comparision]


--------------------
> use to check equivalence of two objects.[by default it check only ref comparison
but not content comparison ]
> if our class do not contain .equals() method then object class .equals() will be
executed which is always for ref/add comparison

Note:
-----
== for ref comparision
wheres
.equals() for content comparision
Note: - if two refs pointing to the same object then it return true.
Note:- if passing same value while creating object then its not same object,
becouse its creating through new kw so its diff object.
if we assigning one obj ref to other ref then its point to same object.
Note:- based on our prog req we can override .equal() mehtod for content
comparision.
Note:- if two refs pointing to same object then ..equals() retrun true directally
without performing any content comparision.
Imp-Note:
---------
> in String class, .equals() is overriden for content comparision so if content is
same .equals() returns true, even though object is different.
> in StringBuffer class .equals() is not overriden for content comparision so
object class .equals() will be executed which meant for ref comparision, so if
objects are diff then .equals() return false even though content is same.
> in String class, Wrapper class and all Collection classes .equals() method is
overriden for content comparision.

** RELATION BW .EQUALS() AND == OPERATOR:


--------------------------------- ---------
1 if r1 ==r2 is true then r1.equals(r2) is always true.
means if two objects are equal by == then objects are always equal
by .equals()method also.
2 if r1==r2 is false , then we can not say about r1.equals(r2) , it may retrurn
true or false.
3 if r1.equals(r2) is true then we can not say about r1==r2 , it may retrun true or
false.
4 if r1.equals(r2) is false then r1==r2 always false.

** DIFF BW == AND .EQUALS


-------------------------

[== operator] and .equals()


-----------------------------------------------------------------------------------
---------------------------------------------

1 its a operator , applicable for both primitive and ref 1 it is method


only for obj ref.
in case of obj ref - this operator meant for ref comparision by
default .equals() mehtod present in object class for
ref comparision

2 we can not override == operator for content comparision in ref obj. 2 we can
override .equals() method for content comparision.

3 if there is no relation bw obj, we get CE. 3 if there is no


relation, it return false but not get CE.

4 for any obj ref r, r--null is always false. 4 for any obj ref
r, r.equals(null) is also always false.
-----------------------------------------------------------------------------------
------------------------------------------------
Note:
-----
== for ref comparision
wheres
.equals() for content comparision

** RELATION BW .EQUALS() AND HASHCODE()METHOD:


----------------------------------------------
1- if two objects are equals by .equal() mehtod , then compulsory their hashCodes
must be same.
2 if two objects are not equals by .equal() mehtod , then there is no restrictions
to their hashCodes must be same or diff.
3 if hashCode of two objects are equals , we can not say anything
about .equals() , it may return true or false.
4 if hashCode of two objects are not equal , then these objects are always not
equal by .equals()

When override equals?


if two same (content) object will have different hashcode .(duplicaiton)

Why you should always override hashCode when overriding equals.


Case Override only hashcode:two same content object will have same hashcode
(duplication)

Q how to override equals() and hashcode()


-----------------------------------------

public class User {


private String name;
private int age;
private String passport;

//getters and setters, constructor


}

@Override
public boolean equals(Object o) {

if (o == this)
return true;

if (!(o instanceof User))


{
return false;
}

User user = (User) o;

return user.name.equals(name) && user.age == age &&


user.passport.equals(passport);
}

@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
result = 31 * result + passport.hashCode();
return result;
}

or

@Override
public boolean equals(Object o) {

if (o == this) return true;


if (!(o instanceof User)) {
return false;
}
User user = (User) o;
return age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(passport, user.passport);
}

@Override
public int hashCode() {
return Objects.hash(name, age, passport);
}

Q diff bw abstract and interface ?


----------------------------------
DIFF BW :

INTERFACE ABSTRACT-CLASS
-----------------------------------------------------------------------------------
-------------------
0.contains only abstract methods 0. can contains both
abstract and concreate methods.

1 if we dont know anything about impl 1. talking about partial


impl but not fully
just have only req speci..

2 every method inside interface is 2. need not to be public abstract.


always public abstract. we can take concreate method
also.

3.we cant declare methods with following 3. no restriction on abstract class


methods.
modifiers-private, protected, static,final
native, syncronized, strictfp.

4.every var inside interface, is always 4. need not to be public


static final.
public static final....wheather declare or not.

5. we cant declare interface var's with 5.No restriction on


abstract class var modifiers
private, protected, transient,volatile

6. for interface var's compulsory we should 6 not require.


provide initilization at the time declration

7 inside interface, we cant declare static and 7.inside abstract class, we


can declare static and
instance blocks. instance blocks.

8. inside interface we cant take constructor. 8. we can take constructor.


===================================================================================
========

**IMPORTANT NOTE:

1. we can not create object for abstract class but abstract class can contain
constructor.
Q what is need?
ans - to perform initialization of child object at the time of child object
creation.

Note: Either directally or indirectally we cant create obj for abstract class.
> whenever we r creating child class object parent constructor will be executed,
but parent obj will not be
created.

> interface contains only abstract methods but abstract class can contain both
abstract and concreate methods.

Q-> if interface contains only abstract methods but abstract class also contain
fully abstract methods
then what is difference?
or
is it possible interface replace by abstract class.
ans: yes we can replace but two problums are there
1 abstract class can extends only one class where as interface can more than one
interfaces
2 object creation is costally for abstract classes.

1 INTERFACE:
------------
>a interface is fully unimplemeted class used for declaring a set of operation of
object.
it contain only final static var and public abstract methods.

2 ABSTRACT CLASS:
-----------------
>a class that is declared as abstract .
it is a partially implimented class used for developing some of the operations of
an object which are common for
all next level subclasses.
> abstract class contains both abstract method and concrete methods including
variables blocks, constructor.

Consider using abstract classes if :


You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or
fields, or require access modifiers other than public (such as protected and
private).
You want to declare non-static or non-final fields.
Consider using interfaces if :

You expect that unrelated classes would implement your interface. For example,many
unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned
about who implements its behaviour.
You want to take advantage of multiple inheritance of type.

Q what is method overridding? with use case? why we prefer Polymorphism over
inheritance?
-----------------------------------------------------------------------------------
-------
**POLYMORPHISM :-
-----------------
>a method with same name with diff forms is concept of polymorphism.
*POLYMORPHISM : consist of-
----------------------------
1-Compiletime or static or earlybinding : [overloading (same method name but diff
args)+ method hiding]
2-Runtime/dynamic/latebinding : [overriding] (same method name and same
args)

OOPS : PILLARS-
---------------
1- inheritance is talks to reusability.
2- polymorphism talks to flexibility.
3- encapsulation talks to security.

** OVERLOADING :-(same method name but diff args)


-----------------
1- two methods are said to be overloaded if and only if both method have same name
but diff argument type.
> overloading also considerd as "Compiletime or static or earlybinding"

ans:

** OVERRIDING : (same method name and same args)


---------------
>whatever parent has by default avaible to child through inheritance, but if child
is not satisfy then child allowed to redefine that parent class method in child in
its own way , this process is called overriding.

*overriding is also considerd as polymorphism or latebinding or late binding.


Nore:- in overriding runtime object will play the role and ref type is dummy.

*RULES FOR OVERRIDING:


----------------------
>method name and args(signatur) must be same.
>return type same and co-variant type are allowed.

CO-VARIANT:
ALLOWED PARENT => OBJECT NUMBER
| | |
CHILD => STRING INTEGER

NOTE ALLOWED PARENT => STRING DOUBLE


| | |
CHILD OBJECT INT

Note:- Co-variant return type concept is applicable only for object type not for
primitive.
Note:- private methods are not visible in child classes hence overriding concept is
not applicable for private method.
base on our requirment we can declare same parent private method in child it
is allowed , but it is not overriding.

Note:- parent class final method can not be override in child class.
Note:- parent class final method we can override as final in child class. we can
also override native methods in child.
Note:- we can override a non abstract method as abstract.
Note:- syncronized, strictfp will not has any restriction on overriding.
Note:- not allowed: final -->non final but non-final -> final is allowed.
native <====> non native, abstract <====> non abstract,
syncronized <====> non syncronized,
strictfp <====> non strictfp.
*OVERRIDING RULE:- while overriding if the child class method throws any checked
exception compulsory the parent class method should throw same checked exception.
else we get C.E
but
There is no restrictions on un-checked exceptions.

*OVERRIDING WITH RESPECT TO STATIC METHODS:


------------------------------------------
CASE 1: we can not overide a static method as non static. same as
we can not override a non static method as static.

Note:- if we overriding static to static then its not overriding , its mehtod
hiding.

**METHOD HIDING:-re defining same parent class static method in child class.
-----------------
overriding hiding
-----------------------------------------------------------------------------------
------------------------------------
1.both non static 1.both static
2.take care by jvm 2. take care by compiler
3.runtime/dynamic/latebinding
3.compiletime/static/early binding.

-----------------------------------------------------------------------------------
------------------------------------
Note:- overriding concept is not applicable for variables.
OVERLOADING OVERRIDING
-----------------------------------------------------------------------------------
----------------------------------
1. method name must be same 1. Must be same
2. argument type diff 2. must be same.
3. method signature must be diff 3. must be same.
4. return type no restriction 4. same or co-variant.
5. private, static, final can not be overloaded. 5. also can not be
overriden.
6. no restriction on Access Modifiers 6. weak / reducing is not
allowed.
7. no restriction on throws clause 7. parent method should
throw same checked exception as child,
not restiction for un-
checked.
8.also called compiletime/static/early binding 8.also called
runtime/dynamic/late binding.
-----------------------------------------------------------------------------------
-------------------------
imp note:
1 : in overloading , we have check only method name same, and args diff , remaining
things like return type extra not req.
but
2 : in overriding , we check everything like mehtod names, args, return type,
throws , modifiers.

imp :-MethodOverriding in Java


There are many rules if we talk about methodoverriding with exception handling. The
Rules are as follows:
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.

Q how to write custom exception handling code ?


------------------------------------------------
The following is a custom exception class which is created by following the above
steps:

public class StudentNotFoundException extends Exception {

public StudentNotFoundException(String message) {


super(message);
}
}
And the following example shows the way a custom exception is used is nothing
different than built-in exception:

public class StudentManager {

public Student find(String studentID) throws StudentNotFoundException {


if (studentID.equals("123456")) {
return new Student();
} else {
throw new StudentNotFoundException(
"Could not find student with ID " + studentID);
}
}
}
And the following test program handles that exception:

public class StudentTest {


public static void main(String[] args) {
StudentManager manager = new StudentManager();

try {

Student student = manager.find("0000001");

} catch (StudentNotFoundException ex) {


System.err.print(ex);
}
}
}
Run this program and you will see this output:

StudentNotFoundException: Could not find student with ID 0000001

ex 2:
------

simple example of java custom exception.

class InvalidAgeException extends Exception{


InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[]){


try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

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


}
}
Test it Now
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Q diff bw throw and throws ?
-----------------------------
THROW :- to hand over our created exception object to JVM manually.
THROWS :- to delegate responsiblity of excepiton handling to caller method.
EX:

*** THROW STATEMENT:


======================
> we can create Exception object explicitally and we can handover to JVM manually
by using throw kw.

ex: throw new ArthimeticException("\ by zero");


Note:- in above stmt, creating explicitally ArthimeticException object new.

Note:- Generally we can use throw kw for customized exceptions but not for
predefined exceptions.

CASE 1: throw e; // if e refer null then we get NPE.

CASE 2: after throw stmt , we can not take any stmt directally , then we get CE -
unreachable stmt.
ex: throw new ArthimeticException("\ by zero");
sop("hello");

CASE 3: we can use throw kw only for Throwable type , otherwise we get CE-
incompatible type.
ex:

class test extends RuntimeException


{
PSVM()
{
throw new Test();
}
}

*** THROWS STATEMENT:


--------------------
1 :we can use Throws kw to delegate the responsibility of exception handling to
caller method. then caller method is responsible to hande that exception.

2 : throws kw required only for checked exception, and usage for unchecked is no
use.
3 : throws kw req only to continue compiler, but it not handle exception,and throws
does not prevent abnormal termination of program.
4 to handle exception we use try catch. so

NOTE:- recomende to use try catch over throws kw.

IMP_NOTE: => In our prog, if there is any chance of raising checked exception
then compulsory we should handle either try catch or by throws kw else
code will not compile.

// if we are not handling


ex: PrintWriter pw = new PrintWriter("abc.txt");
pw.println("hello"); // unreported exception:-
FileNotFounException,must be caught/declared to be thrown

or

Thread.sleep(5000); // unreported exception:-


java.lang.InterptedException, must be caught/declared to be thrown

Note:- we can handle this CE by using 2 ways:


---------------------------------------------

1 : By using try catch:


11:24 AM 9/7/2018-----------------------
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
//
}

op: compile and run successfully

2 : By using Throws kw:


---------------------------

Class Test
{
PSVM() throws InterruptedException
{
Thread.sleep(5000);
}
}

ex:2
-----

1 : By using try catch:


try
{
sop(10/0);
}
catch(ArthimeticExceptin e)
{
//
}

op: compile and run successfully

2 : By using Throws kw:


---------------------------
Class Test
{
PSVM() throws ArthimeticExceptin
{
sop(10/0);
}
}
**Note:- if we have many mehtod and we handover exception one above one order
then , we can not remove at least one throws kw
then prog will not be execute.
CASE 4:- we can use throws kw only for constructor and methods but not for classes.

or
throws clause is used to declare an exception and throw keyword is used to throw an
exception explicitly.
If we see syntax wise then throw is followed by an instance variable and throws is
followed by exception class names.
The keyword throw is used inside method body to invoke an exception and throws
clause is used in method declaration (signature).
or
Difference between throw and throws in Java
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.

------------------------------------
MethodOverriding in Java
---------------------------
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.

Q diff bw sleep and wait ?


---------------------------
sleep() :
-----------
if a thread do not want to perform any operation for a particular amount of time
then use sleep().
where as Thread which is required updation it has to call wait() mehtod on the req
obj
then immediately the thread will entered into waiting state.
once a thread calls wait() method on given object , first it release the lock of
that object immediataly and entered into waiting state.

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.

or

wait()

wait() method releases the lock.


wait() is the method of Object class.
wait() is the non-static method - public final void wait() throws
InterruptedException { //...}
wait() should be notified by notify() or notifyAll() methods.
wait() method needs to be called from a loop in order to deal with false alarm.
wait() method must be called from synchronized context (i.e. synchronized method or
block), otherwise it will throw IllegalMonitorStateException
sleep()

sleep() method doesn't release the lock.


sleep() is the method of java.lang.Thread class.
sleep() is the static method - public static void sleep(long millis, int nanos)
throws InterruptedException { //... }
after the specified amount of time, sleep() is completed.
sleep() better not to call from loop(i.e. see code below).
sleep() may be called from anywhere. there is no specific requirement.

Wait and sleep are two different things:

In sleep() the thread stops working for the specified duration.


In wait() the thread stops working until the object being waited-on is notified,
generally by other threads.

From this post : http://javaconceptoftheday.com/difference-between-wait-and-sleep-


methods-in-java/

wait() Method.

1) The thread which calls wait() method releases the lock it holds.

2) The thread regains the lock after other threads call either notify() or
notifyAll() methods on the same lock.

3) wait() method must be called within the synchronized block.

4) wait() method is always called on objects.

5) Waiting threads can be woken up by other threads by calling notify() or


notifyAll() methods.

6) To call wait() method, thread must have object lock.


sleep() Method

1) The thread which calls sleep() method doesn�t release the lock it holds.

2) sleep() method can be called within or outside the synchronized block.

3) sleep() method is always called on threads.

4) Sleeping threads can not be woken up by other threads. If done so, thread will
throw InterruptedException.

5) To call sleep() method, thread need not to have object lock.

Q how to get abstraction in class ?


-----------------------------------
Abstraction in Java:
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal
details

Ways to achieve Abstraction

There are two ways to achieve abstraction in java


Abstract class (0 to 100%)
Interface (100%)

Q-what is diff bw final, finally, finalize?


-------------------------------------------
1>final and finally are kw where as finalize is method
2>final-used to create constants vars, methods, class.
finally-to define a block of statments to be executed definately for a try block
finalize- used to define logic to be executed definately before object is
destroyed.
Note:- logic written inside finally and finalize method is called as resource
releasing logic
or clean up code

Q- diff bw static kw, final kw and abstract kw ?


------------------------------------------------
ans:

STATIC MODIFIER:
----------------
>applicable for var , method, block, inner-class, but not allowed for top class
>we can access static members directally from both area's static and instance
but we can not directally access instance(non-static) member from static area,
require class obj ref.

>we can access directally instance(non-static) members from instance(non-static)


area.
>instance and static var with same name not allowed but local and static var may be
with same name

>inheritance concept is applicable for static methods including main() but while
executing child
class mm then parent class mm will be executed.
it seems overriding concept for static members but its not overriding its method
hiding.

> if we r not using any instance var inside a method then we should declare static
but if we r using any instance var inside a method then declare that method as
instance method.

FINAL :- final class, final method,final varible:


====================================================
Final- is the modifier applicable for inner class, method , variable
the main advantage of final is achive security , its not allowed
modification
but disadvantage is missing benifits of oops like inheritance ,
polymorphism.

Final method:
-------------
>if child method not allowed to override then declare final method in parent class.
>whatever parent has by default availble to child through inheritance.
but if child is not satisfy with parent impl then child is allowed to override tht
method on
its requirement.
but
if parent class method declared final then child is not allowed to override that
method.
or means we cant override final method and final class methods also.

Final Class:
------------
>if a class declared final then we cant create child class
or
>we cant extends final class or inharitance is not applicable to final class.

Note:- every method inside final class is final method , whether we r declaring or
not.
but
every variable present inside final class need not be final.

Abstact modifier:
-----------------
> applicable only for method and classes not for variable.

Abstact method:
---------------
>if we dont know implitation then we can declare method with abstract modifier
>abstact method has only declaration but not implementation.
>abstact method declaration should end with semicolon ;
>its not allowed body.
Note:-advantage is we can provide guidline to child for impl.
ex;
public abstact void showData();

>child class is responsible to provide impl for parent class abstact method.
ex:
abstact class vechile
{
public abstact int getnowheels();
}
class bus extends vechile
{
public int getnowheels()
{
return 7;
}
}

>abstract method never talk about implementation.


>illegal combination with abstract :
abstract-> final
syncronized
static
native
private
strictfp

Abstract Class:
---------------
>if we dont want to create object, or dont allow to create object of class then
declare with abstract modifier
>for abstract class instantiation is not possible.

Abstract class Vs Abstract method:


----------------------------------
1> if a class contains atleast one abstract method then compulsory declare that
class
abstract class because impl is not complete so cant create object.
2> even though class not contain any method but we can declare abstract class
means abstract class may be with zero no of absract method.

ex: HttpServlet, Adapter class that is absract class but doesnot contains any
absract method.

Abstract Vs Final:
------------------
1>for abstract class we can create child class to provide impl but final class
we can not create child class.

2> abstract method can be override in child to provide impl


but final we can not override . so abstract final is illegal comb..

rules for abstract class:


-------------------------
>if we extending any abstract class then for each and every abstract method of
parent class
we should provide impl, else we have to declare this class as abstract class.
then again child class is responsible to provide impl.
ABSTRACT:
- the class can be extendable but we can't instantiate that.
- the class must be used if you declare.
FINAL:
- if you apply on the class, which can not be extendable.
- if you apply on methods, those are not overridden.
-if you apply on variables, those are not reinitialized.
STATIC:
- those methods and block can be invoked before creating an instantiation.

collections.
------------
Q tell me interfaces in collection framwork ?
key interfaces in collection :-
ans:-
1 Collection (I)
2 List(I)
3 Set(I)
4 Map(I)
5 SortedSet(I)
6 SortedMap(I)
7 NaviabeSet(I)
8 NavigableMap(I)
9 Queue(I)

Q collection herairchy ?

diag: Collection(i) [1.2]


|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]

---------------------------

Set(i) :
-------------

diag: Collection(i) [1.2]


|
Set(i) [1.2]
|
----------------------------------------------------------
| |
HashSet(c) [1.2] SortedSet(i) [1.2]
| |
LinkedHashSet(c) [1.4] NavigableSet(i) [1.6]
|
TreeSet(c) [1.2]

Map(i) : diag
==========

Map(i) [1.2]
|

-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]

Q what is generics and benifits of it in collections framwork ?


---------------------------------------------------------------
INTRODUCTION:
-------------
the main objective of Generics is to
1 provide Type-Safety and
2 resolve Type-Casing problums.

CASE 1: Type-Safety
-------------------
> array are always type safe.
> ex : if our prog req is to hold string type of objects its recommended to use
string array.
in case of string array , we can hold only string type of objects, if by
mistak we try to add any other then get CE.

Note:-
> array are type safe.
but
> collections are not type-safe.[means we can not say which type elements present
inside colleciton]
ex: if req to hold string type of objects then its never recomended to for for
arraylist.
by mistake if we try to add any other type then we will not get any CE but prog
may fail at Runtime.

CASE 2: Type-Casting:
---------------------
> in case of array at the time of retrivel , its not req to perform any type
casting.
ex: String sname=str[0];

but
> in case of collection, at the time of rerival compulsory req type casting else we
get CE.
ex: String s=(String) al.get(0);
Integer i = (Integer) al.get(1);

this type type casting is mandatory in collection.


Note:- To overcome above prob of collection(type safety, and type casting) sun
introduced generics concepts in 1.5v
Q-Why generics are used
ans:-
1 To provide type safety to collections
2 To resovle type casting problums
**To hold only perticular type objects we can create a generic version of arraylist
as below:
ex: ArrayList<String> al = new ArrayList<String>();

Note:we can store only defined type objects. like above string only.

Imp-Note: after defining a generic type object , while retriving object type
casting not required.
this is done through generic syntax.
**CONCLUSION 1:
===============
Note:- Polymorphism concept is applicable only for base type not for param type.
[holding child ref in parent]
ex: ArrayList<String> // here Arraylist is base type and String is param type.

means Arraylist can hold ref of its sub type.


ex:
=> List<String> l = new ArrayList<String>(); // correct
=> Collection<String> al = new ArrayList<String>();// correct
=> ArrayList<Object> al = new ArrayList<String>();// its not allowed Object
**CONCLUSION 2:
==============
> Collections concept applicabe only for objects, so for param type we can use any
class or interface but not primitive type.
if use then we get CE

ex: List<int> l = new ArrayList<int>(); // not allowed pritive type param.

Q what is collection class ?


----------------------------
COLLECTION: -
-----------
>if we want to (represnt a group of objects as a single entity) then we should go
for collection.
>collection defines several classes and interfaces to represent a group of objects
as a single entity.
Collection(i) [1.2]:
--------------------
> It is root interface,
> It is used to represent a group of individual Objects as a single entity.
> it define Most common mehtods which are applicable for any collection.
[Note:-
1-To represent a group of individual obects :-Collection, List, Set,
SortedSet, NavigableSet Queue
2-To represent a group of key-value pairs :- map
]

Note: DIFF BW Collection(i) and Collections(c) :


==================================================
Collection(i): = > is a interface to represent a group of individual objects as a
single entity.
where as
Collections(c): => is an Utility classes present in java.uti pckg to define
utillity methods for collection objects.

Q where you use collections in your project ?


----------------------------------------------
List<Item> itemList=service.getAllItemsOfCust(custId);
List<Object[]> arrList=service.getIdAndNamesOnly();
List<Location> locList=service.getAllLocations()
List<Object[]> data=service.getLocationwiseCount();
List<Vendor> venList=service.getAllVendors();
List<Location> locList=(List<Location>)map.get("locListObj");
public List<Customer> getAllCustomers();
public List<Item> getAllItemsOfCust(int custId);
public List<Object[]> getIdAndNamesOnly();
List<Customer> custList=ht.find(hql, email);
public List<Customer> getAllCustomers() {}
public List<Item> getAllItemsOfCust(int custId){}

Q diff bw array.sort and collections.sort ? [remaining - search in net]


----------------------------------------------------------------------

Q What is Comparable and Comparator?


------------------------------------

**Note:-
Comparable mean -> for default natural sorting
Comparator mean -> for Customized sorting order

**Note:-

Default Natural Sorting order-> compulsory objects should Homogenuous and


Comparable (obj that impl Comaparable interface)

Wrapper classes and String class- is already impl Comparable interface

Q- what is Comparable ?
-----------------------
ans-it is interface present in java.lang package , used to Natural default sorting
order, it contain only one mehtod- compareTo().

ex it return 3 value
+ for above element
0 for same element
- for back element
if null -then null pointer excption.

Q- what is Comparator ?
-----------------------
-> it is interface present in java.util package.

->if we are not satified with Default Natural Sorting


or
not availble then we define our own Sorting order by using Comparator object.

->it contains 2 methods: 1 compare() 2 equals()

Note:-whenver we impl Comparator interface compulsory we should provide impl for


compare().
but
impl equals() method is optional , because its already in Object class
through inheritance.

Q- Diff bw Comparable and Comparator ?


--------------------------------------
ans:-
Comparable Comparator

1 in java.lang in java.util
2 for Defualt Natural Soring order for Customized Sorting
Order
3 one mehtod- compareTo() two method:- compare() ,
equals()

programme for Comparator:-[insert into string object treeset and order is reverse
of alphabatical]
----------------------------
ex:

import java.util.*;

class TreeSetDemo
{
Public static void Main(st[args])
{
TreeSet t = new TreeSet(new MyComparator());
t.add("Roja");
t.add("Sobha");
t.add("Ansual");

sop(t);
}
}

class MyComparator implements Comparator


{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=(String)obj2;

return s2.compareTo(s1);
}
}

Q how to travrse a collection using iterator [univeral]?


----------------------------------------------
we can interator to get object one by one from collection. and it applied for any
collection.it is universal.
we can able to perform read and remove operation
create by using interator() method of Collection interface
ex:- Iterator itr = c.iterator(); // c mean Collection object.

code:

import java.util.*;

class IteratorDemo
{
Public static void Main(str[args])
{
ArrayList L = new ArrayList();
for(int i=0; i<=10 ; i++)
{
L.add(i);
}

sop(L);

//now using Iterator()

Iterator itr = L.iterator();

while(itr.hasNext())
{
Integer i=(Integer)itr.next();
Sop(i)
}

}
}

Q diff bw enumerable iterator listIterator ?


----------------------------------------------
cursor in collection ?
------------------------------------------
ans:- to get obj one by one from collection use cursor
three cursor are there

1 Enumerator using -> element()


2 Iterator using -> iterator()
3 ListIterator using -> listiterator()

Q Diff bw
---------
Enumerator Iterator ListIterator

1 only for legacy classes -> any collection objects any


List objects

2 single directional -> single direction Bi-


Direction

3 only read -> Read and Remove Read ,


Remove, Replace and Add new object

Methods-> hasMoreElement(), nextElement(). hasNext(), next(), remove(),


9 mehtods

Q- Diff bw List , Set, Map ?


---------------------------------

List(i) [1.2v]:
===================
1- its child interface of collection interface.
2- duplicate are allowed
3- insertation order is preserved.
Note:- in 1.2v vector and stack classes are impl to impl List interface.

diag: Collection(i) [1.2]


|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]

---------------------------

3 : Set(i) :
-------------

diag: Collection(i) [1.2]


|
Set(i) [1.2]
|
----------------------------------------------------------
| |
HashSet(c) [1.2] SortedSet(i) [1.2]
| |
LinkedHashSet(c) [1.4] NavigableSet(i) [1.6]
|
TreeSet(c) [1.2]

3 : Set(i) :
------------
>- child interface of collecion,
>- duplicate not allowed
>- insertion order not preserved(save in diff order)

4 : SortedSet(i):
-----------------
>- its child of Set interface
>- without duplicate but according to some sorting order.

5 : NavigableSet(i):
--------------------
>- child interface of SortedSet.
>- it Define several method for Navigation purpose.

-------------------------------------

7 : Map(i) :
-----------
>Note:-its not child of any collection interface.
>used to represent a group of object as Key-value pairs
>duplicate key not allowed but value can be duplicate.

8 : SortedMap(i) :
------------------
> its child of Map interface
> used to represent group of objects as Key-value with some sorting order.
> sorting based on key but not based on value.

9 : NavigableMap(i) :
---------------------
its child of SortedMap
>it define several method for navigation purpose.

List Q:

->tell me all impl of list ?


-------------------------------
ans:

Collection(i) [1.2]
|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]

ARRAYLIST(I):
----------------------
**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations but
worst case if our operation is insertation or deletation in middile.(it
req several shift operation).
>underlying data structure for arraylist is "resizable array or growable array".
>duplicate allowed.
>insertion order is preserved.
>Heterogenous obj are allowed.
>null allowed.
*Note:- Except TreeSet and TreeMap everwhere heterogenuous object are allowed.

LinkedList:
---------------------
Note:-Best choice for our operation is - insertation or deletation in midile. but
worst choice for :- retrival.
>underlying data structur is "Double LinkedList"
>insertation order is preserved
>duplicate allowed
>hetero..obj is allowed.
>null is possible.

Note:- impl Serializable and Clonable interface but not RandomAccess interface.

VECTOR: [Every Method Syncronized]


-------------------
>Note:-best choice if our operation is retrival
but worst if our operation is insertation or deletation in midile.
>data structure is resizable or growable array.
>insertion order is preserved.
>duplicate allowed.
>null insertation is possible.
>impl Serializable, Clonable, and RandomAccess interface.
>vector is tread safe.->Every Method Syncronized inside vector.
STACK :
-----------------------
> its child of vector.
> specially designed for LIFO order.

Q what is diff bw arraylist and vector ?


------------------------------------------
ARRAYLIST VECTOR
-----------------------------------------------------------------------------------
--
1- every method inside arraylist is- non syncronized 1- syncronized

2- at a time- multithread allowed- so it is not thread safe. 2- thread safe

3- prformance is high 3- low-


becouse of thread waiting.

4- introduced in 1.2 4- introduced


in 1.0 (its legacy)

Q what is diff bw arraylist and linkedList ?


---------------------------------------------
ARRAYLIST(I):
----------------------
**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations but
worst case if our operation is insertation or deletation in middile.(it
req several shift operation).
>underlying data structure for arraylist is "resizable array or growable array".
>duplicate allowed.
>insertion order is preserved.
>Heterogenous obj are allowed.
>null allowed.
*Note:- Except TreeSet and TreeMap everwhere heterogenuous object are allowed.

LinkedList:
---------------------
Note:-Best choice for our operation is - insertation or deletation in midile. but
worst choice for :- retrival.
>underlying data structur is "Double LinkedList"
>insertation order is preserved
>duplicate allowed
>hetero..obj is allowed.
>null is possible.

Note:- impl Serializable and Clonable interface but not RandomAccess interface.

ArrayList LinkedList Vector


-----------------------------------------------------------------------------------
-----------------------------------------
DS-growable/resizable DS-double LinkedList Note:-
every thing is same Arraylist Allow duplicate allow
duplicate except-vector is syncronized
Order is preserved Order is preserved
Heterogeneous obj also allowed hetereogenous obj also allowed
[Enumeration element()]
null possible null is possible
Impl serializable,clonable and RandomAccess. impl only serializable and clonable
not RandomAccess
Best-sutaible for Retrival operation Best- insertation/deletion in middile

Note:- every collection class implements Serelizable and clonable interface.


and
ArrayList and Vector implement RandomAccess interface[java.util].

Set Q:-

Q what is diff bw list and set ?


---------------------------------
List(i) [1.2v]:
===================
1- its child interface of collection interface.
2- duplicate are allowed
3- insertation order is preserved.
Note:- in 1.2v vector and stack classes are impl to impl List interface.

Set(i) :
------------
>- child interface of collecion,
>- duplicate not allowed
>- insertion order not preserved(save in diff order)

Q what is deff bw hashset and treeset ?


---------------------------------------

HashSet: (for search operation)


---------------
>underlying datastructur is Hashtable.
>insertation order is not preserved and it is based on hashCode of Obects.
>Duplicate are not allowed . if we are trying then no CE, RE, only get boolean
False Return.
>Null insertion is allowed.
>Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.

>Best for search operation.

LinkedHashSet: [imp]
=======================
> its child class of hashset
> underlying data structur is combination of LinkedList and Hashtable.
> insertation order is preserved
> Duplicate are not allowed . if we are trying then no CE, RE, only get False
Return.
> Null insertation is allowed.
> Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.
> Best for search operation.
> it is exactally same as HashSet except following diff.

TreeSet:
------------------
> underlying Data Structure is balanced Tree.
> insertation order is not preserved and it is based on some Sorting order.
> Heterogenous objects are not allowed, if we are trying then we will get RE-
ClassCastException.
> null Insertion is allow (Only Once)
IMP NOTE:-> impl Serializable and Clonable interfaces but not RandomAccess
interface.

** DIFF BW:
-----------

PROPERTY | HashSet | LinkedHashSet |


TreeSet
-----------------------------------------------------------------------------------
-----------------
data structur | Hashtable | Hashtable and LinkedList |
Balanced Tree

Insertion order | Not preserved | Preserved | Not


preserved

Sorting order | not applicable | not applicable |


applicable

Heterogenous Objects | allowed | allowed |


not allowed

Duplicate Objects | not allowed | not allwed |


not allowed

null acceptance | allowed (only once) | allowed (only once) |


for empty Treeset as first element null is
posible, but in other case we will get:-npe

-----------------------------------------------------------------------------------
--------------------------------------------

Map Q:

Q does map impl collection interface ? why ?


---------------------------------------------
ans:- search in internete ?

Q what is main impl of map interface ?


--------------------------------------
Map(i) [1.2]
|

-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]

MAP(I):
===========
> map is not child of collection.
> if we want to represent a group of objects as a key-vlaue pairs then go for Map.
> Both key and values are objects only.
> Imp:->Duplicate Key not allwed but values can be duplicated.

ENTRY:=> Each key and value pair is called Entry.


ex: 101 durga => is one entry.

HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

LinkedHashMap:
-----------------
> its child class of HashMap.
> Note:- insertion order is preserved.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
> its exactally same as HashpMap except following differences

**IdentityHashMap:
------------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
>exactally same as HashMap except following diff.
1 in HashMap jvm will use .equals() to identify duplicate keys, which mean for
content comparision.
but
in IdentityHashMap jvm will use == operator to identify duplicate keys, which is
mean for reference comparision.

WeakHashMap :
---------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times).

>Exactally same as HashMap Except following Diff-

Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.

Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.

** SortedMap :
--------------
>its child interface of Map.
>it represent according some sorting order of keys.

METHODS:
--------
>SortedMap defines the following methods.

1 Object firstKey()
2 Object lastKey()
3 SortedMapheadMap(Object key)
4 SortedMaptailMap(Object key)
5 SortedMapsubMap(Object key1, Object key2)
6 Comparator comparator()

** TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.

**Hashtable :
--------------
>underlying data structur for Hashtable is Hashtable only.
>Duplicate keys are not allowed. but values can be duplicate.
>insertion order is not preserved and its based on Hashcode of the keys.
>Heterogenous objects are allowed for both keys and values.
>null insertion is not posible for both key and values. we get :-NPE.

Note:-every method inside Hashtable is -syncronized so hashtable is tread safe.

Properties:
==============
>it is child class of Hashtable.
use Properties Object to hold Properties which are comming from Properties File.
>if anything which changes frequently (like DB username, password, urls etc) never
Recommended to Hard Code in prog.
bcoz for every changes in source file we have to Recompile, Rebuild and
Redeploying apps and some times server restart also req.

* To Overcome this problum we have to Configur such type of Properties in


Properties File.
the main advantage of this approach is if there is a change in Properties file,
then to Reflect that changes just Redeployment is Enough.

Q diff bw hashmap and treemap and hashtable ?


-----------------------------------------------

HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.

**Hashtable :
--------------
>underlying data structur for Hashtable is Hashtable only.
>Duplicate keys are not allowed. but values can be duplicate.
>insertion order is not preserved and its based on Hashcode of the keys.
>Heterogenous objects are allowed for both keys and values.
>null insertion is not posible for both key and values. we get :-NPE.

Note:-every method inside Hashtable is -syncronized so hashtable is tread safe.

or
diff bw HashMap, LinkedHashMap , TreeMap ?
-----------------------------------------------
HashMap LinkedHashMap
TreeMap

1 DS-HashTable Ds-Hashtable and Linkedlist Ds-


Red Black Tree

2 duplicate key not allowed but value allowed ||


||

3 order is not preserved order is preserved order


is not preserved
but it is based on hashcode of keys. but its
based on some sorting order of keys
[if we depend on DNS
order then keys should be
Homo..and Comparable
else get-
ClassCastException ]
[if our own sorting
order then keys can be]
Heterogenous and Non-
Comparable ]

4 null allow for key (once) [Other exact same as HashMap]


null allow for key as first entry else NPE
for value multiple

5 heterogenous obj allow for both K,V.

Q-diff bw HashMap and HashTable ?


----------------------------------
ans:-
HashMap HashTable

1 not syncronized every method is syncronized.

2 not thread safe thread safe

3 performance high low

4 1.4 legacy 1.0

Q diff bw hashmap, linkedhashmap , treemap ?


---------------------------------------------

diff bw HashMap, LinkedHashMap , TreeMap ?


-----------------------------------------------
HashMap LinkedHashMap
TreeMap

1 DS-HashTable Ds-Hashtable and Linkedlist Ds-


Red Black Tree

2 duplicate key not allowed but value allowed ||


||

3 order is not preserved order is preserved order


is not preserved
but it is based on hashcode of keys. but its
based on some sorting order of keys
[if we depend on DNS
order then keys should be
Homo..and Comparable
else get-
ClassCastException ]
[if our own sorting
order then keys can be]
Heterogenous and Non-
Comparable ]

4 null allow for key (once) [Other exact same as HashMap]


null allow for key as first entry else NPE
for value multiple

5 heterogenous obj allow for both K,V.

Q how to decide hashmap and treemap ?


-------------------------------------
hashmap vs treemap ?
------------------------
Hashmap TreeMap
1 DS-HashTable =>Ds- Red Black Tree
2 duplicate key not allowed but value allowed =>duplicate key not allowed but
value allowed
3 order is not preserved =>order is not preserved
=>but its based on some sorting order of keys
[if we depend on DNS order then keys should be
Homo..and
Comparable else get-ClassCastException ]
[if our own sorting order then keys can be]
Heterogenous and Non-Comparable ]
4 null allow for key (once)for value multiple =>null allow for key as first entry
else NPE
5 heterogenous obj allow for both K,V.

Q what happen if for same key multiple value added in hashmap ?


-----------------------------------------------------------------
ans:- see in internate

Q can we add more than one null keys in hashmap?


------------------------------------------------
No- see in net .

Q how to iterate hashmap ?


-------------------------
ex:

import java.util.*;

class HashMapDemo
{
Public static Void main(st[args])
{
HashMap m = new HashMap();
m.put("Chiru" , 300);
m.put("Bala" , 500);
m.put("Ashish" , 400);

sop(m); //
Collection c=m.values();
sop(c);
Set s1=m.entrySet();

Iterator itr = s1.iterator();


while(itr.hasNext())
{
Map.Entry m1 = (Map.Entry)itr.next();
sop(m1.getKey() + "---------"+m1.getValue());

or if(m1.getKey().equals("Naag"))
{
m1.setValue(1000);
}
}
sop(m);
}
}

Q how to measure the performance of hashmap ?


-----------------------------------------------
ans:- see in internet

Q Treemap and treeset ? where to use ?


---------------------------------------

TreeSet:
------------------
> underlying Data Structure is balanced Tree.
> insertation order is not preserved and it is based on some Sorting order.
> Heterogenous objects are not allowed, if we are trying then we will get RE-
ClassCastException.
> null Insertion is allow (Only Once)
IMP NOTE:-> impl Serializable and Clonable interfaces but not RandomAccess
interface.

TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.

Q how to convert map to list ?


------------------------------
ans- see in internate

Q How internally hashing works?


------------------------------
ans:- see in internate

Q how hash map internally work ?


--------------------------------
ans:- internate

Q If I want to make user defined class as a key within HashMap then which methods
do I need to override?
equals() and hashCode().
-----------------------------------------------------------------------------------
----------------

Q can i store duplicate value or key in hashmap ?


-------------------------------------------------
ans:- see above

Q diff bw hashmap and treehashmap ?


------------------------------------
see above

Q- diff bw hashmap and weakhashmap ?


------------------------------------

HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

WeakHashMap :
---------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times).

>Exactally same as HashMap Except following Diff-

Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.

Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.

Q what is concurrenthashmap ? how it work ?


-------------------------------------------
ans:-

Concurrent collections :
---------------------------
1 Concurrent collections are thread safe
2 performance is more because of diff Locking Mechanism.
3 while one thread interacting collection the other thread allowed to modify
collection in safe manner.

ConcurrentHashMap(C):
=====================
> underlying data structur is Hashtable
>ConcurrentHashMap allows Concurrent Read and Thread safe update operations.
to perform Read operation thread will not require any Lock. but
to perform update operation thread requires Lock but it is lock of a perticular
part of Map.
Note:- instead of whole Map concurrent update achived by internally dividing Map
into smaller Portion which is defined by
Concurrency Level.

> the default concurrency level is 16.


Note:- that is ConcurrentHashMap allows simultanceous Read operation and
simultancously 16 Write(Update) operations.
> null is not allowed for both Keys and Values.

Note:- while one thread iterating , the other thread can perform update operation
and ConcurrentHashMap never threw ConcurrentModificationException

Q what is diff bw hashmap and concurrenthashmap ?


--------------------------------------------------

HashMap ConcurrentHashMap
-----------------------------------------------------------------------------------
---------------------------------------
1 not thread safe 1 thread safe
2 performance is high, not req to thread wait 2 performance is low, req
to thread wait.
3 while one thread iterating , other thread not allowed to modity.
3 while one thread iterating , other
thread allowed to modity.

4 Iterator of HashMap is Fail-Fast and its throws ConcurrentModificationException.


4 Iterator of ConcurrentHashMap is Fail-
Safe and its will not throws
ConcurrentModificationException.

5 null is allowed for both keys and values 5 null is not allowed for
both keys and values-get=>NPE

6 introduce in 1.2 v 6 introduce in 1.5 v

-----------------------------------------------------------------------------------
--------------------------------------

Q What is difference between HashSet and HashMap ?


--------------------------------------------------
HashSet: (for search operation)
---------------
>underlying datastructur is Hashtable.
>insertation order is not preserved and it is based on hashCode of Obects.
>Duplicate are not allowed . if we are trying then no CE, RE, only get boolean
False Return.
>Null insertion is allowed.
>Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.
>Best for search operation.

HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

Q How internally hashing works?


-------------------------------
ans:- search internat

Q hashmap and weakhashmap ?


---------------------------

** HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)

weakhashmap :
-------------
>Exactally same as HashMap Except following Diff-
Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.

Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.

Q where we are using security in our project and what kind of security is it?
------------------------------------------------------------------------------
ans:
we use filter security for User Login and
CODEC(Base64) security for Customer Operations using EDI.

filter security:-
what is Filters-> o A Filter is an interface. It provides request & response
filtering before processing.
o It works based on Servlet URL matching.
o Filter should be configured in web.xml, using Servlet URL pattern. It can /*
also to specify all request filtering.
o Filter also contains life-cycle methods
1. init()
2. doFilter()
3. destroy()
o init() and destroy() are executed only one time.
o Filter supports init parameters from web.xml

Creating security filter for session management


Step 1
Define a filter class and configure in web.xml that should filter all
DispatcherServlet request
( i.e. use filter url as /mvc/* ).
Step 2
Provide init-param�s which doesnot required session check.
Step 3
Read all init-param�s into filter and store in List object.
Step 4
In doFilter() method, get current URI using with the request.getRequestURI()
and check this with avoid url list.
o If available, then skip session check.
o Else check session and return to home page.
o Here, we can also enable cache clear and this will be executed on
invalidation of session. ( also disables back button ).

//disable back button


res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", 0);

Q diff bw hashmap and treehashmap ?


-----------------------------------
Map Overview

There are 4 commonly used implementations of Map in Java SE - HashMap, TreeMap,


Hashtable and LinkedHashMap.
HashMap is implemented as a hash table, and there is no ordering on keys or values.

TreeMap is implemented based on red-black


tree structure, and it is ordered by the key.

or

The main difference between HashMap and TreeMap actually reflect the main
difference between a Hash and a Binary Tree , that is, when iterating, TreeMap
guarantee can the key order which is determined by either element's compareTo()
method or a comparator set in the TreeMap's constructor.

or
HashMap is implemented as a hash table, and there is no ordering on keys or values.

TreeMap is implemented based on red-black tree


structure, and it is ordered by the key. ...
Hashtable is synchronized, in contrast to HashMap.

or
HashMap on the other hand, makes no such guarantee. Therefore, when iterating over
the keys of a HashMap, you can't be sure what order they will be in.
TreeMap is an example of a SortedMap, which means that the order of the keys can be
sorted, and when iterating over the keys, you can expect that they will be in
order.

HashMap will be more efficient in general, so use it whenever you don't care about
the order of the keys.
or
HashMap only works with objects with a suitable hashCode() implementation. TreeMap
only works with Comparable objects,

or

HashMap allows null key and null values (Only one null key is allowed). If TreeMap
uses natural ordering or its comparator, does not allow null keys, an exception
will be thrown.

or

HashMap is used for fast lookup, whereas TreeMap is used for sorted iterations over
the map.

The HashMap is a general purpose Map (hash table data structure), which should be
used whenever you need a hashing-based data structure for storing your mappings
(key-value pairs).
or
TreeMap is a Red-Black tree based NavigableMap implementation provides you sorting,
on top of hashing offered by Map interface.
or
HashMap: Lookup-array structure, based on hashCode(), equals() implementations,
O(1) runtime complexity for inserting and searching, unsorted
TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime
complexity for inserting and searching, sorted

or
HashMap -- implement basic map interface
implemented by an array of buckets, each bucket is a LinkedList of entries
running time of basic operations: put(), average O(1), worst case O(n), happens
when the table is resized; get(), remove(), average O(1)
not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new
HashMap(...));
Iteration order of the map is unpredictable.
TreeMap -- implement navigable map interface
implemented by a red-black tree
running time of basic operations: put(), get(), remove(), worst case O(lgn)
not synchronized, to synchronize it: SortedMap m =
Collections.synchronizedSortedMap(new TreeMap(...));
provide ordered iteration. higherKey(), lowerKey() can be used to get the successor
and predecessor of a given key.
or
When to Prefer TreeMap over HashMap :-
1. Sorted elements are required instead of unordered elements. The sorted list
return by TreeMap is always in ascending order.
2. TreeMap uses Red-Black algorithm underneath to sort out the elements . When one
need to perform read/write operations frequently , then TreeMap is a good choice.

Q-Differences Between wait() And sleep() Methods In Java :


----------------------------------------------------------
Both wait() and sleep() methods are used to pause the execution of current thread
for some period of time. Whenever a thread calls wait() method, it goes into
WAITING state after releasing the lock it holds. Whenever a thread calls sleep()
method, it goes into TIMED_WAITING state without releasing the lock it holds.
A thread which is in WAITING state (state after calling wait() method) can be woken
up by other threads by calling notify() or notifyAll() methods on the same lock.
But, a thread which is in TIMED_WAITING state (state after calling sleep() method)
can not be woken up. If any threads interrupt sleeping thread, InterruptedException
will be raised.
wait() method along with notify() and notifyAll() are used for inter thread
communication where as sleep() method is used to pause the execution of current
thread for specific period of time.
wait() method is an instance method of java.lang.Object class. That means, this
method is available in all objects you create in java. Where as sleep() method is a
static method of java.lang.Thread class. That means, it is available only in
threads.
wait() method is called on objects. Whenever it is called by a thread on a
particular object, thread releases the lock of that object and waits until other
threads call either notify() or notifyAll() methods on the same object. Where as
sleep() method is called on threads.
Whenever sleep() method is called, only current thread is going for sleep. For
example, if main thread calls sleep() method on a thread t, i.e t.sleep(), main
thread itself is going to sleep not thread t.
To call wait() method, calling thread must hold the lock of the object on which it
is calling wait() method. That means, wait() method must be called within the
synchronized block. Where as to call sleep() method, thread need not to hold the
object lock. That means, sleep() method can be called outside the synchronized
block also.
Below is the quick recap of above points.

wait() sleep()
The thread which calls wait() method releases the lock it holds. The thread which
calls sleep() method doesn�t release the lock it holds.
The thread regains the lock after other threads call either notify() or notifyAll()
methods on the same lock. No question of regaining the lock as thread doesn�t
release the lock.
wait() method must be called within the synchronized block.sleep() method can be
called within or outside the synchronized block.
wait() method is a member of java.lang.Object class. sleep() method is a member of
java.lang.Thread class.
wait() method is always called on objects. sleep() method is always called on
threads.
wait() is a non-static method of Object class. sleep() is a static method of
Thread class.
Waiting threads can be woken up by other threads by calling notify() or notifyAll()
methods. Sleeping threads can not be woken up by other threads. If done so,
thread will throw InterruptedException.
To call wait() method, thread must have object lock. To call sleep() method,
thread need not to have object lock.

Q Difference between collection and collections.


-------------------------------------------------
ans:-
Both are belongs to java.util package
=>collection is an interface , can be used to represent a group of individual
object as a single entity where as
collections is an utilityclass, present in java,util package,to define several
utility methods for collections
The Collection interface only used to store group of objects into a single
Collection object. On the other hand Collections class is used to perform some
operation on object of Collection.

I. Collection is an interface in Java. But Collections is a class in Java.


II. Collection defines methods that are used for data structures that contain the
objects. Collections defines the methods that are used for operations like
access, find ,max, search

Collection is base interface for list set and queue.


Collections is a class and it is called utility class.
Collections utility class contains some predefined methods so that we can use while
working with Collection type of classes(treeset, arraylist, linkedlist etc.)

Collection interface consist of many sub-interfaces like as List, Set, Queue


whereas
Collections class consist of many static utility methods like sort(), reverse (),
synchronisedCollection() etc.

-----------------------------------------------------------
program to sort an array with some specific scenarios ?

import java.util.Scanner;

class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)


array[c] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

for (c = 0; c < n; c++)


{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}

or
Java version of this program is given bellow :

public class Search_Ele {


public static void main(String[] args){
int[] array={11,-10,25,18,45,55,30,87,-28,18};

System.out.println("The contents of the Array are :");

for(int i=0;i<array.length;i++)
System.out.println("Array[" + i + "] = " + array[i]);

int search_element=55;
int find_index=-1;

for(int j=0;j<(array.length-1);j++){
if(array[j]==search_element){
find_index=j;
break;
}
}

if(find_index!=-1){
System.out.println(" The search element is : " + search_element);
System.out.println(" It is found in the array at position : " +
find_index);
}

else
System.out.println("\n The search element is not found in the array.");
}
}

or

Write a Java program to search an element in an array using linear search


algorithm.

ans
Java program to search an element in an array
package com.tcc.java.programs;

import java.util.*;
public class ArrayLinearSearch {
public static void main(String args[]) {
int count, num, i;
int[] inputArray = new int[500];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");


count = in.nextInt();
System.out.println("Enter " + count + " elements");
for(i = 0; i < count; i++) {
inputArray[i] = in.nextInt();
}

System.out.println("Enter element to search");


num = in.nextInt();
// Compare each element of array with num
for (i = 0; i < count ; i++) {
if(num == inputArray[i]){
System.out.println(num+" is present at index "+i);
break;
}
}

if(i == count)
System.out.println(num + " not present in input array");
}
}
Output
Enter number of elements
6
Enter 6 elements
3 8 7 2 9 4
Enter element to search
7
7 is present at index 2
Enter number of elements
7
Enter 7 elements
3 8 12 8 11 0 -4
Enter element to search
5
5 not present in input array

and

Q5: selection sort vs heap sort ?


---------------------------------
ans:-
Selection Sort in Java

We can create a java program to sort array elements using selection sort.
we search for the lowest element and arrange it to the proper location. We swap the
current element with the next lowest number.
ex:
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

selectionSort(arr1);//sorting array using selection sort

System.out.println("After Selection Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}
Output:

Before Selection Sort


9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58

=================================================================
colls
----

---
AD
---

Q how to change port no of tomcate server ?


-------------------------------------------
ans:- in 2 way we can change

1- manually:- goto->[apache installation root directory] Apache Software


Foundation home folder -> tomcate7.0->
-> conf -> open 'server' file -> search port -> <connector
port="8080"> change this . now run server.

2- using eclipse:- r-click on 'server [below]' -> open / F3 -> goto Port menu ->
select -> HTTP/1.0- port- change port
-> then cancel tabe from and it will ask to save then yes.
-----------------------------------------------------------------------------------
---------

Q how to host/deploy application in apache tomcate ?


ans:-Apache Tomcat is used to deploy your Java Servlets and JSPs.
So in your Java project you can build your WAR (short for Web ARchive) file,
and just drop it in the deploy directory in Tomcat.

Tomcat is a Servlet and JSP Server serving Java technologies

Deploy method #1: copying web application archive file (.war)


-------------------------------------------------------------
In this method, the web application is packed as a WAR file.
You may generate the WAR file using a tool or IDE like Eclipse,
WAR file (Web Application Resource or Web application ARchive) is a JAR file used
to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML
files, tag libraries, static web pages

1-Copy the .war file (E.g.: project.war) to %CATALINA_HOME%\webapps ( E.g.: C:\


tomcat\webapps )
2-Run %CATALINA_HOME%\bin\startup.bat
Your .war file will be extracted automatically to a folder that has the same name
(without extension) (E.g.: project)
3-Go to %CATALINA_HOME%\conf\server.xml and take the port for the HTTP protocol.
<Connector port="8080" ... />. The default value is 8080.
Access the following URL:

[<protocol>://]localhost:<port>/folder/resourceName

or

1-Copy the WAR file into -> "$CATALINA_HOME\webapps" directory.

2-Restart the server.


[Whenever Tomcat is started, it will unpack the WAR file it found in the webapps
directory and launch the application in that manner.]

NOTE:-Later if you want to update changes for the application, you must both
replace the WAR file and delete the application�s unpacked directory, and then
restart Tomcat.

Deploy method #2: using Tomcat�s manager application


----------------------------------------------------
type the following URL into your web browser�s address bar (the port number may
vary, depending on your server�s configuration):

Using the manager application, you can:


Deploy a new web application either by uploading a WAR file or supplying
a directory on the server.
View a list of applications deployed on the server and their status.
Start, stop and restart an individual application.
Undeploy an individual application.

Q jee architecture ?
------------------------
ans - ecplain self

Q what implicit object and how many in servlet ?


------------------------------------------------
These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables.

Following table lists out the nine Implicit Objects that JSP supports -
S.No. Object & Description
1 request
This is the HttpServletRequest object associated with the request.

2 response
This is the HttpServletResponse object associated with the response to the client.

3 out
This is the PrintWriter object used to send output to the client.

4 session
This is the HttpSession object associated with the request.

5 application
This is the ServletContext object associated with the application context.

6 config
This is the ServletConfig object associated with the page.

7 pageContext
This encapsulates use of server-specific features like higher performance
JspWriters.

8 page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.

9 Exception
The Exception object allows the exception data to be accessed by designated JSP.

or
==
A list of the 9 implicit objects is given below:

Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable

Q diff bw generic servlet and httpservlet ?


-------------------------------------------
Generic Servlet:
GenericServlet class is direct subclass of Servlet interface.
Generic Servlet is protocol independent.It handles all types of protocol like
http, smtp, ftp etc.
Generic Servlet only supports service() method.It handles only simple request
public void service(ServletRequest req,ServletResponse res ).
Generic Servlet only supports service() method.
GenericServlet is Stateless

HttpServlet:
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is protocol dependent. It handles only http protocol.
HttpServlet supports public void service(ServletRequest req,ServletResponse res )
and protected void service(HttpServletRequest req,HttpServletResponse res).
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.
HttpServlet is Stateful.

Q when we go for context and when for session [servlet] ?


---------------------------------------------------------
ans- see in internet

spring
======
Q spring structure folder with maven ?
--------------------------------------

Q what mean by loose coupling ?


--------------------------------

Q what is auto-wiring and drowback of wiring ?


-----------------------------------------------
ans:
automatically inject the depedent, so no need to write xml.
drowback- it will not inject primitive and collection.
type of vars -primitive, collection, ref.

Q xml and annotation ?


----------------------
and:- annotation convert to again xml so it take more time. so xml is better for
performance
for fast development annotation

Q how to read xml file , spring container ?


-------------------------------------------
ans:-through dom parser that is provided by container.

Q what is use @qualifer ?


--------------------------
ans:-
Spring @Qualifier Annotation. There may be a situation when you create more than
one bean of the same type and want to wire only one of them with a property. In
such cases, you can use the @Qualifier annotation along with @Autowired to remove
the confusion by specifying which exact bean will be wired.

Q what is @modelattribute. why we use ?


---------------------------------------
ans:-to get the model value in controller.
controller return only model but in controller model classes provided by this
model.

Q what is @requestparameter, why use ?


--------------------------------------
ans:-it is used to read requested form parameter data.

Q how many injection are in spring ?


------------------------------------
ans:- setter, getter, interface

Q when we should go for setter and constructor ?


------------------------------------------------

Q Difference between BeanFactory and ApplicationContext.


---------------------------------------------------------
Q What is dependency injection? More places people don't know what is need of
dependency injection and
-----------------------------------------------------------------------------------
-------------------
why to use, we need to explain them.
------------------------------------

Q Spring MVC architecture.


---------------------------
Q how to controller get req from dispatcherservlet ?-imp
or how controller sent this req to valid or match with method ?-imp
-----------------------------------------------------------------------
ans:-we define @controller and appropriate @path("reg")
for matched method we define @path.

Q AOP (what is joinpoint, pointcut and advice).


-----------------------------------------------
Q spring hibernate integration ?
ans:- 1-hibernate template

Q spring MVC work flow ? how recognize view extenstion if i want to go for html ?
---------------------------------------------------------------------------------
ans:-viewresolver resolve take this responsibility.

Q can i configure 2 extenstion ?


--------------------------------
ans-yes, we can configur, and we will provide condition to go another .extension

Q what is the architecture of MVC? work flow?


---------------------------------------------

Q how to read the data from controller/Model class ?


----------------------------------------------------
ans:-using @requestparameter we read the form data in controller.

Q how to bind/write form data/ jsp form data to controller ?


------------------------------------------------------------
ans- request.getParameter method is used to get data in controller then parse it.

Q can we develop spring apps without spring confing file ?


---------------------------------------------------------
ans- yes,using annotation

Q- @component ?
-------------

Q- spring scopes ?
------------------

Q- how to read data in jsp from controller ?


--------------------------------------------
ans- jstl tags

Q-@repository
--------------

Q-what stereotype annotype ?


----------------------------

Q What is transaction?
----------------------

Q what will we use to provide security in controller?


-----------------------------------------------------
ans: codec and decode
spring security or servletfilter

Q where we are using security in our project and what kind of security is it?
1- two spring security read......

Q what are util classes in your project?


----------------------------------------

Q how to call stored procesure in spring using jdbc ?


-----------------------------------------------------

Q what you used for versioning tool - git/svn ?


----------------------------------------------

Q why we require dependency injection? if it is used to create object then why we


are not going for new keyword?
ans:- not requier to developer write and container work based on beans with requier
properties like init...post init..

what is the drawback of creating direct object of another class by using HAS-A
relation?

Q different scopes of spring with definition? what is difference between singleton


and prototype? when objects will create?
-----------------------------------------------------------------------------------
-----------------------------------------

Q diff view objects in spring ?


-------------------------------
ans- jsp by default

Q which is best- xml or annotation based configuration ?


--------------------------------------------------------

Q Can we use multilple xml file ?


ans-yes we can use , if it large then make diff and give parent child.or
hibernate or xml

Q how to identify request data and in which form data comming ?


----------------------------------------------------------------
ans:-
************************************[ MIX ]**************************************
********

Q Query and criteriain hibernate?


----------------------------------
ans:-
[**Query / HQL***]

Hibernate Query Language (HQL)


(HQL) is an object-oriented query language,HQL is same as SQL but it doesn't
depends on the table of the database.
HQL is the own query language of hibernate and it is used to perform bulk
operations on hibernate programs
An object oriented form of SQL is called HQL
Instead of table name, we use class name in HQL.
So it is database independent query language.

Advantage of HQL-
database independent
supports polymorphic queries

Query Interface
---------------
The object of Query can be created by createQuery() method of Session interface.
ex:-to get all the records
Query query=session.createQuery("from Emp");
List list=query.list();

[*****criteria :-***]

Hibernate provides three different ways to retrieve data from database.


HQL
Criteria and
native SQL queries.

HCQL (Hibernate Criteria Query Language)


The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on
the specific criteria.
such as retreiving all the records of table whose salary is greater than 50000 etc

The Hibernate Session interface provides createCriteria() method, which can be used
to create a Criteria object.
use add() method to add restriction for a criteria query.

Criteria Interface:-
The Criteria interface provides many methods to specify criteria. The object of
Criteria can be obtained by calling the createCriteria() method of Session
interface.

Crietria c=session.createCriteria(Emp.class); //passing Class class argument


List list=c.list();

example to add a restriction to return the records with salary is equal to 2000 -
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();

Projections & Aggregations :-


The Criteria API provides Projections class, which can be used to get average,
maximum, or minimum of the property values.
ex:- To get average of a property.
cr.setProjection(Projections.avg("salary"));

ex:-To get maximum of a property.


cr.setProjection(Projections.max("salary"));
HCQL with Projection:-
We can fetch data of a particular column by projection such as name
Criteria c=session.createCriteria(Emp.class);
c.setProjection(Projections.property("name"));
List list=c.list();

Q-Difference between HQL and Criteria Query in Hibernate ?


----------------------------------------------------------
1-HQL is to perform both select and non-select operations on the data,
but Criteria is only for selecting the data, we cannot perform non-select
operations using criteria

2-HQL is suitable for executing Static Queries,


where as Criteria is suitable for executing Dynamic Queries

3-HQL doesn�t support pagination concept, but we can achieve pagination with
Criteria
4-Criteria used to take more time to execute then HQL

5-Criteria we are safe with SQL Injection because of its dynamic query generation
but in HQL as your queries are either fixed or parametrized, there is no safe
from SQL Injection.
**Note:-

createQuery -- is for hibernate querying which provides you independent querying


which makes you run that on many databases using API and more other advantages.
createCriteria -- is better to use for simple querying on db because of it's
simplicity and conditions.
createSQLQuery -- is for native sql querying which is selected by you with jdbc
driver cfg or something else

Q what is use @qualifer ?


-------------------------
@Autowired to remove the confusion by specifying which exact bean will be wired.
@Qualifier annotation � This annotation is used to avoid conflicts in bean mapping
and we need to provide the bean name
There may be a situation when you create more than one bean of the same type (mean
fully qualified name same but bean id or name diff with diff implementation)and
want to wire only one of them with a property. In such cases, you can use the
@Qualifier annotation along with @Autowired to remove the confusion by specifying
which exact bean will be wired.
or
if two similar beans are declared in bean configuration file. Will Spring know
which bean should autowired?
@Quanlifier to tell Spring about which bean should autowired.

Q what is @modelattribute. why we use ?


---------------------------------------
@ModelAttribute refers to a property of the Model object (the M in MVC).
The primary objective of this annotation is to bind the request parameters or form
fields to a model object.
@ModelAttribute annotation can be used in following ways.
It can be used to pass data to JSP before it loads.
This ensures that the JSP has all the data which are required to display itself.
The injection of data is achieved by binding an Object with the Model and pass it
to the JSP.
It can also be used to receive data in Controller from form fields.

@ModelAttribute is an annotation that binds a method parameter or method return


value to a named model attribute and then exposes it to a web view.

@ModelAttribute annotation is used as part of a Spring MVC web app and can be used
in two scenarios.
Firstly, it can be used to inject data objects before a JSP loads. ...
Secondly, it can be used to read data from an existing model assigning it to
handler method parameters.

Q @autowire, why use ?


-----------------------
@Autowired annotation can be used to autowire bean on the setter method,instance
variable, and constructor.
Spring @Autowired annotation is used for automatic dependency injection.
Spring framework provides autowiring features too where we don�t need to provide
bean injection details explicitl
The @Autowired annotation is auto wire the bean by matching data type.

Q what is @requestparameter, why use ?


------------------------------
@RequestParam annotation used for accessing the query parameter values from the
request. Look at the following request URL:

http://localhost:8080/springmvc/hello/101?param1=10&param2=20
In the above URL request, the values for param1 and param2 can be accessed as
below:

public String getDetails(@RequestParam(value="param1", required=true) String


param1,
@RequestParam(value="param2", required=false) String
param2)
{
...
}
@RequestParam:
@RequestParam automatically binds the request parameters to the arguments of your
handler method. It also provides auto type conversion for some standard type like
int, long, float, string, date etc.

@RequestParam used for accessing the values of the query parameters


We can use @RequestMapping with @RequestParam annotation to retrieve the URL
parameter and map it to the method argument. For example:
public String method9(@RequestParam("id") int id){
return "method9 with id= "+id;
}
Q how many injection are in spring ?
-------------------------------------
DI / IOC :
----------
DI container or fw assigns values to resouce or obj dynamically is called DI.
here depedent value pushed to resource.

IOC (Inversion of control) -

Inversion of control means the way of managing the dependency the dependent object
will be injected to the target object
it is inverse process of managing the dependency that�s it is called Inversion of
control.
spring we can achieve inversion of control by configuring the spring bean in
�spring bean configuration file�.
? If spring framework is creating the object and establish the dependency with
other objects we call it as inversion of control.
? If spring need to take care of creating the object and establishes the dependency
we need to configure the spring bean in spring bean configuration
file(applicationContext.xml).

1 Setter Injection:
When the dependent object will be injected in to target object via setter method
then it is called setter injection.

2 Constructor Injection:
When the dependent object will be injected in to target object via constructor then
it is called constructor injection.

Difference between Setter and Constructor injection:

Constructor
1. In constructor injection the dependent object will be created and injected
while creating the target object through constructor. Means we can access the
dependent object in constructor of target object.

In setter injection the dependent object will be injected after the target object
will be created means we can�t access the dependent object in constructor.

2 Constructor injection is mandatory because it will not create the object until we
pass something to the constructor. Means if we want injection is mandatory then we
can use constructor.
Setter injection is optional means without setting the property tag also we can
create the objects.

Spring supports 2 types of dependency injection, they are:


1) Constructor-based dependency injection: It is accomplished when the container
invokes a class constructor with a number of arguments, each representing a
dependency on other class.
2) Setter-based dependency injection: It is accomplished by the container calling
setter methods on your beans after invoking a no-argument constructor or no-
argument static factory method to instantiate your bean.

Q- when we should go for setter and constructor ?


--------------------------------------------------
1- if bean class contains only one property
or
if all properties should participate in Depedency injeciton then go for
Constructor Injection.
because const injeciton is faster.

2- if bean class contains more than one properties and there is no need to making
all properties participating in depedency injection
then go for Setter injection

Q-DIFF BW Setter and Constructor injection?


------------------------------------------

Setter Constructor
-----------------------------------------------------------------------------------
------------------------------------------------
1- <property> tag is required 1- <constructor-arg> tag
is required
2- inject after creating bean so its delay 2- inject while
creating bean so no delay
3- support cyclic DI 3- no support
4- to n no setter n no of setter is req 4 to n no of
const , n no of const not req
5- if all properties are configured then container use 0 param const 5- if any
any property is configured container use
parameterized cosnt
6 Setter injection is optional means
without setting the property tag also we can create the objects.
6 Constructor injection is
mandatory because it will not
create the object until we pass something to the constructor.

Q what is diff bw save, and merge method in hibernate ? [modify again]


-------------------------------------------------------
save:
Persists an entity. Will assign an identifier if doesn't exist. If exist it's
essentially doing an update. Returns the generated ID of the entity
hibernate save() can be used to save entity to database. We can invoke this method
outside a transaction, that�s why I don�t like this method to save data. If we use
this without transaction and we have cascading between entities, then only the
primary entity gets saved unless we flush the session.

merge:-
merge can be used to update existing values, however this method create a copy from
the passed entity object and return it. The returned object is part of persistent
context and tracked for any changes, passed object is not tracked. This is the
major difference with merge() from all other methods.

Merge: Suppose we are creating a session and load an employee object. Now object in
session cache. If we close the session at this point and we edit state of object
and tried to save using update() it will throw exception. To make object persistent
we need to open another session. Now we load same object again in current session.
So if we want to update present object with previous object changes we have to use
merge() method. Merge method will merge changes of both states of object and will
save in database.
Merge:-> if you want to save your modifications at any time with outknowing about
the state of an session, then use merge() in hibernate.
If we call merge() method, then it verifies whether the same object is existed in
the cache or not. If the object is existed in the cache then changes are copied in
to the cache. other wise it will load the values to cache.Hence it doesn�t throw
any exception

METHOD � TRANSIENT � DETACHED �


�--------------+-------------------------------+--------------------------------�
� � sets id if doesn't � sets new id even if object �
� save() � exist, persists to db, � already has it, persists �
� � returns attached object � to DB, returns attached object �
�--------------+-------------------------------+--------------------------------�
� � sets id on object � throws �
� persist() � persists object to DB � PersistenceException �
� � � �
�--------------+-------------------------------+--------------------------------�
� � � �
� update() � Exception � persists and reattaches �
� � � �
�--------------+-------------------------------+--------------------------------�
� � copy the state of object in � copy the state of obj in �
� merge() � DB, doesn't attach it, � DB, doesn't attach it, �
� � returns attached object � returns attached object �
�--------------+-------------------------------+--------------------------------�
� � � �
�saveOrUpdate()� as save() � as update() �
� � � �
+-------------------------------------------------------------------------------+

Q what is diff get and load in hibernate ?


-------------------------------------------
1. session.load()
=>return a �proxy� without hitting the database.
whats the meaning of proxy object ?
Proxy means, hibernate will prepare some fake object with given identifier value in
the memory without hitting the database,
=>load() throws exception when data is not found
=>Use this method if it is sure that the objects exist.

2. session.get()
It always hit the database and return the real object, an object that represent the
database row, not proxy.
If no row found , it return null.
Use this method if it is not sure that the objects exist.

Q JSTL tags?
------------
ans:- see in internet
Q tell me JDBC steps ?
----------------------
There are 5 steps to connect any java application with the database in java using
JDBC. They are as follows:

1-Register the driver class


ex: Class.forName("oracle.jdbc.driver.OracleDriver");

2-Creating connection:
ex:Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pas
sword");

3-Creating statement:
Statement stmt=con.createStatement();

4-Executing queries
ex:
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5-Closing connection
ex: con.close();

--------------------

Creating JDBC Application


There are following six steps involved in building a JDBC application -

Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.

Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.

Open a connection: Requires using the DriverManager.getConnection() method to


create a Connection object, which represents a physical connection with the
database.

Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.

Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.

Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Q collection herairchy ?
-----------------------
and:-

diag: Collection(i) [1.2]


|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]

---------------------------

3 : Set(i) :
-------------

diag: Collection(i) [1.2]


|
Set(i) [1.2]
|
----------------------------------------------------------
| |
HashSet(c) [1.2] SortedSet(i) [1.2]
| |
LinkedHashSet(c) [1.4] NavigableSet(i) [1.6]
|
TreeSet(c) [1.2]

Map(i) [1.2]
|

-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]
Q prepaired , connection , what these are class or interface in jdbc ?
----------------------------------------------------------------------

JDBC Driver:-JDBC Driver is a software component that enables java application to


interact with the database
------------
JDBC Drivers
JDBC-ODBC bridge driver
Native-API driver
Network Protocol driver
Thin driver [fully java driver]

1 Connection interface:-
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData

2 Statement interface:-
The Statement interface provides methods to execute queries with the database

3 ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.

4 PreparedStatement interface:-
The PreparedStatement interface is a subinterface of Statement. It is used to
execute parameterized query.
=>Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

Q @transient spring ?
---------------------
ans:-
JPA's @Transient annotation is used to indicate that a field is not to be persisted
in the database,

-------20/11/17------TELEPHONE ROUND Q-----------------------------

Q- spring MVC work flow ? how recognize view extenstion if i want to go for html ?
can i configure 2 extenstion ?
-----------------------------------------------------------------------------------
---------------------------------
ans:-
Client(1) --> Dispatcher Servlet(2) --> Handler Mapping(3) --> Controller(4) -->
ModelAndView(5) -->Dispatcher Servlet(6)--> viewResolver(7) --> View(8) -->
Client(1)

Spring MVC framework:


1) Client sends an HTTP request to a specific URL
2) DispatcherServlet of Spring MVC receives the request
2) It passes the request to a specific controller depending on the URL requested
using @Controller and @RequestMapping annotations.
3) Spring MVC Controller then returns a logical view name and model to
DispatcherServlet.
4) DispatcherServlet consults view resolvers until actual View is determined to
render the output
5) DispatcherServlet contacts the chosen view (e.g. Thymeleaf, Freemarker, JSP)
with model data and it renders the output depending on the model data
6) The rendered output is returned to the client as response

Spring MVC 3.2 Execution Flow


Step 1: First request will be received by DispatcherServlet
Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the
Controller class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the
request by executing appropriate methods and returns ModeAndView object (contains
Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the
actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to
display the result

**resoving view pages problum-solve this using ContentNegotiatingViewResolver.

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter
{

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
configurer.defaultContentType(MediaType.APPLICATION_XML);

}
}

[in spring config]


<bean id="contentNegotiationManager"

class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/xml" />
</bean>

<!-- Make this available across all of Spring MVC -->


<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

-----------------------------------------------------------------------------------
----

Q- how to read the data from controller/Model class ?


ans-
@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne)
{
//do stuff with valueOne variable here
}

Q what is @ModelAttribute ?
-----------------------------
I always use @ModelAttribute to catch object from spring form jsp
method argument indicates the argument should be retrieved from the model
ex:- public String controllerPost(@ModelAttribute("Book") Book book)
{
}

the @ModelAttribute annotation can be used on methods or on method arguments. And


of course we can have both use at the same time in one controller.

1.Method annotation

@ModelAttribute(�cities�)
public List<String> checkOptions()
{
return new Arras.asList(new[]{�Sofia�,�Pleven","Ruse�});
}
Purpose of such method is to add attribute in the model.
So in our case cities key will have the list new Arras.asList(new[]
{�Sofia�,�Pleven","Ruse�}) as value in the Model
(you can think of Model as map(key:value)).
@ModelAttribute methods in a controller are invoked before @RequestMapping methods,
within the same controller.

2.Method argument

public String findPerson(@ModelAttriute(value="person") Person person)


{
//..Some logic with person
return "person.jsp";
}
An @ModelAttribute on a method argument indicates the argument should be retrieved
from the model. So in this case we expect that we have in the Model person object
as key and we want to get its value and put it to the method argument Person
person. If such does not exists or (sometimes you misspell the (value="persson")).
Then Spring will not find it in the Model and will create empty Person object using
its defaults. Then will take the request parameters and try to data bind them in
the Person object using their names.

Q what is hibernate and why we use hibernate ?


------------------------------------------------
Hibernate:-
Hibernate is an Object-Relational Mapping(ORM) and open source persistent framework
.
It perform Object-Relational Persistence and Query service for any Java
Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data
types and relieves the developer from 95% of common data persistence related
programming tasks.
Advantages Hibernate :-
-> Hibernate takes care of mapping Java classes to database tables using XML files
and without writing any line of code.
-> Provides simple APIs for storing and retrieving Java objects directly to and
from the database.
-> Hibernate provides its own query language i.e., HQL. HQL is a Database
Independent Query Langauage.
-> All Exception of Hibernate are Unchecked. So it is not compulsory to add
try,catch blocks to the code.
-> Hibernate provides the facility to use caching mechanism.
-> Hibernate has provided Criteria API. By using this API Hibernate itself creates
a tuned query to perform operations.
-> It provides Lazy Loading concept. Thus it improves the Performance of an
application.
-> Hibernate provides Locking Mechanism. It avoids the Transactions problems.
-> Hibernate bydefault comes with Connection pooling. We are not bother about to
open and close the connection.

Q how to read all data of object using HQL ? write HQL query ?
----------------------------------------------------------------
Query Interface:-
The object of Query can be created by createQuery() method of Session interface.
ex:-to get all the records
Query query=session.createQuery("from Emp");
List list=query.list();

Q- why we use soap and what is diff bw Rest and Soap ?


-------------------------------------------------------
ans:-
WS Security: SOAP defines its own security known as WS Security.
Language and Platform independent: SOAP web services can be written in any
programming language and executed in any platform.
Diff:-
There are many differences between SOAP and REST web services. The important 10
differences between SOAP and REST are given below:
SOAP-REST
1) SOAP is a protocol. REST is an architectural style.
2) SOAP stands for Simple Object Access Protocol. REST stands for REpresentational
State Transfer.
3) SOAP can't use REST because it is a protocol. REST can use SOAP web services
because it is a concept and can use any protocol like HTTP, SOAP.
4) SOAP uses services interfaces to expose the business logic. REST uses URI to
expose business logic.
5) JAX-WS is the java API for SOAP web services. JAX-RS is the java API for RESTful
web services.
6) SOAP defines standards to be strictly followed. REST does not define too much
standards like SOAP.
7) SOAP requires more bandwidth and resource than REST. REST requires less
bandwidth and resource than SOAP.
8) SOAP defines its own security. RESTful web services inherits security measures
from the underlying transport.
9) SOAP permits XML data format only. REST permits different data format such as
Plain text, HTML, XML, JSON etc.
10) SOAP is less preferred than REST. REST more preferred than SOAP.
*****YOGESH
*********20/11/17******************************************************************
*******************************

1) why we require dependency injection? if it is used to create object then why we


are not going for new keyword?
what is the drawback of creating direct object of another class by using HAS-A
relation?
-----------------------------------------------------------------------------------
-------------------------------
ans:-
DI container or fw assigns values to resouce or obj dynamically is called DI.
here depedent value pushed to resource.

IOC (Inversion of control) -

Inversion of control means the way of managing the dependency the dependent object
will be injected to the target object
it is inverse process of managing the dependency that�s it is called Inversion of
control.
spring we can achieve inversion of control by configuring the spring bean in
�spring bean configuration file�.
? If spring framework is creating the object and establish the dependency with
other objects we call it as inversion of control.
? If spring need to take care of creating the object and establishes the dependency
we need to configure the spring bean in spring bean configuration
file(applicationContext.xml).

DI:-
Dependency injection means injecting the dependent object to the target class
through setter or constructor with the help of underlying ioc container.

Advantage of IOC:-
The IOC creates the spring bean objects and automatically injected to the target
class, Only you need to configure the beans with properties.
Your code is clean and readable.
Codes are loosely coupled.
More reusable as the implementations are configured in the XML file, it can be used
in a different context.
Code can be easily testable with different mock implementation.
Your application will be loosely coupled with the help of IOC and Strategic design
pattern.

DI drowback:
------------
Dependency Injection disadvantages:

=> forces developers to use an injection framework like Spring. This causes
dependency on a framework.

=> clients are dependent on the configuration data. This becomes extra task for
developers when the application does not need so many custom configuration values.

=> Code is difficult to trace and read in Dependency Injection. DI separates


behavior from construction of objects.
=> increases complexity in the linkages between classes. It may become harder to
manage such complexity outside the implementation of a class.

2)different scopes of spring with definition? what is difference between singleton


and prototype? when objects will create?
-----------------------------------------------------------------------------------
----------------------------------------

Differen types of spring bean scopes:


-------------------------------------
In the spring bean configurations, bean attribute called 'scope' defines what kind
of object has to created and returned. There are 5 types of bean scopes available,
they are:

1) singleton: -
Returns a single bean instance per Spring IoC container.
Only one instance of the bean per spring container(Default Scope)
It returns a single bean instance per Spring IoC container.This single instance is
stored in a cache of such singleton beans, and all subsequent requests and
references for that named bean return the cached object.If no bean scope is
specified in bean configuration file, default to singleton.

2) prototype:-
Returns a new bean instance each time when requested.
A new instance every time a bean is requested
It does not store any cache version like singleton.
This bean scope just reverses the behavior of singleton scope and produces a new
instance each and every time a bean is requested.

3) request:-
Returns a single instance for every HTTP request call.
single bean instance per HTTP request

4) session:-
Returns a single instance for every HTTP session.
single bean instance per HTTP session
As soon as user ends its session, bean is out of scope.

5) global session:-
global session scope is equal as session scope on portlet-based web applications.
single bean instance per global HTTP session, it's using in portlet applications.

only valid when used in a portlet context. Only valid in the context of a web-aware
Spring ApplicationContext.
*default means when no scope is explicitly provided in the <bean /> tag.
If no bean scope is specified in bean configuration file, then it will be by
default 'singleton'.

how to define scope ?

<bean id="demoBean" class="com.howtodoinjava.application.web.DemoBean"


scope="session" />
or by annotation

@Scope("session")
public class DemoBean
{
//Some code
}

Q-what are joins in SQL ?


---------------------------
ans:-SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
If you want to access more than one table through a select statement.
If you want to combine two or more table then SQL JOIN statement is used .it
combines rows of that tables in one table and one can retrieve the information by a
SELECT statement.
The joining of two or more tables is based on common field between them.

SQL INNER JOIN also known as simple join is the most common type of join.
1-(INNER) JOIN: Returns matching values in both tables
ex:
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

2-LEFT (OUTER) JOIN: Return all records from the left table, and matched records
from the right table
ex:
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

3-RIGHT (OUTER) JOIN: Return all records from the right table, and the matched
records from the left table
ex:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

4-FULL (OUTER) JOIN: Return all records when there is a match in either left or
right table
ex:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

5-SELF JOIN
A self JOIN is a regular join, but the table is joined with itself.

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
3)what is group by clause in sql?
----------------------------------
SQL GROUP BY Statement
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

or

The GROUP BY clause must follow the conditions in the WHERE clause and must precede
the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

-
4)what is method overridding? with use case? why we prefer Polymorphism over
inheritance?
-----------------------------------------------------------------------------------
------

Q where we are using security in our project and what kind of security is it?
------------------------------------------------------------------------------
ans:
we use filter security for User Login and
CODEC(Base64) security for Customer Operations using EDI.

filter security:-
what is Filters-> o A Filter is an interface. It provides request & response
filtering before processing.
o It works based on Servlet URL matching.
o Filter should be configured in web.xml, using Servlet URL pattern. It can /*
also to specify all request filtering.
o Filter also contains life-cycle methods
1. init()
2. doFilter()
3. destroy()
o init() and destroy() are executed only one time.
o Filter supports init parameters from web.xml

Creating security filter for session management


Step 1
Define a filter class and configure in web.xml that should filter all
DispatcherServlet request
( i.e. use filter url as /mvc/* ).
Step 2
Provide init-param�s which doesnot required session check.
Step 3
Read all init-param�s into filter and store in List object.
Step 4
In doFilter() method, get current URI using with the request.getRequestURI()
and check this with avoid url list.
o If available, then skip session check.
o Else check session and return to home page.
o Here, we can also enable cache clear and this will be executed on
invalidation of session. ( also disables back button ).

//disable back button


res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", 0);

6)what are util classes in your project?

7)difference between JPA and Hibernate?

8)What is transaction?

9)what will we use to provide security in controller?

10) what is the architecture of MVC? work flow?

Q Treemap and treeset ? where to use ?

Q Arraylist and Vector ?

Q spring structure folder with maven ?

Q string s="MH" s="INDIA" ?

Q what is immutaiblity ?

Q what you used for versioning tool - git/svn ?

Q-what auto-wiring ?

Q- @component

Q-@repository

Q-what stereotype annotype ?


***********27/11/17= Maketech serve Q*************

Q how to bind/write form data/ jsp form data to controller ?

Q can we develop spring apps without spring confing file ?

Q how to convert json to diff form and object to diff form ?


and if json has diff sub obj data like list, set , array and string then how
convert sepratally ?

Q what is autowire ?

Q hql and criteria ?


and how to pass data to criteria conditions dynamically binds ? how pass ?

Q how to manage session in hibernate ?

Q what is api versioning in rest ?

Q jee architecture ?

Q diff view objects in spring ?

-------17/11/17------TELEPHONE ROUND Q-----------------------------

Q what is singleton class and how to create our own singleton class ?
---------------------------------------------------------------------
Q How to create our own immutaible class ?

Q how to override equals mehtod ?

Q steps to write Rest webservice ?

Q Exception scenerio to get arthimatic ?

Q what comparator and comparable ?

Q-equals() and hashCode() ?


----------------------------
-------------------------------------

--------13/11/17-INFRATECHSOF INTERVIEW Q----------

Q what is SOAP and Rest, where you used in your project ?


---------------------------------------------------------
Ans:-
SOAP:
Simple Object Access Protocol (SOAP) is a standard protocol specification for
message exchange based on XML.
Communication between the web service and client using XML messages.
or
-is a messaging protocol that allows programs that run on diff operating systems
(such as Windows and Linux) to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).
-It is platform independent and language independent.

**Advantages

WS Security: SOAP defines its own security known as WS Security.


Language and Platform independent:

**Disadvantages
Slow: SOAP uses XML format that must be parsed to be read. It defines many
standards .
So it is slow and consumes more bandwidth and resource.

WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the
service.

or

SOAP:-
->soap is webservice to connect two diff apps using xml req and response
->it completely depend on xml
->soap follow SOA(service oriented architechtur) design.
->soap objects are created by using JAXB
->soap mainly works based on WSDL(web services discription language) , which
provide details of skelton(provider) like classes, method name, their
parameters , return type.
->JAX-WS: -> is a Java programming language API for xml web services,particularly
SOAP services.
JAX-WS is one of the Java XML programming APIs.

Rest web service:


=================
Representational State Transfer (REST) is an architectural style that specifies
constraints,
REST is an architectural style not a protocol.
or
REST is a web standards based architecture and uses HTTP Protocol for data
communication.
or
REST architecture, a REST Server provides access to resources and the REST client
accesses and presents the resources.
Here each resource is identified by URIs.
REST uses various representations to represent a resource like Text, JSON and XML.
JSON is now the most popular format being used in Web Services.
or
interoperability:-Software applications written in various programming languages
and running on various platforms can use web services to exchange data over
computer networks .
(between Java and Python, or Windows and Linux applications)

HTTP Methods
The following HTTP methods are most commonly used in a REST based architecture.
GET - Provides a read only access to a resource.
PUT - Used to create a new resource.
DELETE - Used to remove a resource.
POST - Used to update an existing resource or create a new resource.
OPTIONS - Used to get the supported operations on a resource.
or

Web services based on REST Architecture are known as RESTful Web Services.
These web services use HTTP methods to implement the concept of REST architecture.
A RESTful web service usually defines a URI (Uniform Resource Identifier), which is
a service that
provides resource representation such as JSON and a set of HTTP Methods.

Restful Web Services is a stateless client-server architecture where web services


are resources and can be identified by their URIs.
REST Client applications can use HTTP GET/POST methods to invoke Restful web
services.
REST doesn�t specify any specific protocol to use, but in almost all cases it�s
used over HTTP/HTTPS.
these are lightweight and doesn�t follow any standard. We can use XML, JSON, text
or any other type of data for request and response.
or
RESTful Web Services utilize the features of the HTTP Protocol to provide the API
of the Web Service. It uses the HTTP Request Types to indicate the type of
operation:

GET: Retrieve / Query of existing records.


POST: Creating new records.
DELETE: Removing records.
PUT: Updating existing records.
Using these 4 HTTP Request Types a RESTful API mimics the CRUD operations (Create,
Read, Update & Delete). REST is stateless, each call the to a RESTful Web Service
is completely stand-alone, it has no knowledge of previous requests.

or

Restfull web service is process of sending data in some format( Text, HTML, XML and
JSON.)
Rest full is light weight architectur./ it require less memory.
REST stands for REpresentational State Transfer.
REST is an architectural style .
In the REST architectural style, data and functionality are considered resources
and are accessed using Uniform Resource Identifiers (URIs)
**Advantages of RESTful Web Services
1 Fast: RESTful Web Services are fast because there is no strict specification like
SOAP.
It consumes less bandwidth and resource.
2 Language and Platform independent: RESTful web services can be written in any
programming language and executed in any platform.
3 Can use SOAP: RESTful web services can use SOAP web services as the
implementation.
4 Permits different data format: RESTful web service permits different data format
such as Plain Text, HTML, XML and JSON.

Q-DIFF OR IMPORTANCY OF SOAP OR RESTFULL TO USE ?


------------------------------------------------
SOAP vs REST Web Services

There are many differences between SOAP and REST web services. The important 10
differences between SOAP and REST are given below:

No. SOAP REST


1) SOAP is a protocol. REST is an architectural
style.
2) SOAP stands for Simple Object Access Protocol. REST stands for
REpresentational State Transfer.
3) SOAP can't use REST because it is a protocol. REST can use SOAP web
services because it is a concept and
can use any protocol like HTTP, SOAP.
4) SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business
logic.
5) JAX-WS is the java API for SOAP web services. JAX-RS is the java
API for RESTful web services.
6) SOAP defines standards to be strictly followed. REST does not define
too much standards like SOAP.
7) SOAP requires more bandwidth and resource than REST. REST requires less
bandwidth and resource than SOAP.
8) SOAP defines its own security. RESTful web services
inherits security measures from the
underlying transport.
9) SOAP permits XML data format only. REST permits different data
format such as Plain text,
HTML, XML, JSON etc.
10) SOAP is less preferred than REST. REST more preferred than
SOAP.
soap use WSDL.

Difference between SOAP and RESTful Web Service in Java


-------------------------------------------------------
then getting data from a SOAP web service. S
it's easy to understand and correlated how RESTful web services are working and
which URL of REST web service provides what kind of information.
In SOAP, you need to understand lengthy WSDL document to find out right methods and
the right way to call them.
In short, RESTfull web services are much simpler, flexible and expressive than SOAP
web services in Java.
There are a few additional situations:
-getting data from a RESTful web service requires less headache
-
in SOAP you need to understand lengthy WSDL document to find out right methods
and the right way to call them.
SOAP has built in WS-Reliable messaging to increase security in asynchronous
execution and processing.
Finally, SOAP has built-in stateful operations.REST is naturally stateless,
support for WS_AtomicTransaction and WS_Security, SOAP can benefit developers when
there is a high need for transactional reliability.
REST focuses on resource-based (or data-based) operations and inherits its
operations (GET, PUT, POST, DELETE) from HTTP.
This makes it easy for both developers and web-browsers to consume it.
REST allows easy, quick calls to a URL for fast return responses.
The difference between SOAP and REST, in this case, is complexity�-SOAP services
require maintaining is complex client.
REST services are now well-supported by tooling.
The available tools and browser extensions make testing REST services continually
easier and faster.
REST is almost always going to be faster.
REST is much more lightweight

Soap Web-services :
If your application needs a guaranteed level of reliability and security then go
for SOAP.

Totally stateless operations: for stateless CRUD (Create, Read, Update, and Delete)
operations.
Caching situations: If the information needs to be cached.

SOAP) and Representational State Transfer (REST).

SOAP defines a standard communication protocol (set of rules) specification for


XML-based message exchange.
SOAP uses different transport protocols, such as HTTP and SMTP.

WSDL:
WSDL is an acronym for Web Services Description Language.
WSDL is a xml document containing information about web services such as method
name, method parameter and how to access it.
WSDL is a part of UDDI. It acts as a interface between web service applications.
WSDL is pronounced as wiz-dull.
Note-using WSDL WE CAN UNDERSTAND-
Port / Endpoint � URL of the web service
Input message format
Output message format
Security protocol that needs to be followed
Which protocol the web service uses

UDDI:
UDDI is an acronym for Universal Description, Discovery and Integration.
UDDI is a XML based framework for describing, discovering and integrating web
services.
UDDI is a directory of web service interfaces described by WSDL, containing
information about web services.
------------

XML [extensible markup lanugae]-> used to transfer data from one app to another
DTD [document type definition]-> provides rules to xml file, and DTD contains of
Element and Attributes.
XSD [xml schema design]-> xsd provide rules to write xml file, and data type also.
-----------------------------------------------------------------------------------
---------------

Q how hash map internally work ?


--------------------------------

Q can i store duplicate value or key in hashmap ?

Spring :- Q what is wiring ?


Q drowback of wiring ?

Hibernate:Q- criteria ? how i can select emp name wihout select id ?

--[YOHESH]------10/11/17-TCS INTERVIEW Q-----------------

Q- spring scopes ?

Q- why we use Hibernate ,instead of jdbc ?

Q- which is best- xml or annotation based configuration ?

Q- diff bw set and list and map?

Q- diff bw static kw, final kw and abstract kw ?

Q- throw and throws ?

Q- try catch child exception ?

Q- what is JSON ?

Q- Autowired ?

Q- Can we use multilple xml file ?

Q- what is ENUM in java ?

Q- type of joins in sql/oracle ?


---------------------------------------------------

Q:- diff bw interface abstract ?

Q:- what loose coupling ?

Q:- where to use HashMap ? its internally works ?

Q:- What is interface and why we use it?

Q:- Which web service is more secure, SOAP or REST?

1) how to call stored procesure in spring using jdbc ?


-----------------------------------------------------
ans:
Requirement: Develop a spring based application which calls the procedure which is
available in the database.
? In spring if we want to deal with procedures we have to use callback mechanism.
We need to provide the implementation an interface �CallableStatementCreator�. In
this we write the code to create the CallableStatement object and
return this object to JdbcTemplate class.

Program:
Procedure name: myproc
SQL> create or replace procedure myproc
2 as
3 begin
4 insert into emp values(1,'eone',1000);
5 end myproc;
6 /

Procedure created.

Program: OurCallableStatementCreator.java

package org.students;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.jdbc.core.CallableStatementCreator;

public class OurCallableStatementCreator implements CallableStatementCreator


{
public CallableStatement createCallableStatement(Connection con) throws
SQLException
{
CallableStatement cstmt=con.prepareCall("{call myproc}");
return cstmt;
}
}
Program: InsertRecord.java
package org.students;
import java.util.ArrayList;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class InsertRecord {
public static void main(String[] args)
{
ApplicationContext container=new
ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt=(JdbcTemplate)container.getBean("jt");
jt.call(new OurCallableStatementCreator(), new ArrayList());
System.out.println("record successfully inserted");
}
}
Output:
Record successfully inserted.

3) How internally hashing works?

4) If I want to make user defined class as a key within HashMap then which methods
do I need to override?
---> equals() and hashCode().

8) What is Serialization.

1) Spring Hibernate integration.

2) @autowired annotation

3) AOP (what is joinpoint, pointcut and advice).

4) Difference between BeanFactory and ApplicationContext.

6) What is dependency injection? More places people don't know what is need of
dependency injection and why to use, we need to explain them.

7) Spring MVC architecture.

Q- how to controller get req from dispatcherservlet ?-imp


or how controller sent this req to valid or match with method ?-imp

Q- how to write path in controller , and where ? imp

Q. What is difference between put & post in Rest API.?

Q can i map more than object class with database table?

Q- how to identify request data in which form data comming ?

Q- how to convert object data into xml in rest ?

Q- how to recognize req in soap ?


Hibernate

1) How many levels of caches are there and Explain them?


3) entity life cycle.

Q- how to read data in jsp from controller ?


---------------------------------------------
Q can we execute programm , without main ? and what mean main[0] , main[1] ?

Q how to read xml file , spring container ?

-----------------------------
FINISH--------------------------------------------------------------------

****************************************************[WITHOUT INTERVIEW IMP


Q]**************************************************

What is a spring container?


Spring container is a java object. We can call an object as a spring container if
we provide the implementation of an interface
�org.springframework.beans.factory.BeanFactory�.
--

What is the responsibility of spring container?


? The responsibility of the spring container is read the contents from spring
configuration file (ApplicationContext.xml) and creates the object to spring bean.
? Spring guys have provided a class which provides the implementation of
�ApplicationContext� interface.
? The class provided by the spring can search for xml file in the class path and
create the spring container object. The name of the class name is
�ClassPathXmlApplicationContext�.
--
Note: applicationContext.xml file is called as �spring bean configuration file�.
As part of this file we are going to configure the spring bean(java beans).

spring we can achieve inversion of control by configuring the spring bean in


�spring bean configuration file�.
--

default spring bean configuration every time when we use getBean() method it is
returns the same address bean object. By default the spring container creates only
one singleton object.
In the spring bean configuration file we can use an attribute scope. This attribute
can take any of the following four values. They are:
1) Singleton
2) Prototype
3) Session
4) Request
Note: session and request values are used in we

ased applications.
? By default the scope attribute value is singleton.
? When we run the same above java program by specifying scope=�prototype� everytime

--

How many objects will be created by the spring container for a bean(spring bean)?
? It�s based on a configuration of the spring bean.
15
? If scope=�singleton� it creates one object.
? If scope=�prototype� it creates multiple objects.

--

How do you establish one property dependent on the reference of other object?
? In the spring bean configuration file we use �ref tag� if a property dependent on
address of another object. (or)
? By using �ref tag� we can establish one property dependent on the reference of
other object.

What is a wiring?
? Connecting two different objects is called as wiring.
(Or)
? Establishing the dependency between the objects is called as wiring.
? By default the spring container checks for �reference tag�. If it is not
available then the spring container uses autowire.
? Autowire attribute takes 2 different values. They are:
1) byName
2) byType

What is an autowiring?
? Automatically establishing the dependency between the objects is called as
autowiring.
? By default the autowiring is not enabled. When we say autowire=default the spring
container internally consider autowire=no.
? Autowire is dependent on ref tag. That means if ref tag is not there then only
autowire is enabled.
When the autowiring happen?
? If ref tag is not there then only autowiring is done.
? Autowiring will be enabled only after the wiring is not satisfied.

The ModelAndView object can hold 2 different types of objects. They are:
1) View objects
2) Model objects
? In spring model objects hold the data. This data is used by the view component to
render the data.

Procedure to deal with a model object:


? In spring model objects are used (or) responsible to hold the data. This data is
used by view component to render the data to the user.
? If we want to set a string object as a model object we have to use a method
addObject().
Syntax:
? Once if add the data to the model object it will be added to request scope with a
given key.
? Now the jsp can access the data from requestScope.

In model objects we can store any type of objects like String, ArrayList, Map and
etc.

How to deal with multiple model objects in spring:


? If we want to deal with multiple model objects they have to add to Map object.

By default most of the times we display the content in html pages. Sometimes client
would like to render the data in a pdf file (or) ms-excel (or) ms-word.
70
? In majority of the projects we need to develop the reports. Generally the reports
will be in the form of pdfs (or) excel (or) ms-word etc.
? As part of the spring framework they have integrated all the reporting tools.
? As part of spring framework the spring framework has developed set of predefined
classes to simplify the report generations.
? The predefined classes are:
1) AbstractPdfView
2) AbstractExcelView��etc.
? These classes internally uses the reporting tools and generate the pdf document
(or) excel document (or) word document etc.
? The following class will be able to generate the pdf document

****** For synergy Q on net******************

Q2: In depth knowledge of classes and objects ?


------------------------------------------------
Difference between object and class

There are many differences between object and class. A list of differences between
object and class are given below:

No. Object Class


------------------------------------------------------------------------
1) Object is an instance of a class. Class is a blueprint or
template from which objects are created.
2) Object is a real world entity such as pen,
laptop, mobile, bed, keyboard, mouse, chair etc. Class is a group of
similar objects.
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new keyword mainly
e.g. Student s1=new Student(); Class is declared using
class keyword
e.g.class Student{}
5) Object is created many times as per requirement. Class is declared once.
6) Object allocates memory when it is created. Class doesn't allocated
memory when it is created.
7) There are many ways to create object in java such as new keyword,
newInstance() method, clone() method, factory method and deserialization. There
is only one way to define class in java using class keyword.
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors � wagging the tail, barking, eating. An object is
an instance of a class.

Class - A class can be defined as a template/blueprint that describes the


behavior/state that the object of its type support.
Class:-

A class is a user defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of
one type
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

fields
methods
constructors
blocks
nested class and interface
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc.
Object Definitions:

Object is a real world entity.


Object is a run time entity.
Object is an entity which has state and behavior.
Object is an instance of a class.

It is a basic unit of Object Oriented Programming and represents the real life
entities.
a object consist of state, behaviour, identity.

When an object of a class is created, the class is said to be instantiated.


All the instances share the attributes and the behavior of the class.
But the values of those attributes, i.e.
the state are unique for each object.
A single class may have any number of instances.

Q3: static vs non-static ?


--------------------------

ANS:
STATIC:-> For storing data and operate that data common to all instances/references
of objects.
Non-Static:->For storing data and operate that data separately and specified to
every instace / reference of object.

Q when gets memory location these members and by whom ?


ans: identified and get mem location at the time of class loading by default by JVM
in method area.
1 STATIC VARIABLES: - which has static kw in creation stmt.
------------------
Q-does jvm execute static var by default?
ans: yes , it execute static var, and means provides memory location at the time of
class loading.

Q-what is the order of execution of all static members?


ans: in order they are defined top to bottom.

Note:- When class is loaded, JVM provided individual single copy of mem location to
each static variable in method area
only once in a class life time.

Q-what is lifetime and scope of static variables?


ans: get life when class is loaded into jvm and availble till class is removed from
jvm or jvm is shutdown.
its scope is class scope
static var is accessible inside class directally by its name, and outside by
its class name if non private.

Q-can we declare local var or parameter as static ?


ans: No, its not possible.
static kw not allowed inside block\method.

Note:- we can not define duplicate name variable in same scope (means same method /
same class),
it may be possible in diff scope like same name in class var and same inside
methods.

NON STATIC MEMBERS:- class level members (vars, methods, blocks) which dont have
static kw in defintion is called
"non-static" member.

Q-when all these members get mem location and by whom ?


ans: get mem loc only "if object is created " with new kw and with constructore of
that class."

Note: - JVM will not provide mem location for these mem by default.

Q-what is an object and its Creation syntax ?


ans: Technically-> object is instance of a class ,
that object contains continues mem loc of all non-static vars of
a class with specific data of this
instance.
Note:- object is created :- using new kw and constructor of that class.

SYNTAX TO CREATE OBJECT:


-----------------------
<A.M> <MOD> <C.N> <V.N> = NEW <C.N>

EX: Example e = new Example();

here-> e is object name


-> new Example() is object creation stmt.
Non-static Varables:
--------------------
>class level var that dont have static kw in defintion is called non-static var.

Q-who will execute non-static var ?


ans: jvm will execute non-static vars only if object is created.

Q-when , where how, and by whom non-static var get memory location ?
ans ->
when-> get mem loc when obj is created
where -> in heap area and in continuous memory location by jvm.
how-> when obj is create with new kw and gets mem loc in continues mem location.
whom-> by JVM

ex: Example e = new Example();

then assume 1010 is base address or obj ref


e is destination var where this base address is stored.

Note: object ref is 'e' is returned by new keyword not by constructor.

Q- How many obj can we create for a class ?


ans:
Note:in case of static var:
When class is loaded, JVM provided individual single copy of mem location to
each static variable in method area
only once in a class life time.]we can create multiple obj for a class but
their ref var name must be diff.
note-> when we create multiple obj's then non-static var gets separate copy of
memory for each object.
and so to access non static variables from perticuler object we must use
that ref var.

Q-if we modify one object will another object data also be modified ?
ans: No, modification done for one object will not be affected to another object.
bcoz we change object data
using its reference variable.

---------------------

You might also like