You are on page 1of 22

Hi friends, this is arun..

after seeing my previous post lot of people called me and


asked me how to crack interview as experienced java developer.
few tips note down it,
tell about yourself with start your name and end with your roles and responsibility
in previous project which you have worked in previous company.

ex-
my self a arun kumar basically i am from odisha, i have completed bca in 2013,after
completion of my studies i started my carrier by working in infogrid technology
that is there in banglore.
in this organization i am working as a java developer. i have been working in this
organisation since 3.4 years in one project named as AGD.
AGD stands for all goods details .its a erp domain project and our client for this
project from Europe.
the main objective of this project is a user can interact with suppliers through
online. user can get the status through online by mail about transpored product and
availability.
user check and view about historical data and user can generate his own
reports.this application is acts as a mediator between user and suplliers.
to implement this project we have been following agile mathodology.we are
developing code and transfer to tester.
afer completion of testing we deploy into live environment then another sprint wil
be released by our scrum master.
again we follow same. each sprint we takes around 15 to 20 days.and we conduct
daily one meeting roughly around 15 minutes about.
in this duration we talk about what we have done yesterday what problem we faced
and what we are going to do next.
in this project my roles and responsibilities are
implementing dao by using hibernate
developing modules by following spring mvc.
testing web serviece by using saop ui.
generate wsdl, creat wsdl.
debug the code and fixing bugs.
adding jars in pom.xml.
to make application to get better performation developing code by following several
design pattern like singleton, factory pattern, templet, abstarct factory pattern
etc.
implementing bussiness logics,analys bussiness requirement.
these are my roles and responsibilities in this projects
then the interviewer will start asking queations from core java to frameworks.
important topics in core java
1 strings
2oops
3collections include concurrent collections
4multi threading
5 several logical programs like, reversing, sorting, etc
hibernate
1 difference between get and load
3 difference between merge and saveOrUpate
4 caching
5 mappings one to many,many to one many to many
5 why sessionfactory is threadsafe
spring
1 why dependency injection came into the picture
2 what is ioc
3 what are the scopes
4 what is defference between beanfactory container and application container
5 flow of spring mvc
6 what are the view resolver
7 what is aop
8 what are the autowire modes
9 how to integrate with hibernate with spring, some times they ask you to write
down xml file
web services
what is rest
what is deffernce between soap and rest,
what are annotations in rest and their works
what is advantage from soap and disadvantage of soap
. friends these are commonly asked questions in regular interview. instead of by
chosing these question it is far better to learn in depth. but i am sure no
quetions can come out of nataraz sir's meterial.
and one.more thing when your going to interview dont go with heavy make up. just go
how your going daily to class
just go in cool mind. if you dont know any answer at all. say in positively i dont
know but if you give me a chance i will learn.
but sure when your going to attend intervie make sure that remember nataraz sir
classes. and go in cool mind.
ALL THE BEST GUYS
Today's CTS interview question

Technical Round:-
= = = = = = = = = = = = =
*Core-java
************
1 .Tell me the internal flow of Set implementation class with one example
ans:-Set Internally use Map so it doesn't allow duplicate
Map<Set<Obj>,String> m=new HashMap<>();
so whatever object u passed in set.add() method it will place in Map as a key as
per above.

2 . In HashMap if hashing collision occure then how to resolve it.

ans:-Hashing collision means if in collection if multiple object having same


hashCode() then it will definatly placed in same bucket
so to resolve this one we need to override equlas() method it will check content
wise if object are content wise same then override the value.else just place in
same bucket

