133 Core Java Interview Questions Answers From Last 5 Years - The MEGA List
133 Core Java Interview Questions Answers From Last 5 Years - The MEGA List
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
Javarevisited
Blog about Java programming language, FIX Protocol, Tibco RV
Home
core java
spring
hibernate
collections
Search
multithreading
design patterns
interview questions
coding
133 Core Java Interview Questions Answers From Last 5 Years The MEGA List
data structure
OOP
books
About Me
Interview Questions
core java interview question (159)
Time is changing and so is Java interviews. Gone are the days, when knowing the difference
between String and StringBuffer can help you to go through the second round of interview,
questions are becoming more advanced and interviewers are asking more deep questions.
When I started my career, questions like Vector vs Arrayand HashMap vs Hashtable were the
most popular ones and just memorizing them gives you a good chance to do well in
interviews, but not anymore. Nowadays, you will get questions from the areas where not
many Java programmer looks e.g. NIO, patterns, sophisticated unit testing or those which are
hard to master e.g. concurrency, algorithms, data structures and coding.
Since I like to explore interview questions, I have got this huge list of questions with me,
which contains lots and lots of questions from different topics. I have been preparing this
MEGA list from quite some time and now It's ready to share with you guys. It contains
interview questions not only from classic topics like threads, collections, equals and
hashcode, sockets but also from NIO, array, string, java 8 and many more.
SelectLanguage
Poweredby
Translate
Java Tutorials
It has questions for both entry level Java programmers and senior developers with years of
experience. No matter whether you are a Java developer of 1, 2, 3, 4, 5, 6, 8, 9 or even 10
years of experience, you will find something interesting in this list. It contains questions
which are super easy to answer, and also, a question which is tricky enough for even seasoned
Java programmers.
Given the list is long and we have questions from everywhere, it's imperative that answers
must be short, concise and crisp, no fluffing at all. So apart from this paragraph, you will only
hear from me is the questions and answers, no more context, no more feedback and no more
evaluation. For that, I have already written blog posts, where you can find my views on a
particular question, e.g. why I like that question, what makes them challenging and what kind
of answer you should expect from candidates.
This list is a little bit different and I encourage you to share questions and answers in a similar
way so that it should be easy to revise. I hope this list can be a great use for both interviewer
and candidates, the interviewer can, of course, put a little variety on questions to bring
novelty and surprise element, which is important for a good interview. While a candidate, can
expand and test their knowledge about key areas of Java programming language and
platform. In 2015 and in coming years the focus will be more on advanced concurrency
concept, JVM internals, 32bit vs 64bit JVM, unit testing, and clean code. I am sure, once you
read through this MEGA list of Java interview question, you should be able to do well on both
telephonic and face to face programming interviews.
Search
Follow by Email
Emailaddress...
Submit
Followers
Followers(3865)Next
Follow
Blog Archive
2016 ( 144 )
2015 ( 127 )
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
December ( 11 )
November ( 4 )
October ( 11 )
How to send HTTP request from UNIX or Linux?
Use c...
How to replace NULL with Empty String in SQL
Serve...
Code Academy now has a FREE course to Learn
Java f...
How to implement Binary Search tree in Java?
Examp...
133 Core Java Interview Questions Answers From
Las...
FIX Log Viewer Tool to view FIX messages in
Read...
What is Double Brace Initialization in Java? Anti
...
SQL Server JDBC Error: The TCP/IP connection
to th...
1/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
5. Array
6. String
7. GOF Design Patterns
8. SOLID design principles
9. Abstract class and interface
September ( 9 )
July ( 18 )
May ( 5 )
April ( 4 )
August ( 11 )
June ( 16 )
March ( 10 )
February ( 12 )
January ( 16 )
2014 ( 102 )
21. JUnit
22. Programming
2012 ( 214 )
2013 ( 128 )
2011 ( 136 )
2010 ( 30 )
You guys are also lucky that nowadays there are some good books available to prepare for
Java interviews, one of them which I particularly find useful and interesting to read isJava
Programming Interview Exposed by Markham. It will take you to some of the most important
topics for Java and JEE interviews, worth reading even if you are not preparing for Java
interview.
Pages
Privacy Policy
Copyright by Javin Paul 20102016. Powered by
Blogger.
2/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
One example I have seen is having a long field in your class. If you know that a long field is
accessed by more than one thread e.g. a counter, a price filed or anything, you better make
it volatile. Why? because reading to a long variable is not atomic in Java and done in two
steps, If one thread is writing or updating long value, it's possible for another thread to see
half value (fist 32bit). While reading/writing a volatile long or double (64 bit) is atomic.
5) Which one would be easy to write? synchronization code for 10 threads or 2 threads?
In terms of writing code, both will be of same complexity because synchronization code is
independent of a number of threads. Choice of synchronization though depends upon a
number of threads because the number of thread present more contention, so you go for
advanced synchronization technique e.g. lock stripping, which requires more complex code
and expertise.
6) How do you call wait() method? using if block or loop? Why? (answer)
wait() method should always be called in loop because it's possible that until thread gets
CPU to start running again the condition might not hold, so its always better to check
condition in loop before proceeding. Here is the standard idiom of using wait and notify
method in Java:
//Thestandardidiomforusingthewaitmethod
synchronized(obj){
while(conditiondoesnothold)
obj.wait();//(Releaseslock,andreacquiresonwakeup)
...//Performactionappropriatetocondition
}
See Effective Java Item 69 to learn more about why wait method should call in the loop.
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
3/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
False sharing is very hard to detect because the thread may be accessing completely different
global variables that happen to be relatively close together in memory. Like many
concurrency issues, the primary way to avoid false sharing is careful code review and aligning
your data structure with the size of a cache line.
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
4/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
15) What is an immutable object? How do you create an Immutable object in Java?
(answer)
Immutable objects are those whose state cannot be changed once created. Any modification
will result in a new object e.g. String, Integer,and other wrapper class. Please see the
answer for step by step guide to creating Immutable class in Java.
20) Can we cast an int value into byte variable? what will happen if the value of int is
larger than byte?
Yes, we can cast but int is 32 bit long in java while byte is 8 bit long in java so when you cast
an int to byte higher 24 bits are lost and a byte can only hold a value from 128 to 128.
21) There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C)
B; (answer)
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
5/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
25) Can I store a double value in a long variable without casting? (answer)
No, you cannot store a double value into a long variable without casting because the range of
double is more that long and you we need to type cast. It's not dificult to answer this
question but many develoepr get it wrong due to confusion on which one is bigger between
double and long in Java.
26) What will this return 3*0.1 == 0.3? true or false? (answer)
This is one of the really tricky questions. Out of 100, only 5 developers answered this question
and only of them have explained the concept correctly. The short answer is false because
some floating point numbers can not be represented exactly.
27) Which one will take more memory, an int or Integer? (answer)
An Integer object will take more memory an Integer is the an object and it store meta data
overhead about the object and int is primitive type so its takes less space.
6/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
The size of an int variable is constant in Java, it's always 32bit irrespective of platform.
Which means the size of primitive intis same in both 32bit and 64bit Java virtual machine.
32) The difference between Serial and Parallel Garbage Collector? (answer)
Even though both the serial and parallel collectors cause a stoptheworld pause during
Garbage collection.The main difference between them is that a serial collector is a default
copying collector which uses only one GC thread for garbage collection while a parallel
collector uses multiple GC threads for garbage collection.
33) What is the size of an int variable in 32bit and 64bit JVM? (answer)
The size of int is same in both 32bit and 64bit JVM, it's always 32 bits or 4 bytes.
34) A difference between WeakReference and SoftReference in Java? (answer)
Though both WeakReference and SoftReference helps garbage collector and memory
efficient, WeakReference becomes eligible for garbage collection as soon as last strong
reference is lost but SoftReference even thought it can not prevent GC, it can delay it until
JVM absolutely need memory.
35) How do WeakHashMap works? (answer)
WeakHashMap works like a normal HashMap but uses WeakReference for keys, which means if
the key object doesn't have any reference then both key/value mapping will become eligible
for garbage collection.
36) What isXX:+UseCompressedOopsJVM option? Why use it? (answer)
When you go migrate your Java application from 32bit to 64bit JVM, the heap requirement
suddenly increases, almost double, due to increasing size of ordinary object pointer from 32
bit to 64 bit. This also adversely affect how much data you can keep in CPU cache, which is
much smaller than memory. Since main motivation for moving to 64bit JVM is to specify large
heap size, you can save some memory by using compressed OOP. By using
XX:+UseCompressedOops, JVM uses 32bit OOP instead of 64bit OOP.
37) How do you find if JVM is 32bit or 64bit from Java Program? (answer)
You can find that by checking some system properties likesun.arch.data.model or os.arch
38) What is the maximum heap size of 32bit and 64bit JVM? (answer)
Theoretically, the maximum heap memory you can assign to a 32bit JVM is 2^32 which is 4GB
but practically the limit is much smaller. It also varies between operating systems e.g. form
1.5GB in Windows to almost 3GB in Solaris. 64bit JVM allows you to specify larger heap size,
theoretically 2^64 which is quite large but practically you can specify heap space up to
100GBs. There are even JVM e.g. Azul where heap space of 1000 gigs is also possible.
39) What is the difference between JRE, JDK, JVM and JIT? (answer)
JRE stands for Java runtime and it's required to run Java application. JDK stands for Java
development kit and provides tools to develop Java program e.g. Java compiler. It also
contains JRE. The JVM stands for Java virtual machine and it's the process responsible for
running Java application. The JIT stands for Just In Time compilation and helps to boost the
performance of Java application by converting Java byte code into native code when the
crossed certain threshold i.e. mainly hot code is converted into native code.
7/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
memory is used to create heap space, which is used to allocate memory to objects whenever
they are created in the program. Garbage collection is the process inside JVM which reclaims
memory from dead objects for future allocation.
42) How do you find memory usage from Java program? How much percent of the heap is
used?
You can use memory related methods from java.lang.Runtime class to get the free memory,
total memory and maximum heap memory in Java. By using these methods, you can find out
how many percents of the heap is used and how much heap space is remaining.
Runtime.freeMemory() return amount of free memory in bytes,
Runtime.totalMemory() returns total memory in bytes and Runtime.maxMemory()
returns maximum memory in bytes.
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
8/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
47) What is a compile time constant in Java? What is the risk of using it?
public static final variables are also known as a compile time constant, the public is optional
there. They are replaced with actual values at compile time because compiler know their
value upfront and also knows that it cannot be changed during runtime. One of the problem
with this is that if you happened to use a public static final variable from some inhouse or
third party library and their value changed later than your client will still be using old value
even after you deploy a new version of JARs. To avoid that, make sure you compile your
program when you upgrade dependency JAR files.
52) What is a couple of ways that you could sort a collection? (answer)
You can either use the Sorted collection like TreeSet or TreeMap or you can sort using the
ordered collection like a list and using Collections.sort() method.
9/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
58) Write code to remove elements from ArrayList while iterating? (answer)
Key here is to check whether candidate uses ArrayList's remove() or Iterator's remove(). Here
is the sample code which uses right way o remove elements from ArrayList while looping over
and avoids ConcurrentModificationException.
59) Can I write my own container class and use it in the foreach loop?
Yes, you can write your own container class. You need to implement the Iterable interfaceif
you want to loop over advanced for loop in Java, though. If you implement Collection then
you by default get that property.
61) Is it possible for two unequal objects to have the same hashcode?
Yes, two unequal objects can have same hashcode that's why collision happen in a hashmap.
the equal hashcode contract only says that two equal objects must have the same hashcode it
doesn't say anything about the unequal object.
62) Can two equal object have the different hash code?
No, thats not possible according to hash code contract.
64) What is the difference between Comparator and Comparable in Java? (answer)
The Comparable interface is used to define the natural order of object while Comparator is
used to define custom order. Comparable can be always one, but we can have multiple
comparators to define customized order for objects.
65) Why you need to override hashcode, when you override equals in Java? (answer)
Because equals have code contract mandates to override equals and hashcode together
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
10/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
.since many container class like HashMap or HashSet depends on hashcode and equals
contract.
77) Tell me few best practices you apply while using Collections in Java? (answer)
Here are couple of best practices I follow while using Collectionc classes from Java:
a) Always use the right collection e.g. if you need nonsynchronized list then use ArrayList and
not Vector.
b) Prefer concurrent collection over synchronized collection because they are more scalable.
c) Always use interface to a represent and access a collection e.g. use List to store ArrayList,
Map to store HashMap and so on.
d) Use iterator to loop over collection.
e) Always use generics with collection.
78) Can you tell us at least 5 best practice you use while using threads in Java? (answer)
This is similar to the previous question and you can use the answer given there. Particularly
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
11/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
83) How do you format a date in Java? e.g. in the ddMMyyyy format? (answer)
You can either use SimpleDateFormat class or jodatime library to format date in Java.
DateFormat class allows you to format date on many popular formats. Please see the answer
for code samples to format date into different formats e.g. ddMMyyyy or ddMMyyyy.
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
12/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
104) The difference between abstract class and interface in Java? (answer)
There are multiple differences between abstract class and interface in Java, but the most
important one is Java's restriction on allowing a class to extend just one class but allows it to
implement multiple interfaces. An abstract class is good to define default behavior for a
family of class, but the interface is good to define Type which is later used to leverage
Polymorphism. Please check the answer for a more thorough discussion of this question.
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
13/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
105) Which design pattern have you used in your production code? apart from Singleton?
This is something you can answer from your experience. You can generally say about
dependency injection, factory pattern, decorator pattern or observer pattern, whichever you
have used. Though be prepared to answer followup question based upon the pattern you
choose.
109) What is "dependency injection" and "inversion of control"? Why would someone use
it? (answer)
110) What is an abstract class? How is it different from an interface? Why would you use
it? (answer)
One more classic question from Programming Job interviews, it is as old as chuck Norris. An
abstract class is a class which can have state, code and implementation, but an interface is a
contract which is totally abstract. Since I have answered it many times, I am only giving you
the gist here but you should read the article linked to answer to learn this useful concept in
much more detail.
111) Which one is better constructor injection or setter dependency injection? (answer)
Each has their own advantage and disadvantage. Constructor injection guaranteed that class
will be initialized with all its dependency, but setter injection provides flexibility to set an
optional dependency. Setter injection is also more readable if you are using an XML file to
describe dependency. Rule of thumb is to use constructor injection for mandatory
dependency and use setter injection for optional dependency.
112) What is difference between dependency injection and factory design pattern?
(answer)
Though both patterns help to take out object creation part from application logic, use of
dependency injection results in cleaner code than factory pattern. By using dependency
injection, your classes are nothing but POJO which only knows about dependency but doesn't
care how they are acquired. In the case of factory pattern, the class also needs to know about
factory to acquire dependency. hence, DI results in more testable classes than factory
pattern. Please see the answer for a more detailed discussion on this topic.
14/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
existing code.
120) The difference between nested public static class and a top level class in Java?
(answer)
You can have more than one nested public static class inside one class, but you can only have
one toplevel public class in a Java source file and its name must be same as the name of
Java source file.
122) Give me an example of design pattern which is based upon open closed principle?
(answer)
This is one of the practical questions I ask experienced Java programmer. I expect them to
know about OOP design principles as well as patterns. Open closed design principle asserts
that your code should be open for extension but closed for modification. Which means if you
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
15/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
want to add new functionality, you can add it easily using the new code but without touching
already tried and tested code. There are several design patterns which are based upon open
closed design principle e.g. Strategy pattern if you need a new strategy, just implement the
interface and configure, no need to modify core logic. One working example
isCollections.sort()method which is based on Strategy pattern and follows the open
closed principle, you don't modify sort() method to sort a new object, what you do is just
implement Comparator in your own way.
123) Difference between Abstract factory and Prototype design pattern? (answer)
This is the practice question for you, If you are feeling bored just reading and itching to write
something, why not write the answer to this question. I would love to see an example the,
which should answer where you should use the Abstract factory pattern and where is the
Prototype pattern is more suitable.
126) Can you write a regular expression to check if String is a number? (solution)
If you are taking Java interviews then you should ask at least one question on the regular
expression. This clearly differentiates an average programmer with a good programmer. Since
one of the traits of a good developer is to know tools, regex is the best tool for searching
something in the log file, preparing reports etc. Anyway, answer to this question is, a numeric
String can only contain digits i.e. 0 to 9 and+ and sign that too at start of the String, by
using this information you can write following regular expression to check if given String is
number or not
127) The difference between checked and unchecked Exception in Java? (answer)
checked exception is checked by the compiler at compile time. It's mandatory for a method to
either handle the checked exception or declare them in their throws clause. These are the
ones which are a sub class of Exception but doesn't descend from RuntimeException. The
unchecked exception is the descendant of RuntimeException and not checked by the compiler
at compile time. This question is now becoming less popular and you would only find this with
interviews with small companies, both investment banks and startups are moved on from this
question.
16/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
means you can throw both Error and Exception using throw keyword e.g.
thrownewIllegalArgumentException("sizemustbemultipleof2")
On the other hand, throws is used as part of method declaration and signals which kind of
exceptions are thrown by this method so that its caller can handle them. It's mandatory to
declare any unhandled checked exception in throws clause in Java. Like the previous
question, this is another frequently asked Java interview question from errors and exception
topic but too easy to answer.
130) The difference between DOM and SAX parser in Java? (answer)
Another common Java question but from XML parsing topic. It's rather simple to answer and
that's why many interviewers prefers to ask this question on the telephonic round. DOM parser
loads the whole XML into memory to create a tree based DOM model which helps it quickly
locate nodes and make a change in the structure of XML while SAX parser is an event based
parser and doesn't load the whole XML into memory. Due to this reason DOM is faster than SAX
but require more memory and not suitable to parse large XML files.
133) What is the difference between Maven and ANT in Java? (answer)
Another great question to check the all round knowledge of Java developers. It's easy to
answer questions from core Java but when you ask about setting things up, building Java
artifacts, many Java software engineer struggles. Coming back to the answer of this question,
Though both are build tool and used to create Java application build, Maven is much more
than that. It provides standard structure for Java project based upon "convention over
configuration" concept and automatically manage dependencies (JAR files on which your
application is dependent) for Java application. Please see the answer for more differences
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
17/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
That's all guys, lots of Java Interview questions? isn't it? I am sure if you can answer this list
of Java questions you can easily crack any core Java or advanced Java interview. Though I
have not included questions from Java EE or J2EE topics e.g. Servlet, JSP, JSF, JPA, JMS, EJB
or any other Java EE technology or from major web frameworks like Spring MVC, Struts 2.0,
Hibernate or both SOAP and RESTful web services, it's still useful for Java developers
preparing for Java web developer position, because every Java interview starts with questions
from fundamentals and JDK API. If you think, I have missed any popular Java question here
and you think it should be in this list then feel free to suggest me. My goal is to create the
best list of Java Interview Questions with latest and greatest question from recent interviews.
References
The Java Virtual Machine Spefication (see here)
The Java language Specification (Java SE 8) (see here)
Java SE 8 API Specification (see here)
24 comments :
Vijay Tidake said...
Hurrah... That what exactly I was waiting for..Good work Javin..Best Luck and Keep it up.
October 19, 2015 at 8:34 AM
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
18/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
2) Why ThreadLocal was introduced in java , when the motive is to provide each thread its own local copy , can't
normal instance variables do the same by default ?
October 31, 2015 at 10:12 AM
Anonymous said...
Not many questions from NIO or Exception handling and data structures. I would love to ask how a Java developer
will use fundamental data structure e.g. array, linked list, tree, stack and queues, their time and space complexity
and when to use one over other.
December 2, 2015 at 11:43 PM
Anonymous said...
Thank you so much, it's the best list of java interview questions I have ever seen.
December 20, 2015 at 10:42 PM
Anonymous said...
big list, almost cover all topics required for Java interviews. Good Job Javin, keep it up, you are inspiration for
many Java developers.
December 27, 2015 at 9:31 PM
Anonymous said...
massive list, can you also post PDF copy for downloading and offline reading?
January 5, 2016 at 6:44 PM
himanshu saini said...
thanks a ton.
can you also post PDF copy for downloading and offline reading?
January 25, 2016 at 8:00 AM
ashish narote said...
Thank You
February 16, 2016 at 11:11 PM
Anonymous said...
Why should someone remember the syntax and code for formatting date or time zone in an interview? Arent these
kind of questions pointless??
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
19/20
10/22/2016
133CoreJavaInterviewQuestionsAnswersFromLast5YearsTheMEGAList
Post a Comment
Enteryourcomment...
Commentas:
Publish
RajuSai(Google)
Signout
Notifyme
Preview
Newer Post
Home
Older Post
https://javarevisited.blogspot.in/2015/10/133javainterviewquestionsanswersfromlast5years.html
20/20