Tell us about what you consider as your Weak Area ?
Things you find Difficult to Manage?
How would you Evaluate your Analytical Skills?
Give us an Instance when you Failed in spite of your Best Efforts?
I would like to hear about some Experience from your Work Life so Far ?
In what ways do you think you are Suited for this Job?
How can you Contribute to this Organization?
What is your Way of Handling Conflicts?
Can you tell us about a Challenging Situation at work you have Encountered so Far? How did you Tackle it?
If you had to Live your Life over Again ? What one thing would you Change?
What Qualities do you feel a Successful Manager Should Have?
What is your Long term Objective?
If the Interviewer asked me about a time When I had been in a Leadership Position and there was a difficult member of the team who was causing some Aggravation, and How I handled the situation ?
5. I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
Ans. The existing object will be overwritten and thus it will be lost.
Can a vector contain heterogenous objects?
Ans. Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
7. Can a ArrayList contain heterogenous objects?
Ans. Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList ?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
What is an enumeration ?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
What are the steps in the JDBC connection ?
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\” driver classs for that specific database\” );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\”select * from TABLE NAME\”);
Step 4 : Exceute the query :
stmt.exceuteUpdate();
What is the basic difference between the 2 approaches to exception handling…1> try catch block and 2> specifying the candidate exceptions in the throws clause? When should you use which approach ?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
How does ConcurrentHashMap works in Java ?
is ConcurrentHashMap is thread-safe?
Can we replace Hashtable to ConcurrentHashMap without external synchronization?
As you see there are multiple question in this category, those are mostly followup and can be answered if you understand ConcurrentHashMap well. you can see this article about Hashtable and ConcurrentHashMap to learn more.
What is CountDownLatch in Java?
What is CyclicBarrier in Java?
What is difference between CountDownLatch and CyclicBarrier in Java?
Concurrency is favorite topic on advanced core java interviews and its expected from experienced and senior Java developers to have good understanding of multi-threading and concurrency API in Java. See these post about CountDownLatch in Javaand Difference between CountDowntLatch and CyclicBarrier in Java.
What is Race condition ? Have you faced any race condition?
What is deadLock in Java? Write code to avoid deadlock in Java
Raced conditions and deadlock are major challenges while writing high performance concurrent Java applications and hands on experience of dealing with synchronization and concurrency issue expected from a senior and experience Java programmer. Refer how to avoid deadlock in Java and What is race condition in Java for more details.
What is PermGen space ?
What is memory leak in Java?
What is OutOfMemoryError in PermGen mens?
What is difference between NoClassDefFoundError and ClassNotFoundException in Java?
Have you analyzed thread dump? How do you analyze thread dump ?
How do you determine the memory required for your application?
Is using session to store data a good practice?
Difference between PATH and CLASSPATH in JavaHere are some of the common difference between PATH vs CLASSPATH in Java :
1)Main difference between PATH and CLASSPATH is that PATH is an environment variable which is used to locate JDK binaries like "java" or "javac" command used to run java program and compile java source file. On the other hand CLASSPATH environment variable is used by System or Application ClassLoader to locate and load compile Java bytecodes stored in .class file.
2) In order to set PATH in Java you need to include JDK_HOME/bin directory in PATH environment variable while in order to set CLASSPATH in Java you need to include all those directory where you have put either your .class file or JAR file which is required by your Java application.
3) Another significant difference between PATH and CLASSPATH is that PATH can not be overridden by any Java settings but CLASSPATH can be overridden by providing command line option -classpath or -cp to both "java" and "javac" commands or by using Class-Path attribute in Manifest file inside JAR archive.
4) PATH environment variable is used by operating system to find any binary or command typed in shell, this is true for both Windows and Linux environment while CLASSPATH is only used by Java ClassLoaders to load class files.
These were some notable difference between PATH vs CLASSPATH in Java and they are worth remembering to debug and troubleshoot Java related issues.
Can we override private method in Java - Example program
No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn't depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature.
Difference between Comparator and Comparable in Java - Interview Question
Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some difference between them, major difference between Comparable and Comparator is that former is used to define natural ordering of object e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object. Main usage of java.lang.Comparable and java.util.Comparatorinterface is for sorting list of objects in Java. For example to sort a list of Employee by there Id, we can use Comparable interface and to provide additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare age of employee, SalaryComparator to compare salary of employees etc. This brings another important difference between Comparator and Comparable interface in Java, you can have only one ordering via Comparable e.g. natural ordering, while you can define multiple Comparator for alternative ordering as discussed above. Coming to Interviews, this question is very common on 2 to 3 years experience Java interviews, and you just can't afford to not prepare this. It's definitely possible to achieve years of experience in Java, without writing your own Comparator or Comparable, especially if you are not doing active development or coding, but even though, you must know basics e.g. equals and hashcode,compareTo and compare. In this article, we will see some notable difference between Comparator vs Comparable in Java from interview perspective.
1) How does get method of HashMap works in Java?
Yes, this is still one of the most popular questions for senior developer, you can expect this on telephonic round, followed by lot's of related questions, see here for answers
2) Which two method HashMap key object should implement? (equals and hashcode)
3) Why should an object used as key should be Immutable? (so that hashcode always return same value)
4) How does ConcurrentHashMap achieves it's scalability? or sometime this interview question is also asked as, difference between ConcurrentHashMap and Hashtable in Java, see here for answers.
5) How do you share an object between threads? or How to pass an object from one thread to another? there are multiple ways to do that e.g. Queues, Exchanger etc, but BlockingQueue using Producer Consumer pattern is the easiest way to pass an object from thread to another.
6) How do find if your program has deadlock? ( By taking thread dump using kill -3, using JConsole orVisualVM), I suggest to prepare this core java interview question in more detail, as Interviewer definitely likes to go with more detail e.g. they will press with questions like, have you really done that in your project or not?
7) How do you avoid deadlock while coding? (By ensuring locks are acquire and released in an ordered manner, seehere for detail answer of this question)
8) What is busy spinning? Why should you use it?
One of the interesting multithreading question to senior Java programmers, Busy spinning is a waiting strategy, in which a thread just wait in a loop, without releasing CPU for going to sleep. This can be used in a particular scenario, where wait time is very minimal, by not releasing CPU or suspending thread, your thread retain all cached data and instruction, which may be lost if further suspended and resumed back in a different core of CPU. This question is quite popular in high frequency low latency programming domain, where programmers are trying for extremely low latency in range of Micro to Milli seconds.
9) What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?
ReadWrite Lock is an implementation of lock stripping, where two separate locks are used for read and write operation. Since read operation doesn't modify state of object, it's safe to allow multiple access of shared object to multiple reader without locking, and by splitting lock into ReadLock and WriteLock, you can easily do that. Java provides an implementation of ReadWriteLock in form of ReentrantReadWritLock, which is worth looking. AlsoConcurrentHashMap doesn't use ReadWriteLock, instead it divides maps into several segments and lock them separately using different locks, which means any given time, only a portion of map is locked, instead of whole map. This question is also very popular on Senior and experienced level Java interviews, expect Interviewer to go into more detail, e.g. asking you to provided an implementation of ReadWriteLock with different policies.
10) How to make an Object Immutable in Java? Why should you make an Object Immutable?
Well, Immutability offers several advantage including thread-safety, ability to cache and result in more readable multithreading code. See here to learn how to make object Immutable. Once again, this question can also go into more detail and depending upon your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.
11) Which design patterns have you used?
Always expect design and patterns related question for Senior developer Core Java Interview. It's best to mention any GOF design pattern rather than Singleton or MVC, which almost every other Java developer use it. Your best bet can be Decorator pattern or may be Dependency Injection Pattern, which is quite popular in Spring Framework. It's also good to mention only design pattern, which you have really used in your project and knows it's tradeoffs. As once you mention a particular design pattern say Factory, Interviewer's next question would be, have you used in your project? So be ready with proper example and why you choose a particular pattern.
12) Do you know about Open Closed Design Principle or Liskov Substitution Principle?
Design patterns are based upon object oriented design principles. I strongly suggest to take a look at my article 10 SOLID and Object Oriented design principle, Java programmer should know, to at least have a basic idea of what are these principles and how they help you to write better object oriented code. If you don't know answer of this question, you can politely say no, as it's not expected from you to know answer of every question, but answering question, which most developer doesn't answer, can make your candidature much stronger.
13) Which design pattern you will use to shield your code from a third party library, which will likely to be replaced in another couple of years?
This is just another example of scenario based design pattern question, you can expect in different formats, some with more detail explanation with context, or some with only intent around. One way to shield your code form third party library is todepend upon interface rather than implementation and than use dependency injection to provide a particular implementation. This kind of questions are also asked quite frequently to experienced and senior Java developers with 5 to 7 years of experience.
14) How do you prevent SQL Injection in Java Code?
This question is more asked to Java EE developers than core Java developers but still a good question to know,PreparedStatement is the way to go. PreparedStatement not only provides better performance but also shield from SQL Injection attack. If you are working more on Java EE or J2EE side, than you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them.
15) Tell me about different reference type available in Java, e.g. WeakReference, SoftReference or PhantomReference? and Why should you use them?
Well, they are different reference types coming from java.lang.ref package and provided to assist Java Garbage Collector in case of low memory issues. If you wrap an object with WeakReference than it will be garbage collected if there is no strong reference and GC is running low on memory. WeakHashMap is a Map implementation, whose keys usesWeakReference, so if only Map contains reference of any object and no other, those object can be garbage collected, if GC needs memory.
Memory Leak in Java Application
Saying that a Java program can have memory leak is little surprising for many programers, because they think that Garbage Collector will reclaim memory, and that's one of the reason, why Java is popular programming language. Bug, GC has it's limitation, it can not reclaim the object, which is undesired but still refrenced by some object in Program. This memory, which should be free but still can not be reclaimed is called Memory leak in Java. If you see java.lang.OutOfMemoryError:Java heap space, even after increasing heap space, than it's good to analyze memory pattern for any possible memory leak. There are tools like Profiler (JProbe, Yourkit or Netbeans Profiler), JConsole, VisualVM, which you can use to see memory usage of Java application to confirm memory leak. There are even tools like Plumber, which can help you to find memory leaks in Java. Though this would be as easy as increasing heap memory to fixjava.lang.OutOfMemoryError: Java heap space.
Difference between Error vs Exception in Java - Interview question
Both Error and Exception are derived from java.lang.Throwable in Java but main difference between Error and Exception is kind of error they represent. java.lang.Error represent errors which are generally can not be handled and usually refer catastrophic failure e.g. running out of System resources, some examples of Error in Java are java.lang.OutOfMemoryError orJava.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand java.lang.Exceptionrepresent errors which can be catch and dealt e.g. IOException which comes while performing I/O operations i.e. reading files and directories.
How to Convert Array to Collection, Set and List in Java with Example
Arrays.asList() returns a List object which can be used in the constructor of a collection object.
String[] operatingSystems = new String[]{"Windows", "Linux", "Android", "iOS", "Solaris"};
// Convert array to Collection in Java
Collection collection = Arrays.asList(operatingSystems);
// Convert String array to Set in Java
Set set = new HashSet(Arrays.asList(operatingSystems));
// Convert String array to List in Java
List list = Arrays.asList(operatingSystems); logger.info("List created from Array in Java : {}", list);
What is difference between Thread vs Process in Java
Thread and Process are two closely related term in multi-threading and main difference between Thread and Process in Java is that Threads are part of process. i.e. one process can spawn multiple Threads. If you run a Java program in UNIX based system e.g. Linux and if that program creates 10 Threads, it still one process and you can find that by using ps -ef | grep identifiercommand which is one of most popular use of grep command in UNIX, Where identifier is unix text which can be used asregular expression to find that Java process. Another major difference between Process and Thread is that, each process has its own separate memory space but Threads from same process same memory space. Some linux command map Java thread withlight weight process or lwp, e.g. if you use prstat command in Solaris, you can get how many light weight process or Thread a particular Java program is using.
SPRING
Difference Between @Component, @Service, @Repository and @Controller
Spring Configuration for Component-scanFor these beans to be instantiated by Spring, we need to have the following configuration in the spring configuration XML. Assuming com.javapapers.spring is a base package containing these classes. Needless to say, these Java classes should be part of the application classpath.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.javapapers.spring"/> </beans>
Disable automatic scan of @Component, @Repository, @Service, @Controller:This automatic scan behavior can be disabled for the default stereotypes by setting the use-default-filters property to false,
<beans> <context:component-scan use-default-filters = "false" base-package="com.javapapers.spring" /> </beans>
Customize Default Spring Scan BehaviorWhen component-scan is enable, by default spring scans for @Component, @Service, @Repository and @Controller stereotypes only. All the classes present in the classpath coming under the base-package annotated with these stereotypes will be auto-detected. We can modify this default Spring behavior using include-filter or exclude-filter attribute of the component-scan attribute. There are five filter types available ‘annotation, assignable, aspectj, regex, custom’ and they can be used as below,
<beans>
<context:component-scan base-package="com.javapapers.spring">
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="assignable" expression="com.javapapers.spring.AnimalService"/> </context:component-scan>
</beans>
How can you give the bean name as part of the class definition ?
Bean NamingFor all @Component, @Service, @Repository and @Controller stereotyped components the bean name is assigned based on BeanNameGenerator strategy. We can also supply our name choice during annotation and that will take high precedence.
@Service("lionKing") public class LionService { // ... } @Repository public class AnimalJpa { // ... }
For LionService the instantiated bean name will be lionKing which we have supplied, but in the case of AnimalJpa the bean name will be animalJpa. This behavior is same for all sterotypes @Component, @Service, @Repository and @Controller.
http://javapapers.com/spring/spring-component-service-repository-controller-difference/
http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
http://www.journaldev.com/2696/spring-interview-questions-and-answers
http://www.journaldev.com/7153/java-101-tutorials-learn-java
http://javarevisited.blogspot.in/2010/10/why-string-is-immutable-in-java.html
Any wrapper class with value null will throw java.lang.NullPointerException when Java unbox them into primitive values. Some programmer makes wrong assumption that, auto boxing will take care of converting null into default values for respective primitive type e.g. 0 for int, false for boolean etc, but that's not true, as seen below.
Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error
but when you run above code snippet you will see Exception in thread "main" java.lang.NullPointerException in your console. This happens a lot while working with HashMap and Integer key values. Code like shown below will break as soon as you run
Read more: http://javarevisited.blogspot.com/2014/12/9-things-about-null-in-java.html#ixzz3UQkx8nqx
Read more: http://javarevisited.blogspot.com/2014/12/9-things-about-null-in-java.html#ixzz3UQlNGGAT
What will happen if the below code is executed ?
public class Test {
public static void main(String args[]) throws InterruptedException {
Map numberAndCount = new HashMap<>();
int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};
for(int i : numbers){
int count = numberAndCount.get(i);
numberAndCount.put(i, count++);
}
}
}
Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25)
This code looks very simple and innocuous. All you are doing is finding how many times a number has appeared in a array, classic technique to find duplicates in Java array. Developer is getting the previous count, increasing it by one and putting it back into Map. He might have thought that auto-boxing will take care of converting Integer to int , as it doing while calling put method, but he forget that when there is no count exist for a number, get() method of HashMap will return null, not zero because default value of Integer is null not 0, and auto boxing will throw null pointer exception while trying to convert it into an int variable.
What will happen if the below code is executed?
public class Testing {
public static void main(String args[])
{
Testing myObject = null;
myObject.iAmStaticMethod();
myObject.iAmNonStaticMethod();
}
private static void iAmStaticMethod(){
System.out.println("TEST 1 OK");
}
private void iAmNonStaticMethod(){
System.out.println("TEST 2 OK");
}
}
you can call static method with reference variables with null values. Since static methods are bonded using static binding, they won't throw NPE.
Output: I am static method, can be called by null reference Exception in thread "main" java.lang.NullPointerException at Testing.main
Why character array is better than String for storing password in Java
Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text
http://javarevisited.blogspot.sg/2012/03/10-object-oriented-design-principles.html
General Web:
HTTP Vs HTTPS
GET Vs POST
What is the difference between URL and URI ?
Authentication: A user provides his ID/Password and the system allows him to login. After getting the response page, he clicks on a link/button and the request is sent to server. How does the server recognize that the request is coming from an authenticated
user?
Authentication Vs Authorization
What is mukti-factor authentication?
XML - what is well formed XML ? Can you write an example?
JSON - what is JSON? why do we need it? Can you write an example?
AJAX
What is REST?
What is the architecture of your application - how the web/application/data layers are organized?
Core Java:
Why the main method is static?
String literal question
When do you need to do a type casting? - Candidate need to explain about autoboxing
How and why will you define a variable in an interface? - All variables in an interface are static and final as interfaces cant be instantiated. So you will declare the variable in an interface if the value is a constant and is known to / required by all classes that
implement the interface,
What is subclassing?
What is the difference between overloading and overriding? Write an example?
What is the use of abstract class? - It mandates a common template + default implementations for all subclasses that extend it.
What is the difference between abstract class and interface?
Can i create an interface withtout a variable / method ? - Marker interface.
What is transient? - The answer will tough on serialization. Ask few questions on serialization.
How serialization works ? - Looks for SerialVersionID.
How do you format a floating point number without rouding errors ? / What is the need for BigDecimal ?
Define a function using Generics and explain how you will call it.
Write a sample code to format a date time object in MM/DD/YYYY HH:mm:ss format.
Does the below class has a parent class? Or What is the parent of all the objects?
Class MyClass {
}
What are the methods supported by Object class?
What is the object lifecylce in Java? - class loading, object creation, usage, marked for removal, garbage collection
In Java, it has seven states in Object lifecycle. They are,
Created
In use
Invisible
Unreachable
Collected
Finalized
De-allocated
What is the difference between throw and throws?
What is the difference between final,finalize,finally ?
Explain how memory is managed by JVM ?
The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some
number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects
describing classes and methods, as well as the classes and methods themselves.
How do you optimize the memory configuration of JVM ?
How will you find menory required for your container?
What is annotation? Write an example for custom annotation.
What is a locale object?
What does Runtime.getRuntime() do ? - Gives an handle to JVM, with which you can execute a Java program in a separate thread, initiate GC programmatically.
Collections:
What is a container class?
Difference between Set and Map?
Can I store heterogeneous objects in ArrayList?
Why do we need Comparator?
What is the difference between HashTable Vs HashMap?- Synchronized vs unsync.
Which collection types need to be considered for what usecase?
Java 8:
What is predicate?
What is Lambda?
What is :: ? - Double colon.
What is Functional Interface? - An interface which has Single Abstract Method can be called as Functional Interface.
OO:
Difference between Data Hiding, Abstraction and Encapsulation
Difference between Aggregation and Composition - which one is better ?
Explain one of the design patterns you have used - ask for the reason on why they have used that specific pattern.
Do you know what is anti-pattern?
Take a mobile manufacturing company. They manufacture many different models with different functionalities based on the price range. Can you write a program with actual class model for this company?
JEE
What is HTTPServlet?
Lifecycle of Servlet - init,service,destroy
What are the methods in a Servlet?
How one servlet talks to another servlet ? - ServletConfig.
What is a Bean? How does it differ from a POJO?
How will you include on jsp file in another jsp file? Write sample code.
What is a web service? How the user is authenticated in a Web Service call?
Why do we need a web service?
What is MVC? Take on JEE framework you are comfortable with and explain the MVC model.
What is a container?
Struts:
What are the classes used in Struts?
Struts Framework consists of following classes:
Action Servlets: used to control the response for each incoming request.
Action Class: used to handle the request.
Action Form: it is java bean, used to referred to forms and associated with action mapping
Action Mapping: used for mapping between object and action.
Action Forward: used to forward the result from controller to destination.
What is DynaActionForm?
DynaActionForm is a special type of actionForm class (sub-class of ActionForm Class) that’s used for dynamically creating form beans. It uses configuration files for form bean creation.
Why ActionServlet is singleton in Struts?
In Struts framework, actionServlet acts as a controller and all the requests made by users are controlled by this controller. ActionServlet is based on singleton design patter as only one object needs to be created for this controller class. Multiple threads are
created later for each user request.
What is the difference between forward and redirect?
In redirect, the control can be directed to different servers or even another domain name.The redirect takes a round trip.When a redirect is issued , it is sent back to the client , and redirected URL information is in the header instructing the browser to move
to the next URL. This will act as a new request and all the request and response data is lost.
In forward , the forwarding is done from server side , the client browser URL do not change.the data is also not lost.It is just like a browser page refresh. Whatever data posted in the first submit is resubmitted again.So use it with caution.
Spring
What does a Spring application look like?
An interface that defines the functions.
The implementation that contains properties, its setter and getter methods, functions etc.,
Spring AOP
The Spring configuration XML file.
Client program that uses the function
What are the different types of IoC (dependency injection)?
Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based dependency injection: Setter-based DI 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.
Which DI would you suggest Constructor-based or setter-based DI?
You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.
Explain Bean lifecycle in Spring framework
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Spring populates all of the properties as specified in the bean definition (DI).
If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
If the bean implements DisposableBean, it will call the destroy() method.
What is bean wiring?
Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them
together.
What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using
<constructor-arg> and <property> elements.
What is Aspect?
The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect
for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).
What are the types of advice?
Spring aspects can work with five kinds of advice mentioned below:
before: Run advice before the a method execution.
after: Run advice after the a method execution regardless of its outcome.
after-returning: Run advice after the a method execution only if method completes successfully.
after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
around: Run advice before and after the advised method is invoked.
What is the difference between join point and point cut?
The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework.
The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns.
What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.
What is Controller in Spring MVC framework?
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very
abstract way, which enables you to create a wide variety of controllers.
@Controller annotation
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.
@RequestMapping annotation
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
What is Spring IoC container? What are the benefits of IOC?
The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together, configuring them, as also managing their complete lifecycle.
IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive
mechanism. IOC containers support eager instantiation and lazy loading of services.
Explain Bean lifecycle in Spring framework?
Following is sequence of a bean lifecycle in Spring:
Instantiate - First the spring container finds the bean's definition from the XML file and instantiates the bean..
Populate properties - Using the dependency injection, spring populates all of the properties as specified in the bean definition..
Set Bean Name - If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
Set Bean factory - If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Initialize beans - If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Post Initialization - If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ready to use - Now the bean is ready to use by the application.
Destroy - If the bean implements DisposableBean , it will call the destroy() method .
What are the design patterns used in Spring framework?
What are the common implementations of the ApplicationContext?
The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.
What is the difference between Bean Factory and ApplicationContext?
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
JDBC
What are the different drivers supportrd by JDBC?
What is connection pool?
What is a prepared statement?
Things you find Difficult to Manage?
How would you Evaluate your Analytical Skills?
Give us an Instance when you Failed in spite of your Best Efforts?
I would like to hear about some Experience from your Work Life so Far ?
In what ways do you think you are Suited for this Job?
How can you Contribute to this Organization?
What is your Way of Handling Conflicts?
Can you tell us about a Challenging Situation at work you have Encountered so Far? How did you Tackle it?
If you had to Live your Life over Again ? What one thing would you Change?
What Qualities do you feel a Successful Manager Should Have?
What is your Long term Objective?
If the Interviewer asked me about a time When I had been in a Leadership Position and there was a difficult member of the team who was causing some Aggravation, and How I handled the situation ?
5. I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
Ans. The existing object will be overwritten and thus it will be lost.
Can a vector contain heterogenous objects?
Ans. Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
7. Can a ArrayList contain heterogenous objects?
Ans. Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList ?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
What is an enumeration ?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
What are the steps in the JDBC connection ?
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\” driver classs for that specific database\” );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\”select * from TABLE NAME\”);
Step 4 : Exceute the query :
stmt.exceuteUpdate();
What is the basic difference between the 2 approaches to exception handling…1> try catch block and 2> specifying the candidate exceptions in the throws clause? When should you use which approach ?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
- What is the performance effect of a large number of import statements which are not used?
Answer: They are ignored if the corresponding class is not used.
- Give a scenario where hotspot will optimize your code?
Answer: The compiler itself will perform compile time optimization like dead code elimination, code inlining, loop unrolment, computable expressions substitution. It has the whole processor power and significant time at its disposition. Thus it can be pretty clever in optimize code using algorithms like graph analysis, branche elimination, register colorization ect.The JIT (hotspot) compiler on the other hand have limited processor power and time at its disposition. It compile the most heavily used byte code portions to native code at runtime in an attempt to speed up program execution. It is not clever at all, it uses a statistic based heuristic and always end up optimizing loops (i.e. in can not optimize anything more subtle that loops). - What will happen if an exception is thrown from the finally block?
Answer: The program will exit if the exception is not catched in the finally block. - How does decorator design pattern works in I/O classes?
Answer: The various classes like BufferedReader , BufferedWriter workk on the underlying stream classes. Thus Buffered* class will provide a Buffer for Reader/Writer classes. - If I give you an assignment to design Shopping cart web application, how will you define the architecture of this application. You are free to choose any framework, tool or server?
Answer: Usually I will choose a MVC framework which will make me use other design patterns like Front Controller, Business Delegate, Service Locater, DAO, DTO, Loose Coupling etc. Struts 2 is very easy to configure and comes with other plugins like Tiles, Velocity and Validator etc. The architecture of Struts becomes the architecture of my application with various actions and corresponding JSP pages in place. - What is a deadlock in Java? How will you detect and get rid of deadlocks?
Answer: Deadlock exists when two threads try to get hold of a object which is already held by another object. - Why is it better to use hibernate than JDBC for database interaction in various Java applications?
Answer: Hibernate provides an OO view of the database by mapping the various classes to the database tables. This helps in thinking in terms of the OO language then in RDBMS terms and hence increases productivity. - How can one call one constructor from another constructor in a class?
Answer: Use the this() method to refer to constructors. - What is the purpose of intern() method in the String class?
Answer: It helps in moving the normal string objects to move to the String literal pool. Using intern() on Strings helps to reduce your memory footprint by pointing duplicate Strings to the same constant instance". - How will you make your web application to use the https protocol?
Answer: This has more to do with the particular server being used than the application itself. Here is how it can be done on tomcat:
http://tomcat.apache.org/tomcat-4.1-doc/ssl-howto.html
How does ConcurrentHashMap works in Java ?
is ConcurrentHashMap is thread-safe?
Can we replace Hashtable to ConcurrentHashMap without external synchronization?
As you see there are multiple question in this category, those are mostly followup and can be answered if you understand ConcurrentHashMap well. you can see this article about Hashtable and ConcurrentHashMap to learn more.
What is CountDownLatch in Java?
What is CyclicBarrier in Java?
What is difference between CountDownLatch and CyclicBarrier in Java?
Concurrency is favorite topic on advanced core java interviews and its expected from experienced and senior Java developers to have good understanding of multi-threading and concurrency API in Java. See these post about CountDownLatch in Javaand Difference between CountDowntLatch and CyclicBarrier in Java.
What is Race condition ? Have you faced any race condition?
What is deadLock in Java? Write code to avoid deadlock in Java
Raced conditions and deadlock are major challenges while writing high performance concurrent Java applications and hands on experience of dealing with synchronization and concurrency issue expected from a senior and experience Java programmer. Refer how to avoid deadlock in Java and What is race condition in Java for more details.
What is PermGen space ?
What is memory leak in Java?
What is OutOfMemoryError in PermGen mens?
What is difference between NoClassDefFoundError and ClassNotFoundException in Java?
Have you analyzed thread dump? How do you analyze thread dump ?
How do you determine the memory required for your application?
Is using session to store data a good practice?
Difference between PATH and CLASSPATH in JavaHere are some of the common difference between PATH vs CLASSPATH in Java :
1)Main difference between PATH and CLASSPATH is that PATH is an environment variable which is used to locate JDK binaries like "java" or "javac" command used to run java program and compile java source file. On the other hand CLASSPATH environment variable is used by System or Application ClassLoader to locate and load compile Java bytecodes stored in .class file.
2) In order to set PATH in Java you need to include JDK_HOME/bin directory in PATH environment variable while in order to set CLASSPATH in Java you need to include all those directory where you have put either your .class file or JAR file which is required by your Java application.
3) Another significant difference between PATH and CLASSPATH is that PATH can not be overridden by any Java settings but CLASSPATH can be overridden by providing command line option -classpath or -cp to both "java" and "javac" commands or by using Class-Path attribute in Manifest file inside JAR archive.
4) PATH environment variable is used by operating system to find any binary or command typed in shell, this is true for both Windows and Linux environment while CLASSPATH is only used by Java ClassLoaders to load class files.
These were some notable difference between PATH vs CLASSPATH in Java and they are worth remembering to debug and troubleshoot Java related issues.
Can we override private method in Java - Example program
No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn't depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature.
Difference between Comparator and Comparable in Java - Interview Question
Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some difference between them, major difference between Comparable and Comparator is that former is used to define natural ordering of object e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object. Main usage of java.lang.Comparable and java.util.Comparatorinterface is for sorting list of objects in Java. For example to sort a list of Employee by there Id, we can use Comparable interface and to provide additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare age of employee, SalaryComparator to compare salary of employees etc. This brings another important difference between Comparator and Comparable interface in Java, you can have only one ordering via Comparable e.g. natural ordering, while you can define multiple Comparator for alternative ordering as discussed above. Coming to Interviews, this question is very common on 2 to 3 years experience Java interviews, and you just can't afford to not prepare this. It's definitely possible to achieve years of experience in Java, without writing your own Comparator or Comparable, especially if you are not doing active development or coding, but even though, you must know basics e.g. equals and hashcode,compareTo and compare. In this article, we will see some notable difference between Comparator vs Comparable in Java from interview perspective.
1) How does get method of HashMap works in Java?
Yes, this is still one of the most popular questions for senior developer, you can expect this on telephonic round, followed by lot's of related questions, see here for answers
2) Which two method HashMap key object should implement? (equals and hashcode)
3) Why should an object used as key should be Immutable? (so that hashcode always return same value)
4) How does ConcurrentHashMap achieves it's scalability? or sometime this interview question is also asked as, difference between ConcurrentHashMap and Hashtable in Java, see here for answers.
5) How do you share an object between threads? or How to pass an object from one thread to another? there are multiple ways to do that e.g. Queues, Exchanger etc, but BlockingQueue using Producer Consumer pattern is the easiest way to pass an object from thread to another.
6) How do find if your program has deadlock? ( By taking thread dump using kill -3, using JConsole orVisualVM), I suggest to prepare this core java interview question in more detail, as Interviewer definitely likes to go with more detail e.g. they will press with questions like, have you really done that in your project or not?
7) How do you avoid deadlock while coding? (By ensuring locks are acquire and released in an ordered manner, seehere for detail answer of this question)
8) What is busy spinning? Why should you use it?
One of the interesting multithreading question to senior Java programmers, Busy spinning is a waiting strategy, in which a thread just wait in a loop, without releasing CPU for going to sleep. This can be used in a particular scenario, where wait time is very minimal, by not releasing CPU or suspending thread, your thread retain all cached data and instruction, which may be lost if further suspended and resumed back in a different core of CPU. This question is quite popular in high frequency low latency programming domain, where programmers are trying for extremely low latency in range of Micro to Milli seconds.
9) What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?
ReadWrite Lock is an implementation of lock stripping, where two separate locks are used for read and write operation. Since read operation doesn't modify state of object, it's safe to allow multiple access of shared object to multiple reader without locking, and by splitting lock into ReadLock and WriteLock, you can easily do that. Java provides an implementation of ReadWriteLock in form of ReentrantReadWritLock, which is worth looking. AlsoConcurrentHashMap doesn't use ReadWriteLock, instead it divides maps into several segments and lock them separately using different locks, which means any given time, only a portion of map is locked, instead of whole map. This question is also very popular on Senior and experienced level Java interviews, expect Interviewer to go into more detail, e.g. asking you to provided an implementation of ReadWriteLock with different policies.
10) How to make an Object Immutable in Java? Why should you make an Object Immutable?
Well, Immutability offers several advantage including thread-safety, ability to cache and result in more readable multithreading code. See here to learn how to make object Immutable. Once again, this question can also go into more detail and depending upon your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.
11) Which design patterns have you used?
Always expect design and patterns related question for Senior developer Core Java Interview. It's best to mention any GOF design pattern rather than Singleton or MVC, which almost every other Java developer use it. Your best bet can be Decorator pattern or may be Dependency Injection Pattern, which is quite popular in Spring Framework. It's also good to mention only design pattern, which you have really used in your project and knows it's tradeoffs. As once you mention a particular design pattern say Factory, Interviewer's next question would be, have you used in your project? So be ready with proper example and why you choose a particular pattern.
12) Do you know about Open Closed Design Principle or Liskov Substitution Principle?
Design patterns are based upon object oriented design principles. I strongly suggest to take a look at my article 10 SOLID and Object Oriented design principle, Java programmer should know, to at least have a basic idea of what are these principles and how they help you to write better object oriented code. If you don't know answer of this question, you can politely say no, as it's not expected from you to know answer of every question, but answering question, which most developer doesn't answer, can make your candidature much stronger.
13) Which design pattern you will use to shield your code from a third party library, which will likely to be replaced in another couple of years?
This is just another example of scenario based design pattern question, you can expect in different formats, some with more detail explanation with context, or some with only intent around. One way to shield your code form third party library is todepend upon interface rather than implementation and than use dependency injection to provide a particular implementation. This kind of questions are also asked quite frequently to experienced and senior Java developers with 5 to 7 years of experience.
14) How do you prevent SQL Injection in Java Code?
This question is more asked to Java EE developers than core Java developers but still a good question to know,PreparedStatement is the way to go. PreparedStatement not only provides better performance but also shield from SQL Injection attack. If you are working more on Java EE or J2EE side, than you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them.
15) Tell me about different reference type available in Java, e.g. WeakReference, SoftReference or PhantomReference? and Why should you use them?
Well, they are different reference types coming from java.lang.ref package and provided to assist Java Garbage Collector in case of low memory issues. If you wrap an object with WeakReference than it will be garbage collected if there is no strong reference and GC is running low on memory. WeakHashMap is a Map implementation, whose keys usesWeakReference, so if only Map contains reference of any object and no other, those object can be garbage collected, if GC needs memory.
Memory Leak in Java Application
Saying that a Java program can have memory leak is little surprising for many programers, because they think that Garbage Collector will reclaim memory, and that's one of the reason, why Java is popular programming language. Bug, GC has it's limitation, it can not reclaim the object, which is undesired but still refrenced by some object in Program. This memory, which should be free but still can not be reclaimed is called Memory leak in Java. If you see java.lang.OutOfMemoryError:Java heap space, even after increasing heap space, than it's good to analyze memory pattern for any possible memory leak. There are tools like Profiler (JProbe, Yourkit or Netbeans Profiler), JConsole, VisualVM, which you can use to see memory usage of Java application to confirm memory leak. There are even tools like Plumber, which can help you to find memory leaks in Java. Though this would be as easy as increasing heap memory to fixjava.lang.OutOfMemoryError: Java heap space.
Difference between Error vs Exception in Java - Interview question
Both Error and Exception are derived from java.lang.Throwable in Java but main difference between Error and Exception is kind of error they represent. java.lang.Error represent errors which are generally can not be handled and usually refer catastrophic failure e.g. running out of System resources, some examples of Error in Java are java.lang.OutOfMemoryError orJava.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand java.lang.Exceptionrepresent errors which can be catch and dealt e.g. IOException which comes while performing I/O operations i.e. reading files and directories.
How to Convert Array to Collection, Set and List in Java with Example
Arrays.asList() returns a List object which can be used in the constructor of a collection object.
String[] operatingSystems = new String[]{"Windows", "Linux", "Android", "iOS", "Solaris"};
// Convert array to Collection in Java
Collection collection = Arrays.asList(operatingSystems);
// Convert String array to Set in Java
Set set = new HashSet(Arrays.asList(operatingSystems));
// Convert String array to List in Java
List list = Arrays.asList(operatingSystems); logger.info("List created from Array in Java : {}", list);
What is difference between Thread vs Process in Java
Thread and Process are two closely related term in multi-threading and main difference between Thread and Process in Java is that Threads are part of process. i.e. one process can spawn multiple Threads. If you run a Java program in UNIX based system e.g. Linux and if that program creates 10 Threads, it still one process and you can find that by using ps -ef | grep identifiercommand which is one of most popular use of grep command in UNIX, Where identifier is unix text which can be used asregular expression to find that Java process. Another major difference between Process and Thread is that, each process has its own separate memory space but Threads from same process same memory space. Some linux command map Java thread withlight weight process or lwp, e.g. if you use prstat command in Solaris, you can get how many light weight process or Thread a particular Java program is using.
SPRING
Difference Between @Component, @Service, @Repository and @Controller
- Major difference between these stereotypes is they are used for different classification.
- In a multitier application, we will have different layers like presentation, service, business, data access etc. When a class is to be annotated for auto-detection by Spring, then we should use the respective stereotype as below.
- @Component – generic and can be used across application.
- @Service – annotate classes at service layer level.
- @Controller – annotate classes at presentation layers level, mainly used inSpring MVC.
- @Repository – annotate classes at persistence layer, which will act as database repository.
- If technically they are going to be same then why do we need to use these at different layers level. Why not use the same at all layers. For example, if we use @Service in all layers, all the beans will get instantiated and no issues. There is a minor difference, for example consider @Repository.
The postprocessor automatically looks for all exception translators (implementations of the PersistenceExceptionTranslator interface) and advises all beans marked with the @Repository annotation so that the discovered translators can intercept and apply the appropriate translation on the thrown exceptions.
Similar to the above, in future Spring may choose to add value for @Service, @Controller and @Repository based on their layering conventions. To that additional feature advantage its better to respect the convention and use them in line with layers. - Other than the above, with respect to scan-auto-detection, dependency injection for BeanDefinition @Component, @Service, @Repository, @Controller are same.
Spring Configuration for Component-scanFor these beans to be instantiated by Spring, we need to have the following configuration in the spring configuration XML. Assuming com.javapapers.spring is a base package containing these classes. Needless to say, these Java classes should be part of the application classpath.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.javapapers.spring"/> </beans>
Disable automatic scan of @Component, @Repository, @Service, @Controller:This automatic scan behavior can be disabled for the default stereotypes by setting the use-default-filters property to false,
<beans> <context:component-scan use-default-filters = "false" base-package="com.javapapers.spring" /> </beans>
Customize Default Spring Scan BehaviorWhen component-scan is enable, by default spring scans for @Component, @Service, @Repository and @Controller stereotypes only. All the classes present in the classpath coming under the base-package annotated with these stereotypes will be auto-detected. We can modify this default Spring behavior using include-filter or exclude-filter attribute of the component-scan attribute. There are five filter types available ‘annotation, assignable, aspectj, regex, custom’ and they can be used as below,
<beans>
<context:component-scan base-package="com.javapapers.spring">
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="assignable" expression="com.javapapers.spring.AnimalService"/> </context:component-scan>
</beans>
How can you give the bean name as part of the class definition ?
Bean NamingFor all @Component, @Service, @Repository and @Controller stereotyped components the bean name is assigned based on BeanNameGenerator strategy. We can also supply our name choice during annotation and that will take high precedence.
@Service("lionKing") public class LionService { // ... } @Repository public class AnimalJpa { // ... }
For LionService the instantiated bean name will be lionKing which we have supplied, but in the case of AnimalJpa the bean name will be animalJpa. This behavior is same for all sterotypes @Component, @Service, @Repository and @Controller.
http://javapapers.com/spring/spring-component-service-repository-controller-difference/
http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
http://www.journaldev.com/2696/spring-interview-questions-and-answers
http://www.journaldev.com/7153/java-101-tutorials-learn-java
http://javarevisited.blogspot.in/2010/10/why-string-is-immutable-in-java.html
Any wrapper class with value null will throw java.lang.NullPointerException when Java unbox them into primitive values. Some programmer makes wrong assumption that, auto boxing will take care of converting null into default values for respective primitive type e.g. 0 for int, false for boolean etc, but that's not true, as seen below.
Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error
but when you run above code snippet you will see Exception in thread "main" java.lang.NullPointerException in your console. This happens a lot while working with HashMap and Integer key values. Code like shown below will break as soon as you run
Read more: http://javarevisited.blogspot.com/2014/12/9-things-about-null-in-java.html#ixzz3UQkx8nqx
Read more: http://javarevisited.blogspot.com/2014/12/9-things-about-null-in-java.html#ixzz3UQlNGGAT
What will happen if the below code is executed ?
public class Test {
public static void main(String args[]) throws InterruptedException {
Map numberAndCount = new HashMap<>();
int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};
for(int i : numbers){
int count = numberAndCount.get(i);
numberAndCount.put(i, count++);
}
}
}
Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25)
This code looks very simple and innocuous. All you are doing is finding how many times a number has appeared in a array, classic technique to find duplicates in Java array. Developer is getting the previous count, increasing it by one and putting it back into Map. He might have thought that auto-boxing will take care of converting Integer to int , as it doing while calling put method, but he forget that when there is no count exist for a number, get() method of HashMap will return null, not zero because default value of Integer is null not 0, and auto boxing will throw null pointer exception while trying to convert it into an int variable.
What will happen if the below code is executed?
public class Testing {
public static void main(String args[])
{
Testing myObject = null;
myObject.iAmStaticMethod();
myObject.iAmNonStaticMethod();
}
private static void iAmStaticMethod(){
System.out.println("TEST 1 OK");
}
private void iAmNonStaticMethod(){
System.out.println("TEST 2 OK");
}
}
you can call static method with reference variables with null values. Since static methods are bonded using static binding, they won't throw NPE.
Output: I am static method, can be called by null reference Exception in thread "main" java.lang.NullPointerException at Testing.main
Why character array is better than String for storing password in Java
Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text
http://javarevisited.blogspot.sg/2012/03/10-object-oriented-design-principles.html
General Web:
HTTP Vs HTTPS
GET Vs POST
What is the difference between URL and URI ?
Authentication: A user provides his ID/Password and the system allows him to login. After getting the response page, he clicks on a link/button and the request is sent to server. How does the server recognize that the request is coming from an authenticated
user?
Authentication Vs Authorization
What is mukti-factor authentication?
XML - what is well formed XML ? Can you write an example?
JSON - what is JSON? why do we need it? Can you write an example?
AJAX
What is REST?
What is the architecture of your application - how the web/application/data layers are organized?
Core Java:
Why the main method is static?
String literal question
When do you need to do a type casting? - Candidate need to explain about autoboxing
How and why will you define a variable in an interface? - All variables in an interface are static and final as interfaces cant be instantiated. So you will declare the variable in an interface if the value is a constant and is known to / required by all classes that
implement the interface,
What is subclassing?
What is the difference between overloading and overriding? Write an example?
What is the use of abstract class? - It mandates a common template + default implementations for all subclasses that extend it.
What is the difference between abstract class and interface?
Can i create an interface withtout a variable / method ? - Marker interface.
What is transient? - The answer will tough on serialization. Ask few questions on serialization.
How serialization works ? - Looks for SerialVersionID.
How do you format a floating point number without rouding errors ? / What is the need for BigDecimal ?
Define a function using Generics and explain how you will call it.
Write a sample code to format a date time object in MM/DD/YYYY HH:mm:ss format.
Does the below class has a parent class? Or What is the parent of all the objects?
Class MyClass {
}
What are the methods supported by Object class?
What is the object lifecylce in Java? - class loading, object creation, usage, marked for removal, garbage collection
In Java, it has seven states in Object lifecycle. They are,
Created
In use
Invisible
Unreachable
Collected
Finalized
De-allocated
What is the difference between throw and throws?
What is the difference between final,finalize,finally ?
Explain how memory is managed by JVM ?
The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some
number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects
describing classes and methods, as well as the classes and methods themselves.
How do you optimize the memory configuration of JVM ?
How will you find menory required for your container?
What is annotation? Write an example for custom annotation.
What is a locale object?
What does Runtime.getRuntime() do ? - Gives an handle to JVM, with which you can execute a Java program in a separate thread, initiate GC programmatically.
Collections:
What is a container class?
Difference between Set and Map?
Can I store heterogeneous objects in ArrayList?
Why do we need Comparator?
What is the difference between HashTable Vs HashMap?- Synchronized vs unsync.
Which collection types need to be considered for what usecase?
Java 8:
What is predicate?
What is Lambda?
What is :: ? - Double colon.
What is Functional Interface? - An interface which has Single Abstract Method can be called as Functional Interface.
OO:
Difference between Data Hiding, Abstraction and Encapsulation
Difference between Aggregation and Composition - which one is better ?
Explain one of the design patterns you have used - ask for the reason on why they have used that specific pattern.
Do you know what is anti-pattern?
Take a mobile manufacturing company. They manufacture many different models with different functionalities based on the price range. Can you write a program with actual class model for this company?
JEE
What is HTTPServlet?
Lifecycle of Servlet - init,service,destroy
What are the methods in a Servlet?
How one servlet talks to another servlet ? - ServletConfig.
What is a Bean? How does it differ from a POJO?
How will you include on jsp file in another jsp file? Write sample code.
What is a web service? How the user is authenticated in a Web Service call?
Why do we need a web service?
What is MVC? Take on JEE framework you are comfortable with and explain the MVC model.
What is a container?
Struts:
What are the classes used in Struts?
Struts Framework consists of following classes:
Action Servlets: used to control the response for each incoming request.
Action Class: used to handle the request.
Action Form: it is java bean, used to referred to forms and associated with action mapping
Action Mapping: used for mapping between object and action.
Action Forward: used to forward the result from controller to destination.
What is DynaActionForm?
DynaActionForm is a special type of actionForm class (sub-class of ActionForm Class) that’s used for dynamically creating form beans. It uses configuration files for form bean creation.
Why ActionServlet is singleton in Struts?
In Struts framework, actionServlet acts as a controller and all the requests made by users are controlled by this controller. ActionServlet is based on singleton design patter as only one object needs to be created for this controller class. Multiple threads are
created later for each user request.
What is the difference between forward and redirect?
In redirect, the control can be directed to different servers or even another domain name.The redirect takes a round trip.When a redirect is issued , it is sent back to the client , and redirected URL information is in the header instructing the browser to move
to the next URL. This will act as a new request and all the request and response data is lost.
In forward , the forwarding is done from server side , the client browser URL do not change.the data is also not lost.It is just like a browser page refresh. Whatever data posted in the first submit is resubmitted again.So use it with caution.
Spring
What does a Spring application look like?
An interface that defines the functions.
The implementation that contains properties, its setter and getter methods, functions etc.,
Spring AOP
The Spring configuration XML file.
Client program that uses the function
What are the different types of IoC (dependency injection)?
Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based dependency injection: Setter-based DI 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.
Which DI would you suggest Constructor-based or setter-based DI?
You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.
Explain Bean lifecycle in Spring framework
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Spring populates all of the properties as specified in the bean definition (DI).
If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
If the bean implements DisposableBean, it will call the destroy() method.
What is bean wiring?
Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them
together.
What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using
<constructor-arg> and <property> elements.
What is Aspect?
The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect
for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).
What are the types of advice?
Spring aspects can work with five kinds of advice mentioned below:
before: Run advice before the a method execution.
after: Run advice after the a method execution regardless of its outcome.
after-returning: Run advice after the a method execution only if method completes successfully.
after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
around: Run advice before and after the advised method is invoked.
What is the difference between join point and point cut?
The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework.
The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns.
What is a Proxy?
A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.
What is Controller in Spring MVC framework?
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very
abstract way, which enables you to create a wide variety of controllers.
@Controller annotation
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.
@RequestMapping annotation
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
What is Spring IoC container? What are the benefits of IOC?
The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together, configuring them, as also managing their complete lifecycle.
IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive
mechanism. IOC containers support eager instantiation and lazy loading of services.
Explain Bean lifecycle in Spring framework?
Following is sequence of a bean lifecycle in Spring:
Instantiate - First the spring container finds the bean's definition from the XML file and instantiates the bean..
Populate properties - Using the dependency injection, spring populates all of the properties as specified in the bean definition..
Set Bean Name - If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
Set Bean factory - If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Initialize beans - If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Post Initialization - If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ready to use - Now the bean is ready to use by the application.
Destroy - If the bean implements DisposableBean , it will call the destroy() method .
What are the design patterns used in Spring framework?
What are the common implementations of the ApplicationContext?
The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.
What is the difference between Bean Factory and ApplicationContext?
Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.
JDBC
What are the different drivers supportrd by JDBC?
What is connection pool?
What is a prepared statement?