3 . can we add duplicate in set and map if yes why write one code
ans: yes, we can add if u don't override equlas() and hashCode() then duplicate
will be allow in set and map also coz there is no element for comparing thats the
reason duplicate are allow..
class Employee{
int id;
String name;
public Employee(int id,String name){
this.id=id;
this.name=name;
}
@Override
//toString() method here
public static void main(String[] args){
Set<Employee> s=new Set<>();
s.add(new Employee(10,"Basant"));
s.add(new Employee(10,"Basant"));
sop(s);
}
}
4 . Read data from file find the duplicate word and count them and sort them in
desending order
public class ReadFileAndCount {

Map<String, Integer> wordMap = null;


String line = null;

public Map<String, Integer> counter(String fileName) throws IOException {


wordMap = new HashMap<String, Integer>();
try (BufferedReader br = new BufferedReader(new FileReader(new File(
fileName)))) {

while ((line = br.readLine()) != null) {


String[] data = line.split(" ");
for (String word : data) {
if (wordMap.containsKey(word)) {
wordMap.put(word, (wordMap.get(word) + 1));
} else {
wordMap.put(word, 1);
}
}
}

return wordMap;
}

public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap)


{
// convert map to set
Set<Entry<String, Integer>> mapSet = wordMap.entrySet();
// add set to list
List<Entry<String, Integer>> mapList = new ArrayList<>(mapSet);
// use utility method
Collections.sort(mapList, new Comparator<Map.Entry<String, Integer>>()
{

@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});

return mapList;
}

public static void main(String[] args) throws IOException {

ReadFileAndCount rfc = new ReadFileAndCount();

Map<String, Integer> value = rfc.counter("info.txt");

List<Entry<String, Integer>> data = rfc.sortByValue(value);

for (Map.Entry<String, Integer> getData : data) {


sop(getData.getKey() + "=>" + getData.getValue());
}
}

5 . where to use Comparable and where to use Comparator did you ever used in ur
project
ans: actually we are not using that interface in our project to sorting data..but i
have idea on it that we have to use Comparable if u want
to sort the object in collection in simple sorting order like assending or
desending if u want custom sorting then better to choose
Comparator.
6 . what is bubble sort can you write one programme. .?
public class ArraySort {
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };

for (int i = 0; i < arr.length; i++) {


for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
System.out.print(arr[i] + ",");
}
}
}

7 . can I write try block single means without using try-catch or try-finally
ans: yes we can write .in java 1.7 there is one features try-with-resources by
which ur resourse stream will be closed automatically
8 . what is Executor framework
ans:Executor Framework is interduced in Concurrent package normaly if we want use
thread pool to achive reusability then we have to choose this one
9 . how many way we can create thread and which one best approach and why
ans:There are 4 way

1 . extends Thread
2 . implements Runnable
3. implements Cloneable
4 . using AnonymousThread

Preferable is 3rd one coz if you implements from Callable then see below

class MyThread implements Callable {

public Object call (){


return obj;
}
Here after execution my thread return something based on requirements u have to
choose
2 nd approach also good
In both cases we can achive fully abstraction and runtime polymorphism nd multiple
inheritance so 2 nd 3 r best approach

10 . jdk version u r using in ur project and why (be care on that question coz they
indirectly ask u the advantages of version or latest features added in New
version )

We are using jdk 7


Then tell all the advantages Like
1 . try with resources
2 . multi catch Exp Handler
3 . String Switch case
4 . Diamond Operator
6 . simple way to declare long variable

*Jdbc:-
**********
1 . difference between Statement and PreparedStatement
ans:Statement are use if we want to pass static querry or hardcoded value if we
uant to pass positional parameter/Runtime value
then better to use PreparedStatement and in Simple Statement there may be a chance
to get SQL Injection which we can be
Resolve by PreparedStatement
2.they give one db schema and ask me to retrieve data from DB by passing id
table:-
=====
id name
=============
101 Basant
104 Santosh

final String SQL_QRY_FOR_GET_NAME_BY_ID="SELECT NAME FROM EMPLOYEE WHERE ID=?";


1.class.forName()
2.Connection con=DriverManager.getConnection();
3.PreparedStatement ps=con.preparedStatement(SQL_QRY_FOR_GET_NAME_BY_ID);
4.ps.setParameter(1,101)
5.ResultSet rs=ps.executeQuerry();
6.Itterate

*Spring :-
**********
1.What is RowMapper when we have to use it write sample code not completely just
give sm hints with flow?

ans:See basically if we want to iterate complete entity from db then we have to use
RowMapper which are
Provided by Spring-Framework by which it can easily featch the data from db and it
follow call back
Mechanisim so it gives us Resultse as method parameter that we can simple get the
data by RS

2.what is ResultSet Extractor where exactly we have to use ?


ans: ResultsetExtractor is used if we want to iterate data from db with some
specific range or partial ,ya i used it in my
project for pagination by assuming display pageNo and size as per SRC

3.if in my Spring bean configuration file I configure same bean with same id 2
times then what is the problem and how to resolve it (contender)
ans:we have to use one atribute in Spring-beans configuration file actualy i am not
able to remebere that word
properly coz we are using eclips id so but it like something Contender ...

4 . Spring Mvc Flow as per your Project


= = = = = = = = = = = = = = = = = = =
To make webapp
=====================================
??1 .First From browser u forward request to servlet (Dispatcher Servlet) to handel
it..

??2.Dispatcher Servlet here act as a controller. Who only manage the request
processing. ..so it rcv the request and then forward request to HandlerMapping

??3.Handler mapping is framework provide class..Normally in mvc there r several


controller Bean so HandlerMapping helps to search appropriate controller Bean based
on request url to perform business operation

??4.and 5 After finding controller Bean it process some operation and return MAV
object ..to Dispatcher Servlet
M:-model
A:-and
V:-view

??6 . Now after processing business operation response will be generated and it
should be display on browser otherwise how enduser know about response. ..so to
find appropriate view representer..Dispatcher Servlet call again ViewResolver.
.which helps to find appropriate jsp to display view

??7 . Then Dispatcher Servlet render data nd call that jsp which is identify by
ViewResolver to view response on browser. ..

??8. Finally Response will be receive by End user. ..

5.Spring transaction, why nd how to work on it


ans: we are using Annotation Approach @Transactional(read-
only="false",isolation="Read-Commit",propagation="Required")

6. How u handle Exception in ur Project just give some brief idea on it with
annotation
ans: ya to handle the exception we are creating separate Controller class
annotatted with @AdviceController and here we are
writting one method by passing the exception as parameter and annotated with method
@ExceptionHandler then from my controller
i have to pass same logical name which i already return from my adviceController
class

*Webservices :-
**************
1 . WSDL ,what are the elements and just explain the role of each section verbally
ans:
WSDL(Web service Description Language) actually it act as contract betwwen
provider and consumer and basically contain 5 section 1)Defination 2)types
3)Message 4)PortType 5)Binding 6)Service
Defination:-it act as a root element in XML it just specify the name
types:-it talks about each indivisual required input and output to my webservice
method
message:-it talks about exactly what my web-service method takes a parameter in
single unit
portType:-it talks about exact structure of your SEI(Service endPoint Interface)
Binding: talks about what is the protocol it used and which Message Exchanging
format it follows
service: it talks about address

