Saturday 6 April 2019

Java Top 100 Interview question and answer

Q:- Wrapper Classes in java?
Ans:-Wrapper classes are used for converting primitive data types into objects,
like int to Integer
here are mainly two uses with wrapper classes.

1) To convert simple data types into objects
2) To convert strings into data types


The eight primitive data types byte, short, int, long, float, double, char and boolean.

Why we need wrapper class?
For example: While working with collections in Java,
we use generics for type safety like this: ArrayList<Integer> instead of this ArrayList<int>.
The Integer is a wrapper class of int primitive type.
We use wrapper class in this case because generics needs objects not primitives.


Wrapper class Example: Primitive to Wrapper



2. Wrapper class objects allow null values while primitive data type doesn’t allow it.



2Example1:-
class WrapperClass{
psvm(){

int i=5; //primitive data type
Interger li= new Integer(i); // so puting value insdie object is called Boxing

int j = li.intValue(); // unboxing


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

Q: STring buffer and Stringbuilder?
Ans: StringBuffer is syncronised an thread  safe but StringBuilder is not synronised an not thread safe
StringBuffer and StringBuiler both are mutable

Example:

String str= new String("Hello");
StringBuffer buffer= new StringBuffer("Hello");
StringBuilder builder = new StringBuilder("Hello");

str.concat("Hello");
buffer.append("Hi");
builder.append("Hi");

System.out.println(str);
System.out.println(buffer)
System.out.println(builder);

OUTPUT:-
Hello  ->  here string is imutable that why its not changable  so it will take first string  data
Hi     -> here it is mutable means its  changeable that why append ouput came 
Hi    -> here also it is mutable so append out put came

here

-------------------------------------------------------------------
Q: diff btn == and equal()?

== method is cpmpare reference
equals() method its compare content of the object

example:

String str1= new String("Hello");
String str2 = new String("Hello");

if(str1 == str2){ // comparing reference
  system.out.println("str1== str2");
}else{
   system.out.println("str1  !== str2");
}

if(str.equals(str2)){
  system.out.println("str1 is equal str2");
}else{
    system.out.println("str1 not equals str2");
}

OUTPUT:-
str1 !== str2
str1 is equal str2
----------------------------------------
Q: Diff btn Abstract class and interface?

Abstarct class vs Interface.
1)An abstarct class  can provide complete default code
and/or just the details that have to be overriden.
where as interface can not provide any code at all, just the signature

2)in case of abstarct class, class may extend only one abstarct class
where as in interface A class may implement serveral interface.

3)abstarct class can have not abstract method.
where as interface can have all methods of interface are abstract

4)abstract class can have instance variable
where as An interface can not have instance variables.

5)abstract class can have any visisbilty: public, private, protected
where as interface visibility must be public or none

6)abstarct class can contain constructor
where as interface can not conatin constructors.

7)abstract classes are fast
where as interfce slow as it required extra indirection to find corresponding method in the actual class.


------------------------------------------------------------------------------
Q:What is overriding with example?
ans: declare the method in sub class which is already present in superclass is called overriding.

we can say method name , signature and return all should be same

-------------------------------------------------------------------------------
Exmaple: What will be the output of this program?

class Parent
{
  public static void foo(){
  System.out.println("i am foo in parent");
 }


 public  void bar(){
  System.out.println("i am bar in parent");
 }

}

class Child extends Parent{

   public static void foo(){System.out.println("i am foo in child
   
 }

public  void bar(){
  System.out.println("i am bar in child");
 }

public static void main(String args[])
{

Parent par = new Child();
Child child = new Child();

par.foo();
child.foo();

par.bar();
child.bar();

}

}


Output:

i am foo in super
i am foo in child
i am bar in child
i am bar in child

------------------------------------
Q:Servlet lifecycle?
ans:-there are five stages.
>servlet is loaded
>servlet is instantiated
>servlet is initialized
>service the request
>servlet is destroy.
-------------------------------------------------------------------------------------------
Q:- What is Request Dispature?
RequestDispature  interface is used to forward the request to another resource
that can be html,jsp or anothr servlet in same application


we can also use include content of another resource to the response
there are two method defines in this interface:
1) forward()
2) include()
----------------------------------------------------------------------------------------
Q:- What is bean in spring and Explain scops of bean in Spring?
A bean is an object that is instantiated, assembled and managed by sping IoC container.
They are managed by the Spring IOC COntainer.
There are 5 scops of bean spring
singleton
prototype
request
session
global-session
-----------------------------------------------------------------------------------------
Q:- What is dispature servlet and COntextLoaderListener?
DispatcherServlet:-
DispatcherSrevlet is front controller in spring mvc
application as it loads the spring bean configruation file
and initializes all the bean that have been configured