2.what is Rest,
ans: Rest is a new architectureal style of develope the webservice or we can say
this one is the easyst way to our
complex business logic over the network with distrubuted technology with
interorporable manner

3 . difference between Soap and Rest ?

ans:Both are used to develope webservices only but the basic difference
1.In sopa base web-service we need to depends on Sopa protocol it act as a
transport protocol who support only Xml for transfer
but in rest it is support not xml it supports XML,JSON,PLAIN_TEXT also
2.Sopa development is complicated in comparision Rest coz we need to depends on
Multiple 3rd party vender
and procudure is varry from one implementation to anothe implementation
3.Sopa is not Message-Represention-Oriented but rest is M-R-O
4.for security and transaction Soap is Preferable..
4.Write one Resource method using Http method Post

5.which Response u provide to presentation layer and how to bind Json Response ?
ans: We are providing JSON Responce and it will bind through Angular js in UI.

6.Difference between @QuerryParm and @PathPatm which one best and where to use. ..
ans: QuerryParm is not mandatory to pass but if u want data is mandatory then
PathParm is Best

Core-Java----1 st round
===================
1.Interface & abstract class ?

ans:Interface is a special type of class through which we can achive fully


abstraction
runtime polymorphisim and multiple inheritance which makes our code completely
loose coupled
but in abstract class also we can achive abstraction and R.P but partially..coz it
contains both abstract method as well as concret method but in abstract class u
can't get
multiple inheritance

2.How can u achive Abstraction With Real Time Example(Project) ?

ans: As per my project what we people are developed that will be hidden from user
so
for them it is abstraction otherwise explain Hari sir Bank Atm example

3.In your Project Where u are using oops concept..?

ans: Ya we implement all the concept in our project and Encapsulation we used in
Business Object or Model class
Inheritance and Polymorphisim we implement in Dao and Service Layer to make it
loosly coupled

4.Encapsulation u are using in ur project in which layer. ?


ans: Ya we are using In Model layer (BO,DTO,FORM)

5.To override all the method from super which keyword we have to use.and why
ans: implements keyword coz class+interface== always implements

6.Why abstract class achive less abstraction why not interface.?


ans: Cause Abstract class contain boh concrete and abstract method but it's not
mandatory that
My subclass always override supperclass method so there is no guarentee to achive
fully abstraction

7.Write 5 classes which u r develope in your project with fully qualified name ?

Just mention as below


1.MODULE_NAME_DAO---------com.productOwnersortname.module.layer
2.MODULE_NAME_SERVICE
3.MODULE_NAME_CONTROLLER
4.MODULE_NAME_BO
5.MODULE_NAME_DTO
6.MODULE_NAME_MAPPER
.MODULE_NAME_UTIL

8.What are the exception u face in ur project development and how u resolve them
explain ?
ans:
1.NullPointerException:-Resolve by Remote Debugging
2.DataAccessException:-Enter the Column name properly this exception from DAO
3.ClassCastException:-Mentain Typecast or Generics properly

9.Why u are using Spring-jdbc why not hibernate ?


ans:Coz my project is Intranet Application and it handles huge amount of data for
persist and retrive thats why we are using Spring-Jdbc

10.Which security u are using..?


ans:Simple Authentication by using Spring
11.Level of log(Which one u use in your project)
ans: DEBUG,ERROR,WARN

Second-Round(CoreJava+Spring)
===========================
1.What is abstraction
ans:Hide the implementation Provide only Functionality is called abstraction
2.How to create own immutable class write code
public class MyImmutable {

int no;

public MyImmutable(int no) {


super();
this.no = no;
}

public MyImmutable modify(int no) {


if (this.no == no) {
return this;
} else {
return new MyImmutable(no);
}
}
}

3.What is singletone ,In your project did u use singletone ,Where write code ?
ans:Singleton is object creation design pattern by which we can instantiate only
one instance
per one class per one jvm.
In my project i didn't use coz we are using Spring so every bean scope is
singleton
so we no need to make explicitly singleton.

4.Why List allow duplicate why not Set with internal ?

ans: Coz List internally follw Array Concept so no there is no restriction in


array to allow duplicate but in case of Set it internally follow Map which object
u add in
set it will be placed as key in That internal Map so duplicate not allowed in Set
Just explain the flow of Map ok if he ask more.....

5.What is Dependency Injection ?

ans:Dependency Injection is a process of inject dependency in Dependant class


automatically we no need create object and no need to map with object .it
internally
follow Strategy design pattern

6.Which type of Injection u are using in ur project and why..


ans: We are using both setter and constructor injection both coz some fields we
need to compolsory
inject and some fields are optional for our project

7.What is autoware,Type explain with sample code


ans:Autowire is auto enable dependency Inject
it is 3 type:1)byName 2)byType 3)Constructor

8.Which version Spring u used.. ?


ans:4.x
9.What are the annotation u are using in ur project ?
ans:-
@Componet,@Service,@Controller,@Autowire,@Transactional,@Scope,@ControllerAdvice,@E
xceptionHandler
@RequestParm,@PathVariable,@ModelAttribute,@PropertyResource
10.Write Spring-transaction configuration
ans:
<aop:config>
<aop:pointcut expression="execution(*
com.dt.service.ManageEmployeeService.*(..))" id="manageEmpPct"/>
<aop:advisor advice-ref="manageEmployeeTxAdvice" pointcut-
ref="manageEmpPct"/>
</aop:config>

<tx:advice id="manageEmployeeTxAdvice">
<tx:attributes>
<tx:method name="new*" read-only="false"
propagation="REQUIRED" />
<tx:method name="*" read-only="true" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

11.Spring-Transaction annotation details with attribute why ?