ContextLoaderListener:
ContextLoaderListener , the listener to start up and shut don the webapplicationCOntext in spring root.
------------------------------------------------------------------------------------------
Q: diff btn COnstructor injection and setter injection?

ANs:-
COnstructor injection:-                        setter injection:
1-no partial injection                         1-Partial injection   

2-Doesnt override the  setter property         2-Overrides the constructor property if both are difined.   

3-Create new instance if any modification      3- DOesnt create the  new instance if you change the property value
occurs.

4- Better for too may properties.              4- better for few properties.


----------------------------------------------------------------------------------------
QA:- What is autowiring in spring? what are the autowiring modes?
Ans"- Autowiring enables the programmer to inject the bean automatically.
We dont need to write explicit injection logic.
example:
<bean id="emp" class="com.java.Employee" autowire="byName"/>

There are 4 type of autowiring?
1- no:- This is default mode. it means autowiring is not enabled.

2-byName:- injection the bean based on the property name.it uses setter method

3- byType:- injection the bean on the property type. it sues setter method.

4- constructor:- it injects the bean using constructor.

-----------------------------------------------------------------------------------------
Q:- How to handle exception in spring mvc framwork?
Ans:- Spring MVC provide some way to help us acchive exception
1- Controller Based: we can define excepton handle methods in our contrller class
2- Global Exception Handle: Exception Handling is a cross cutting concern and spring provides
3- HandlerExcptionResolver
----------------------------------------------------------------------------------------
Q:- What are some of the important Spring annotation used?
Ans:-
@Controller
@PathVariable
@Qualifier
@Configruation
@Scope
@RequestMapping
@AutoWired
@Service
@Aspect
------------------------------------------------------------------------------------------
Q:- How to integarte spring and hibernate framwork?
Ans:- we can use Spring ORM module to integtae Spring and hibernate framwork.
Spring ORM also provide support for using Spring declarative transaction management.
-----------------------------------------------------------------------------------------

Q:- What is Hibernate?
Ans:- Hibernate is java based ORM tool that provides framework for mapping application domain onjects to the relational database tables and vice versa.

Hibernate provide reference implementaion of java Persistence API(JPA).
That makes its great choice as ORM tool with benefits of loose coupling
loose coupling means where dependency level reduce to maximum level.
Hibernate configruation are flexible and can be done from Xml configruation file as well as programmatically

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

Q:- diff btn get and load method in hibernate?
ans:Both are used to get the data from the database
get()-                                   load():
1- Returns null if obejct is not found   1- ThrowsObjectFoundException if object is not found.
2- get() method always hit the database  2- load() method doesnot hit the database, first it will search in cache memory not there than it will hit database.
if data is not there it will retrun null      if data is not there it will throw exception ObjectNotFOund
3- it return real object not proxy       3- it returns proxy object.
4- it should used if you are not sure    4- it should be use if you are sure  that instance.
    about the existence of instance.
==================================================================================

Q:- What is syncronizantion in the thread?
Ans:-syncrinizantion means - it is the process of enableing the lock of object
every java object is associcated with some lock mechanism , by default this lock is disable.
if you want to enable this lock so that it should work in multithreade enviroment.
multiple thread should not enter in critical section at once so there we can use syncronism.

just to enable of lock of object so that multiple thread should not allow to access concurrently.
----------------------------------------------------------------------------------------
Q:- diff btn runnable and thtead?
ans:-1-runnable is interface,  availble in java.lang package
it has only one absract method.. public void run()
 where as thread is concreat class availble in java.lang package, it is also implementing runnable interface
it has thread class has overwritten the run method they have given dumy implementation.
-----------------------------------------------------------------------------------
Q:Which one is better runnable or thread?
Ans:-its depend up on requirement

both implementation is same
only diffrence when you are writting your user define  thread class by extending thread
bcoz java doen not support multiple inheritance with class's so you can not extend any other class
bu when you are writting user define thread by implementing runnable interface so what will have happen
you have change to extend other class also you can implement other interface.

-----------------------------------------------------------------------------------------
Q:- What is auto boxing?
ans:-auto boxing is feature of java 5
you can not store primitive value into collection,

so when ever you have requirement to get primitive as a object type u have to use wrapper class.
you have to create object of Integer class u have to pass primitive than u can get wrapper

Java 5 support autoboxing and unboxing feature

AutoBoxing:-autoboxing is proceess of converting primitive to wrapper and wrapper to primitive automatically.

--------------------------------------------------------------------------------------------
Q:-diff java 7 and java 8?
java 7 they have added some new feature
1: in one catch block we can write multiple exception
2:- they have gievn rethroughing execption imporived type checking
3-dymond operator
4-they have given try with resource