ans: @Transactional(read-only="false",Isolation="Read-
Commit",Propagation="Required")

12.@Qualifier annotation use with example ?


ans:@Qualifier annotation used to avoid ambiguity error
ex:
<bean id="a1" class="A">
<bean id="a2" class="A">
here class is same but id is different so here my IOC Container confuse due to
same class
found multiple time so here bean id u want mention in @Qualifier("a1") then
IOc will instantiate that bean only

13.@RequestParm and @ModelAttribute where we have to use..


ans:If from form page or from UI page u want to get more 2 to 3 element then use
@RequestParm
ex:just assume from login page how many element u will get 2 username and pwd use
@RequestParm
if incoming data will be more then bind them in one object by using @ModelAttribute
ex:Suppose u book a ticket then lot of data u have to pass as input
like movieName,Time,Location,Nearest hall...etc then choose @ModelAttribute

14.What is ur daily activity in ur working environment


ans:Sensiourly working in service and dao based on user story
code testing and write junit test case and test it 2 to 3 times
participate in daily-Scrum

Interview Questions Asked In HCL(Telephonic Round)


1.how to put class in hash map?
2.custom exceptions?(how u will write)
3.XML(total details?)
4.how to iterate database values?
5. what is jndi and explain?
6.weblogic(how u will deploy application in weblogic?
Hiebrnate
1.hibernate interfaces?
2.hql queries?
3.how u will change oracle to mysql ?
4.hql to eliminate duplicate values?
spring
1. spring ioc?
2.autowiring? how u implementd?
3.setter and constructor injection ?what u implemented in u r project?
4.how to load optional beans?
5.scopes of beans?
General
1. static where u used in ur projects?
2.in hash map can u take key as object?
3.hash map(can hash map key allow duplicates)?
4.collections used in u r project?
5.what are the packages u used in ur projects?
6.hash set?
7.how u will eliminate duplicate values from a table?
8.prototype and singleton difference?
9.load on start up?
10.auto boxing and unboxing?

how to manage exception in project which is being developed in spring..


Multiple way is there, but it's quite easy to implement with spring mvc.

Normally we are developing Spring based application so in Spring to handle


exception multiple predefined class is there .so simply in my project we are
throwing custom exception from service layer and when my controller call service it
will catch that exception by using Spring-Aop , We have to create a class which
should be annoted as @ControllerAdvice and we have to take one method whose return
type is Model And View and method should be annoted as @ExceptionHandler so in this
method we have to write the logic for map the exception. And return the same view
which is return by controller class at the time of exception raise. And we have to
return some user understandable message by view page.
Note: Both return logical view should be same

Plz explain Diff between GET and Load in hibernate . just highlight the point
When ever u have requirement that deleting row u dont need to get the comple object
just load proxy object with id u calln delete it
Deleting object from db
By get
Select * from emp and
Delete from emp where id=123
Load
Delete from emp where id =123
In load is best when deltion opration

When ever u have requirement that update / select row then get is best chioce...
need to get the comple object and then update with new values

By get
Get complete object
Update Set new values
Load
Select ....
If set the value it ill load each seeting a new proxy sl it ill degrade
performance...

In interview they r asking wat kind of design document u r prepared


Pls suggest the answer
deployement doc ,srs doc ,secnario doc ,uml doc use case doc

why main() has less priority than static{} and static()


main() is static method..according to execution priority order at class loading
time memory first allocated to static variables then static blocks wil be
executed,then static methods...

how can we deploye application in server in realtime?


ChangeManDs ...
U need to upload your war/ear each devloper will take updated code by the svn and
they make war/ ear have to upload in change man and u i can acess the site direct
like normal site...
Suppose im a dev shahid some other dev ravi is there i have done my changes at the
same time ravi also has done his changes then i can ask to ravi whether his
devlopment completed or not if he said completed i ask hin to update in svn and ill
merge code and ill war /ear in change man and agter that has to promote dev
enviroment ...if it giving expected results for me then ill raise request to aq
people to test if it working fine then they ill pomote iat and then finally
production. ....
There y asked ravi to sync code is if i uploaded ear it ill 30 mins to avail in
server so it is better to synchronize with team...after i update again ravi updated
means 1 hr wast right. ..
The ur for in dev which i have tested is
Www.bhpa.com/dev1/.....etc
Www.bhpa.com/qa2/...
Www.bhpa.com/iat

Hi friends any one knows ofbiz in j2ee technology


ofbiz framework

Can anyone explain me the meaning of term "Inversion of Control" in spring?


The question is "What sort of control are they inverting"?? I just want to dig
dipper into this term ??...Thanks in advance
IOC is a principle. IOC will collaborate the object. Collaborate means manage the
object by injecting one
object into another. IOC will manage the life cycle of the object. Since spring
container can also
collaborate the object and manage the life cycle of the object so it is called as
IOC container. There are two
ways using which we can collaborate objects.
IOC is of two types, again each type is classified into two more types as follows-
1. Dependency Lookup
a) Dependency Pull
b) Contextual Dependency lookup
2. Dependency Injection
a) Setter Injection
b) Constructor Injection
Dependency Lookup-
It is very old technic which is something exists already and most of the J2EE
applications use. In this
technic if a class need another dependent object, it will write the code for
getting the dependency. Again it
has two variants as said above.
a) Dependency Pull
If we take J2EE web application as example, we retrieve and store data from
database for displaying the
web pages. So, to display the data our code requires connection object as
dependent, generally the
connection object will be retrieved from a connection pool. Connection pool are
created and managed by
application server. Below diagram shows the same-
Our component will look up for the connection from the pool by performing a JNDI
lookup. it means we
are writing the code for getting the connection indirectly we are pulling the
connection from the pool. So,
it is called dependency pull.
pseudo code
Context ctx=new InitialContext();
DataSource ds=ctx.lookup("jndi name of cp");
Connection con=ds.getConnection();
//pulling the connection?

b) Contextual Dependency Lookup


In this technic our computer and our environment/server will agree upon a
contract/context, through
which the dependent object will be injected into our code. For example-
If we our servlet has to access environment specific information (init params or to
get context) it needs
ServletConfig object, But the servletContainer will create the ServletConfig
object. So in order to access
ServletConfig object in our servlet, our servlet has to implement servlet interface
and override init
(ServletConfig) as parameter. See the below diagram-
ServletConfig will be injected into servlet by the container. Now the container
will pushes the config object
by calling the init method of the servlet. Until our code implements from servlet
interface,container will
not pushes the congig object, this indicates servlet interface acts as a contract
between we and our servlet
. thats why it is called Contextual dependency lookup.
Dependency Injection
The new way of acquiring the dependent object is using setter injection or
constructor injection
1.Setter Injection
In setter injection if an object depends on another object then the dependent
object will be injected into
the target class through the setter method that has been exposed on the target
classes as shown below-
package com.si.bean;
class Car
{
private Engine engine;
public void setEngine(Engine engine)
{
this.engine=engine;
}
public void start()
{
engine.start();
}
}
}
package com.si.bean;
class Engine
{
private int engNo;
public void setEngNo(int engNo)
{
this.engNo=engNo;
}
public void engStart()
{
System.out.println("Engine starts");
}
}
In above application Car needs the object of Engine it means Car is the
target class in which the dependent object of Engine will be injected by calling
the exposed setter method.If we want our class to
be managed by spring then we have to declare our classes as spring beans in spring
bean configuration
file as follows-
application-context.xml
<beans>
<bean id="car" class="com.si.bean.Car">
<property name="engine" ref="eng"/>
</bean>
<bean id="eng" class="com.si.bean.Engine">
<property name="engNo" value="E1"/>
</bean>
</beans>
2.Constructor Injection
In this technic instead of exposing a setter, your target class will expose a
constructor, which will take the
parameter as our dependent object. As our dependent object gets injected by calling
the target class
constructor, hence it is called constructor injection as shown below-
package com.si.bean;
class Car
{
private Engine engine;
public Car(Engine engine)
{
this.engine=engine;
}
public void start()
{
engine.start();
}
}
package com.si.bean;
class Engine
{
private int engNo;
public void setEngNo(int engNo)
{
this.engNo=engNo;
}
public void engStart()
{
System.out.println("Engine starts");
}
}
In target class Car we have declared constructor in which attribute engine is
of dependent type Engine is
declared as parameter in it. Now to tell the spring to manage the dependency again
we have to declare
car and Engine as bean in Spring bean configuration file like following-
application-context.xml
<beans>
<bean id="car" class="com.si.bean.Car"><constructor-arg ref="eng"/>
</bean>
<bean id="eng" class="com.si.bean.Engine">
<property name="engNo" value="E1"/>
</bean>
</beans>
Now create the IOC container and test the application as below-
package com.si.bean;
class CarTest
{
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("application-
context.xml"));
Car c=(Car) factory.getBean("car");
c.start();
}
}
O/P
Engine starts
In both setter injection and constructor injection we are asking the Car object
from IOC container it will
give us by injecting Engine class object. So, when we call star() method of car
class it will goes there and
call EngStart() method of Engine class. Hence, we see that we have not created the
Engine class object it is
created by spring and injected into the Car class object either by setter or
constructor.
Usually we will create the object and place it in the container and use it. So here
you have the control over objects.

In case of spring, the task of creating the objects, and supplying it where ever
necessary is taken over by Container.

As the control is inversed ( reversed ) , we call it as "inversion of control"

how should i start explain about project architecture. means , what kind of thing i
have to tell.should i mention the technologies which i have used in my project .can
anyone tell me the best way to explain about project architecture?

Project Architecture means to be straight it depends on your project IG,

For Example I am giving any health care project OK.

So first u should tell


1.Project name
2.Client
3.Technolgy used
4. What are the modules and sub modules.
5.which module u worked

Then starts from your UI things

Draw a project UI then pull one by one concept.

Means explain this is the scenario where I used soap web service or rest

This is the case where I used JMS. Collection,

And always explain him like assume I have user online appointment page OK.

So tell their we have one registration page after fill data there is register
button, by clicking on that request goes to controller--service - - server
Validation - - - Dao

It stores on our local DB nd mapped with multiple Sub Resource DB.

Like this u have to explain.

This is the sample I explained. Based on ur project flow, follow the same approach.

Can anyone post a example on how to create a simple maven multi module project
using spring MVC with service and dao with one working example ?
Yes I already did the same thing also I copied child module groupid, archetypeId
and version copied and attached in parent as a dependency , but where I need to
place our service and dao classes, when we run the parent project automatically all
child modules also get executed and display the output. How I will do it , can u
send me in sample and derive that process also.
Create a parrent folder and create pom for that. and then add code as per below.
And create separate folder for each module and they have their own pom again
<packaging>pom</packaging>
<modules>
<module>logging-module</module>
<module>scheduler-module</module>
<module>customer-module</module>
<module>sales-module</module>
</modules>

how many ways we can send data to resource in restful services..?


Header in (@Headersparam) , cookies-(@cookiesParam) uri-(@QyeryParm
TemplateParm
Matrix parm @ pathparam ) via body(.XML 2.JSON 3.Simple Raw )