java8:- they have added new feature
1:- lamda expresion and functional interface
2-Stream API
3-forEach() in iterable interface
4-collection
5-Date and time Api

Q:- Expalin java 1.8 feature?
Ans:-
1)in java 1.8 one of the best feature they have given functional programming
that you can achiev by usinh lamda expression so thats help you to reduce lot of code.
Boilerplate  code you will reduce by using lamda expresion

Boilerplate code means a piece of code which can be used over and over again. On the other hand,
anyone can say that it's a piece of reusable code.

2) They have given java streaming API means
you can write some application which will help in parrell processing.

3) Next they have given utility classes like collection class's , you have array class's
that has only predefine method so

-------------------------------------------------------------------------------------------
Q:- What is diffrence between Soap base web services  and Rest based web services?
Ans:-
1-SOAP based web service- it is based on some standard they are follwing some standard like interface hirarchy is there
But in Rest based web service there is no starbdard

2-Soap based web services you have to use the protocal SOAP/Http
where as Rest full web srvice only based on Http protocal.

3-SOAP based web service will fouce you to use only Xml for communcation but in RESt be]ased web service
you have flexibility, you can use json , you can use xml, you can use simple text, Html and pdf

4- SOAP web services are very havvy u must have to use IDE to develop that
BUt rest full  web service even you can develop in notpad its very light weight

5- To test the SOAP based web service its a long process but To test the rest based web service
you can test using simple url also.

--------------------------------------------------------------------------------------------
Q:-What is servletContext object?
ans: servletContext object is..
It is the web container object like  three type of scope you have in servlet
servletContext , servlet request and session
SO if you want to use any data  among ll servlet and all the user can use  that data
so that you can write the web.xml file servletContext parameter you can define
that is universal object that you can access any where from the application to the end user.

---------------------------------------------------------------------------------------------
Q:- how many instnace of serveltContext will be there?
Ans:- only one

Q:- What is servletCOnfig?
Ans:- servletConfig object it is related to your particular servlet
so if you have requiremnet  to use some data for  particular servlet
how many user comming that many object will be created.

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

Q:- Diff btn HashSet and linkedHashSet?
Ans:
in HashSet data will store based on hashCode value of object you can call that random order
Random order means what ever order you are stroing    that order it will no be store
And HashSet internally using index representation so searching will be fast.

LinkedHashSet data will be store in the same order added by the user  and linkedHashSet internally using
node data structure so when you have requirement perform insert , delete operation
 than we will go for linkedHashSet .
------------------------------------------------------------------------------------
Q:- is there any collection that where can store key value paire and key has to be in sorted  order?

Ans:-TreeMap
suppose if i add Employee object in treeMap so what will  happen?
ANs;- it will give classCastException
so if you want use Employee object so key must be comprable object
when ever you inserting any key inside the treeMap that key must be comprable.
So Employee class has to implement comprable interface, it has override compareTo method
in that you have to return any field like employee id or employee name.
so it will give you the nature sorting order.

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

Q:- What is diffrence between wait() and sleep()?
Ans:-
Wait() is instance method of java object class, java.lang Object class
It has three overloaded method 
wait() with witout any parameter
wait(long timeout) with long mili second
wait(long timeout, int nanos)  with long and integer

Sleep()- sleep is a static method of thread class
this method is  belong to thread class
it has only two overloaded method
sleep(long mili) with long parameter
sleep(long mili, int nanos) with long, int parameter


 Sleep() method is used to pause the execution of thread for specify demon of time

Main diffrence
when we are using in syncronized context
suppose your method is syncronized in that run() method , whatever method
if you are calling sleep() method or run() method than atucall diffrnce will come.

what will happen when you call sleep() method on running thread and than thread will go to sleep state
it will not lock of object but in the case of wait() method thread will go to wait() state
and emidailty it will release lock of object,
SO that is why wait() method is responsible to release the loack of an object
that is why we have to call wait() method from syncronised context only
BUt sleep() method can call non syncronised also 


Q- Diffrence btn HashMap and concurrentHashMap? why it is actually comes in picture?
Ans:- first i need to compare hashMap and hashTable
hashTable is syncronised 
so thats means, at a time one thread can access the data from the hashTable
it can write or read that is hashTabel.
But hashmap it is not syncronised means mutiple thread its support concurrence
Now in hashtable the problem  was..like when ever thread writing to it or reading it
it will lock entire object entire hashMap object so it will not allow any other
suppose hashMap having 1 lakh entry so only one thread can access other thread will not allow to access

No comments:

Post a Comment