why we cannot apply j2ee security for web service security.why we should go for ws-
security?
We can add simple J2ee security also np. But it's is very less secure. Nd
internally ws policy or interceptor internally follow Web security only with
different mechanism like token, bit size increase
security will not work in all situations. There can come a time when the client can
talk to multiple servers. An example given below shows a client talking to both a
database and a web server at a time. In such cases, not all information can pass
through the https protocol This is where SOAP comes in action to overcome such
obstacles by having the WS-Security specification in place. With this
specification, all security related data is defined in the SOAP header element.

Hii everyone...
After completing the project architecture generally interviewed ask where u used
customer exception,multithreading,encapsulation,abstraction,and singleton bean...
in your peoject.... can any one explain all topic
Encapsulation :we used in our Entity/Model/pojo class

Custom Exception :Normally we are using it from dao and service layer like suppose
m searching user from db based on id.

If it is not found in db. Then from service we need to throw out custom exception
and in controller we need to use try catch to handle this.. Nd wrapping the failure
response in in catch itself.

Singleton :depends on which framework u r using.

If u r using Spring then u can say by default every bean scope is singleton so we
are not writing it manually.

Else tell like u r making singleton where u r getting SessionFactory instance and
Invoked class means which called other services.

Multithreading :no used as of now

We have custom exception for our project ,in that for a porject there is one base
exception,after that for module spearte exception is extended from base
exception,then for a layer exception and for operation one exception all those are
hierarchical

difference b/w homogenous and heterogeneous objects....?


A container that contains or holds objects of a single type is said to be
homogenous. On the other hand, A container that contains objects (derived from a
common base class) of a variety of types is termed heterogeneous. EX LIKE Array
contains student type of data if we insert employee data then it will throw
exception. Heterogeneous means like collection ,in collection we can take different
type of object at a time .

Hi,
in the scorecard, every second automatically refreshes and displays present score
how it works and implementing by using java?
I mean not using java only. Create an object scoreboard which gets updated on
every time a record being insert or update into db. In ui use meta refresh as 5 to
make your data update in every 5 seconds or else use ajax.
bro absolutely R8. For this we need to use any in memory container to update and
fetch.

M providing static code using multithreading.

package com.sjgm.question;

public class ScoreBoard {

public synchronized void displayScore(String teamName, int over) {

for (int i = 0; i <= over*2; i++) {

System.out.println("Current Run by :" + teamName + "-" + i);

package com.sjgm.question;

public class India extends Thread {

private ScoreBoard scoreBoard;

public India(ScoreBoard scoreBoard) {


this.scoreBoard = scoreBoard;

@Override

public void run() {

scoreBoard.displayScore("IND", 50);

package com.sjgm.question;

public class SouthAfrica extends Thread {

private ScoreBoard scoreBoard;

public SouthAfrica(ScoreBoard scoreBoard) {

this.scoreBoard = scoreBoard;

@Override

public void run() {

scoreBoard.displayScore("SA", 50);

package com.sjgm.question;

public class UpdateScore {

public static void main(String[] args) {


ScoreBoard scoreBoard = new ScoreBoard();

India india = new India(scoreBoard);

SouthAfrica southAfrica = new SouthAfrica(scoreBoard);

india.start();

southAfrica.start();

}
Asking in interviewer
1.wap to the prime number without using for loop.
2.calculate length of linked list without using counter.

Map is not a child interface of collection then what is the relation between them?
Collection was designed for better memory management in java based on Data
Structure..
If a Map is a Collection, what are the elements? The only reasonable answer is
"Key-value pairs", but this provides a very limited (and not particularly useful)
Map abstraction. You can't ask what value a given key maps to, nor can you delete
the entry for a given key without knowing what value it maps to.

What is filter?How can we use filter concepts in realtime projects?


filters are used for intercepting the requests like validating ip address,profiling
and auditing and authenticating..
Yup term wise different there bro but function wise both hv same. Both handling pre
processing logic.

Yes if we compare filter with interceptor then interceptor provide more features
like some predefined bean is there so we no need to write class and bunch of
configuration for it.

we have interface is there and again y enum was developed? interface contains final
variables and enum also final y?
Interface not Interduced to declare final variable..

Interface is used to achieve oop principles.

Enum only we need to use for declare constraints


Yes Basant is correct interface purpose is to provide loose coupling and enum is to
declare constants and both have their own way of action.

1.what is difference between lazy loading and aggressive loading? 2.what is eager
and lazy fetch types? 3.what is the purpose of mapped by in hibernate?
Eager and Lazy fetch in hibernate

Just consider one to many examples like one customer by multiple products OK. So
what we have to do.

class Customer {
Private List<Product> products ;
}
class Product {}

So here when I want to load all parent with child then I need to specify fetch
eager.

If I will not specify it will take default value as lazy and will load only parents
not child.

Mapped by is nothing by using this annotation we are informing to hibernate to


generate foreign key column in mapper entity

what is difference between @produce and @consume annotations?


The information sent to a resource and then passed back to the client is specified
as a MIME media type in the headers of an HTTP request or response. You can specify
which MIME media types of representations a resource can respond to or produce by
using the javax.ws.rs.Consumes and javax.ws.rs.Produces annotations.
By default, a resource class can respond to and produce all MIME media types of
representations specified in the HTTP request and response headers.
The @Produces Annotation
The @Produces annotation is used to specify the MIME media types or representations
a resource can produce and send back to the client. If @Produces is applied at the
class level, all the methods in a resource can produce the specified MIME types by
default. If it is applied at the method level, it overrides any @Produces
annotations applied at the class level.
If no methods in a resource are able to produce the MIME type in a client request,
the Jersey runtime sends back an HTTP 406 Not Acceptable error.
The value of @Produces is an array of String of MIME types. For example:
@Produces({"image/jpeg,image/png"})
The following example shows how to apply @Produces at both the class and method
levels:
@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
@GET
public String doGetAsPlainText() {
...
}

@GET
@Produces("text/html")
public String doGetAsHtml() {
...
}
}
The @Consumes Annotation
The @Consumes annotation is used to specify which MIME media types of
representations a resource can accept, or consume, from the client. If @Consumes is
applied at the class level, all the response methods accept the specified MIME
types by default. If @Consumes is applied at the method level, it overrides any
@Consumes annotations applied at the class level.
If a resource is unable to consume the MIME type of a client request, the Jersey
runtime sends back an HTTP 415 Unsupported Media Type error.
The value of @Consumes is an array of String of acceptable MIME types. For example:
@Consumes({"text/plain,text/html"})
The following example shows how to apply @Consumes at both the class and method
levels:
@Path("/myResource")
@Consumes("multipart/related")
public class SomeResource {
@POST
public String doPost(MimeMultipart mimeMultipartData) {
...
}

@POST
@Consumes("application/x-www-form-urlencoded")
public String doPost2(FormURLEncodedProperties formData) {
...
}
}

what difference between tx:annotation-driven and mvc:annotation-driven?


Tx: means trasaction ralelated mvc : mvc realated
annotation-driven
Annotation will enabled
Tx:means transcation related annotation enables suppose if u used transcation in ur
projct u ill @Transactional annotation
By defult it wont be enable if u r using configuration to enable u have to use
tx:Annotation-drven...
||ly mvc @controller mvc related enabled

use of lazy and eager loading in spring?


Like u have 2 bean I.e A nd B and u want that B should be instantiate before A so
in this case we need to initialize it early so we need to use
@DependsOn or u can use depends-on attribute in xml configuration on same bean
declaration

Is it possible to write static method in abstract class? justyfy your answer?


Yes we can write, but no use of it cause it will not participate in override. So
it's useless
abstract class AbstractDemo{

public static void m1(){


System.out.println("static method");
}

public static void main(String[] args){

AbstractDemo.m1();
}
}

Mam can you please run this.

is this possible to create an array of 0 length? if so how? if not so why? coz we


have an array in main() likw this "static void main(String [] s) then what it
signifies?
Yes.0size posible.string arg() takes runtime arguments.
Yes we can create Array without mention any length. Like.

String[] strArray=new String[] {"abc", "ghg",...... } ;

what is difference between executor.submit() and executer.execute() method


please go throw below code and comments u will understand the what exact differenc
and when we choose which one.package com.sjgm.question;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableSample implements Callable<String> {


/*
* Based on Generic which u will pass at class level method return type will
* be same i passed Callable<String> so return type of call is also String u
* can change based on your Requirement
*/
@Override
public String call() throws Exception {
System.out
.println("This will print execute() call cause execute() method dont have return
type ");
return "Wao ! Method returning some dummy";
}

public static void main(String[] args) throws InterruptedException,


ExecutionException {
/*
* newFixedThreadPool(2) i passed 2 here cause want to get 2 thread
* reference from POOL
*/
ExecutorService service = Executors.newFixedThreadPool(2);

/*
* service.submit(task) will take my task and provide to my 2 thread
*/
Future<String> future = service.submit(new CallableSample());
System.out.println(future.get());
/*
* as its return type is void so we should prefer here Runnable insted
* of Callable if u want using ExecutorService Framework specially it
* will help full to achive thread pull concept
*/
service.execute(new Task());

}
}

class Task implements Runnable {

@Override
public void run() {
System.out
.println("Hi It will execute by while call execute() cause no return type");
}

}
What is the difference between spring 2.0 and spring 3.0 and spring 4.0 ??????

You might also like