67%(3)67% found this document useful (3 votes) 2K views18 pagesJava Interview Questions (UPDATE 2019) - CodinGame For Work
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Java Interview Questions
Interview Questions for Java Programmers
When discussing preparation for a java programming interview, the focus is typica
Candidates want to know what types of questions to expect so that they can best
issue remains - what type of java interview questions does an employer ask poten
to best evaluate their skills?
HIRE THE MOST
BPR) a0 smog sic)
PLR cea
Eel UL RSL
,
2
In a software development house, regardless of whether the java programming lar
oriented programming is standard, coming up with programming questions and a
straightforward, Itis easy to employ Google, for example, to search for language s)
the core java interview. However, what happens in cases where (or when) the com
contractor for a simple project? Or, similarly, the existing team is non-technical anc
include their own in-house software group?
Before starting, here is a quick definition of the term Java that should help you if yc
this language:Java is a high-level programming language developed by Sun Microsystems, It
designed for developing programs for set-top boxes and handheld devices, bt
popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programmin
‘example, most Java programs contain classes, which are used to define object
which are assigned to individual classes. Java is also known for being more str
meaning variables and functions must be explicitly defined. This means Java s
produce errors or “exceptions” more easily than other languages, but it also lit
errors that may be caused by undefined variables or unassigned types.
CChristensson, P., Java Definition, techterms.corn
‘The goal of this article is to help prepare the interviewer, whatever their experienc
Determining which candidate among many has presented the top java interview is
same time, it will not be found using purely code-related or tricky interview questic
often about the logic, as opposed to the syntax, and it would be a serious mistake
too heavily for not being entirely familiar with something that can easily be looked
That said, itis important to rernember that the interview is, indeed, for a Java prog
candidate must have knowledge of the Java runtime environment (RE), the Java vir
Java development kit (DK), and more, Commonly used libraries such as java lang, j
mystery, Similarly, while it has fallen out of use, the Swing library should at least rir
to not know the Awt library, which is completely obsolete. Finally, candidates may r
experience, but should still at least be aware of the existence of frameworks and 0
as Spring framework, JavaServer Pages (SP), and Java Database Connectivity (DBC
Java interview questions need to be specific in some regards, yet general in others,
necessary to include specific JDBC interview questions? Not likely. However, a cand
know what a List interface is. Similarly, one may be forgiven for not immediately kr
to Oracle using JDBC, while at the same time should have some experience with bt
making use of threads.
With so many competing goals, how does one find the ideal candidate? The answe
of interview questions that covers the topic from more than one perspective, This
these concerns by providing the java interview question, the correct answer or ans
for asking each question,
Programming Questions and Answers
This article cont
ins 14 interview questions and answers. The first 5 are at the begi
remainder vary in both topic and level of difficulty. A perfect score will not necessa
from answering every question to some level of satisfaction. Rather, the discussior
will give the best indicator as to both capability and experience,Beginner-level Programming Interview Ques
Java Interview Question #1 - Java code provides for class me
public and private access specifiers. What is the difference b
modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables anc
classes within a class hierarchy. This is accomplished using various access specifier
difference between these fundamental components is a very relevant java intervie
Particularly in Java, where classes can only be declared public, or not at all - where
have four different modifiers - this is a tricky subject for beginners,
Correct answers
‘A public access specifier directs that the method be accessible both inside and out
true as long as the class, itself, is declared as public, or the calling class is within th:
class does not specify a modifier then itis assumed to have default (package) acce
for its methods do not override this.
Aprivate access specifier directs that the method be accessible only inside of the c
Bonus
>if the candidate knows that there are also specifiers for protected and package (d
demonstrates a good understanding of this topic.
Very bad
Ifthe candidate is unaware of the difference between public and private then it ind
experience in both Java and other object oriented languages such as C++, Should t
but no mention of the fact that the class modifier overrides the methods, it should
Java Interview Question #2 - Consider the following code thi
a static variable and a public method. How many bites were
apple?ot] public class aspie
3 static int &
@, public voi
ra vest
ry public static void main(string[ | are:
18 7 instantiate sed and green apples fos our example public ©
n ple macintosh = new ADple(
2 hople grannySnith = new Apple()
“4 1 Take a bite out of each of the two apples
6 macintosh. cakesite
16 grannySalth. taKeBs
B 1 Display the contents of each class
19 Systen.ou¥.printin("The Macintosh apple has ” + nacinto:
2 Yystem,cut.printin("The Granny Smith apple has: a
Rationale
Static variables are a feature of java that is used regularly by developers. As is the «
itis important for programmers to understand the scope of these objects in order
effects and other errors.
Not declaring a variable. This helps avoid mistyping a variable name as the mistype
be a new, undeclared variable.
Correct answer
‘The Apple class shares the static variable, bites, among all of its Instances. Therefo
method is called on each of the instances, the common variable is updated. The er
The Macintosh apple has 2 bite(s) out of it.
The Granny Seith apple has 2 bite(s) out of it,
Very Bad
If the candidate answers that each of the two instances has a single bite then it ind
experience with static variables. Although this isa trivial topic that is easily learned
frequently encountered. Being unaware of itis an indicator that the candidate is fa
experience with the language.
Java Interview Question #3 - What is an exception? Briefly di
types of exception used in java code.Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in
reasonable course of action. Errors, on the other hand, typically indicate a more se
handling of exceptions is very common and should be understood, at least at a ba
programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
‘A checked exception is one that is “checked! at compile time, When there is code
“throws” a checked exception, the method is required to acknowledge it. This can t
by handing the exception with a try/catch block, or specifying it using the throws ki
exception is one that is not checked at compile time. It is up to the programmer to
this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchec
under Throwable is checked. If the interviewee raises this point then it demonstrat,
understanding of when each one is used
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of th:
responsible for execution control. This functionality represents a step forward fror
which does not support exception handling. While not absolutely necessary, the be
exceptions are many.
Java Interview Question #4 - What are wrapper classes? Give
and their corresponding primitive. How does each relate to
Rationale
Wrapper classes are fundamental in java programming, In fact, their existence imp
object oriented (bonus to the candidate who points this out). This is the case becat
primitive datatypes that are not, by definition, objects.
Correct answers
‘A wrapper class is one that contains a variable that is a primitive data type, and wr
provide functionality for interacting with it, Essentially, it turns the primitive into ar
example, when 2 method is expecting an object to be passed in. The wrapper class
primitive datatype is not. The candidate should be able to name at least two of the
Primative Wrapper Classboolean Boolean
byte Byte
char Char
double Double
float Float
int Int
long Long
short Short
Very Bad
‘The wrapper classes are defined in java.lang, and required because there many cle
objects, Not having knowledge of these wrapper classes, or why they would be use
inadequacy.
Java Interview Question #5 - Define the following terms that
java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
awn e
Serialization
Rationale
This lst includes terms that are used in java, as well as other languages. Interview
experienced programmers include such definitions because it tests for in-depth kr
to discern between languages with similar, yet non-identical concepts.
Correct answers
1. An abstract class is used as a base class for subclasses that will extend or over
example, consider a “Shape” class. A shape may contain a number of sides, fac
Taken in isolation a “Shape” may be of little use. On the other hand if this abst
a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpt
the class hierarchy.
- Itis not possible to instantiate an abstract class,
- It may contain abstract methods, but it is not required.~ Subclasses of the abstract class must implement all of the abstract methods,
abstract class, It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely
maintaining or debugging an existing code base. In addition, experienced obje
make very efficient use of abstract classes.
2. Garbage collection (carried o1
y the garbage collector) is the process of dete
objects in memory that are no longer used or referenced. in java, garbage coll
can also be requested.
‘The commands System.ge() and Runtime.gc() will “hint” to the garbage collecto
although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows «
Which means that in responsive applications the garbage collection should be
Having no knowledge of the garbage collector is not a make-or-break deal, esp
programmer. It should be noted, however, that when coming from a language
memory is managed manually, the programmer should certainly be aware of t
3. Autoboxing is the automatic wrapping of a primitive type, as discussed in ques
will automatically convert a float into a Float. The opposite of this is unboxing,
is extracted from the wrapper class. This is something that the majority of java
familiar with.
4, Serialization refers to the encoding of objects in memory into a stream of byte
stored or transmitted, The opposite is deserialization, which reconstructs the ¢
stream. There are different approaches to achieve serialization. Two common
the object to XML (eXtensible Markup Language), or JSON JavaScript Object Ne
known file types, each with widespread support. Java also supports serializatio
language. The language includes the Serializable interface, which can be used 1
deserialization. The writeObject() method is used to encode the data, whereas
is used to reconstruct objects.
Java Interview Question #6 - Java defines a String class to re
characters. Answer the following questions:
A constructor initializes an object when itis created. However, constructors haven
Generally, you will use a constructor to give intial values to the instance variables «
to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java autome
constructor that initializes all member variables to zero, However, once you define
the default constructor is no longer used.
Java Interview Question #7 - Could you name some Java fratThis interview question is a basic one: any competent java developer is able to nan
written in Java language.
During the interview, the interviewed candidate must mention at least three Java fi
list:
JSF (Java Server Faces), a Java web framework that makes easier the construction 0
server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to
JavaScript applications in Java
Spring, a Java framework which doesn't impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questio
Java Interview Question #8 - Java defines a String class to re
characters. Answer the following questions:
1. After a string is created, is it possible to modify it? Consider the following
2] public static void main(string{] args) { String name = "Ja
Will this work? If not, what changes would be required in order to output the d
2, The String class has more than one Comparator. Consider the following code:
1] public static void main(Stringl]
{ // This program r
~ What does the "XXX" have to be replaced by in order for the two main string «
the arguments are: “Sun Microsystems" and "Sun microsystems", what will the
be? Is there are way to guarantee that it will report them as identical?
- Ifthe argurnents are instead: “Sun microsystemn” and “Sun microsystems”, wt
execution be?
3. Whatis the Java string constant pool? (Or Java string pool)? Does is reside in st:
Rationale
Using string representations is common in many languages, and Java is no except
understand how strings are created, parsed, printed, and manipulated. As an impc
important interview question for java developers.Correct answers
4. No, this wil fil at compile time because itis not possible to modify a string on
This property is known as immutable. In order to make this work, the string co
would have to be recreated. One approach is to use an intermediate character
toCharArray() method on the “name”, replacing the g' with the uppercase lette
the string before printing it, Abonus to the candidate who points out that the:
exists to replace characters, yet cannot be used because al instances of lower:
replaced,
2. The exact drop-in comparator inthis example is either equals.) or equalsigne
type of both of these methods is a boolean value. Ifthe interviewee answers c:
compareTolgnoreCase(..) then credit should be awarded, although the return
an int, so itis technically not correct. It does, however, still demonstrate knowl
In the first example, the strings are identical under equalslgnoreCase(..), but d
In the second example there is a trailing 's, which makes the strings different r
3. The Java Constant String Pool is an area in the Heap memory (so, not the stack
are stored. This approach is behind the reason for which strings are immutabl
For example:
string x = “cain string”;
string y = “virtual machine;
string 2 = “eain string”;
All three of the above strings are stored in the string pool, but the interesting ¢
x and y point to the same area within the string pool, therefore not requiring d
Knowing this, it should be clear that changing the value of x is not allowed bec:
unintended side effect of changing z.
Java Interview Question #9 - What are the differences betwe
and Heap space?
Rationale
In order to improve efficiency, the )VM organizes memory for applications to run ir
and heap space, each of which is used by different operations. Understanding mer
level can lead to more predictable garbage collection and ultimately, increased effiCorrect answers
Stack memory is used for static memory allocation, such as primitive values inside
Used for the execution of a thread. The stack grows when methods are called, and
return. Ifthe memory allocated for the stack is exceeded then the java.lang.StackC
is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifi
in the heap, while the reference to the object is stored in the stack. The JRE classes
heap at runtime, Accessing data in the heap is slower than doing so in stack meme
the action of the garbage collector in order to free up unused objects. If the memo
Is exceeded then the java.lang, OutofMemoryErrar exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of th:
language. Moreover, the terminology is typical in a general programming culture. ¢
related errors, such as a stack overflow caused by an incorrectly behaving recursiv
easier with this understanding,
Java Interview Question #10 - Two class-related terms used
programming are “subclass” and “nested class”. Explain the
between them. Why choose one over the other? Which one
known as an “inner clas
Rationale
In object oriented design there is often confusion about the placement of classes v
Nested classes are relatively rare compared to sub-classes, yet their use is benefici
knowledge of their existence and how they are used should be considered an asse
Correct answers
A subclass is one that extends another class, and is often a specialization of the ori
the public and protected members of their superclass. Subclasses can be instantia
superclass, and in fact, this is always the case when the superclass is an abstract cl
Anested class is a class within a class, which in some cases is an inner class. The sc
includes all of the members in its outer class, giving it access to these variables anc
body exists entirely within the enclosing class, it cannot be instantiated independe
Using an inner class can enhance the object oriented design by further organizing
limited in that it exists to serve its enclosing class. I the inner class offers functions
wider scale then it would make more sense to have it as a top-level class. inner cla
as callback functions for GUI components.
BonusThere are two types of nested classes. Specifically, there is a static nested class, wr
have access to other members of the enclosing class. These are not often used, wr
about them is a bonus as opposed to ignorance of them earning a penalty. The ott
ested-class, which is the version that is referred to as an inner class. These indeec
members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although u
be seen if maintaining an existing code base, the concept is straightforward. inner
more elegant and easier to maintain, but some designers consider this a matter of
other hand, are a fundamental component in object oriented programming that e
should be aware of. Not being able to easily discuss subclasses within a class hiera
Java Interview Question #11 - Two collection classes that are
programming are the Array and List. How do the methods d
these two container objects, and in what circumstances wou
‘one over the other?
Rationale
‘The usage of containers is common in Java and other programming languages. Th
structure, while the Array is static, Itis important to recognize that each is better st
applications, and as such, the candidate should be familiar with them. Having in-de
available datatypes and container classes will ultimately safe on development time
Correct answers
Array
1. Arrays are static in size, so they cannot grow or shrink in terms of the number
that there are methods to access and modify elements, but not to insert or del
2. Java provides methods for performing a binary search or a sort on an array. Al
initialized using the fill) method, or compared using the equals() comparator.
The size of an array is set when itis created
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
ana
All of the elements are of the same type, for example:
Both of these Arrays contain five integers,Vector
Candidates should know when itis appropriate and possible to use these keyword
should know that async can only be placed before the function keyword on a funct
marks the function as returning a Promise, The await keyword can only be used in
asynchronous function and must be placed before a call toa function that will retu
1. Elernents in a List can be added or deleted, meaning the size of the list can cha
for many types of manipulations, including inserting into or removing frorn as
be manipulated as well,
2. The Listis an interface, so when one manipulates a List, a real class, usually Ar
the scene
List relies on the methods from Collections for sorting, such as Collections.s¢
4, The search methods containst), indexOf0, and lastindexOf0) are examples that
the elements. However, to perform a binary search requires calling the more g
Collections.binarySearch(...)
5. Lists can store objects of mixed type, for example:
add(3) .
mist .ada(a4as);
intervienList add("PL
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to m
Aso, the candidate should be credited for knowing that Lists are a replacement for
longer commonly used in Java, The reason has to do with concurrency and the syn
operations. Clearly, a more detailed explanation is beyond the scope of this questi
mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections,
programming and application development. A candidate who is nat comfortable w
almost certainly lacking experience with the language.
Java Interview Question #12 - Unlike C++, Java does not sup
inheritance. How will programming with an Interface provid
this problem? Is an interface part of the class hierarchy?
RationaleWhile there are commonalities between languages for which many programmers \
also distinctions that help to define ther. In a java interview, there will be core jav.
evaluate how well the candidate knows the specifics of the java programming lang
the Diamond Problem in C+, its worthwhile to test the candidate's knowledge fre
Correct answers
‘An interface is similar to a class in that it can contain different types of methods, bi
does not hold the state. Interfaces are inherently abstract, and their methods neec
class. The interface is not instantiated - itis implemented. Unlike in C=+, a class cal
parent (ie. it can only have one superclass). An interface, on the other hand, is cap
than one parent interface, For example:
1] public interface checkersoard
2 Public void setsize(int rovCount, int coluencoun
3
4] puotic interface a
5] public void setiusbero!Piayer
6] public void piay’
7
8] public interface chesscane extends Checkersoard, Ga
In this example, the ChessGame interface inherits from both CheckerBoard and Gi
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a la.
design experience. This is not essential for all applications, although it is important
inherently 00.
Java Interview Question #13 - What is the Java Virtual Machi
main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual
key component of java, and java programmers learn about it at an early stage. Wh
running bytecode generated by other languages, such as JRuby and Jython, it does
fact that itis essential to java itself,
Correct answers
‘The JVM isa virtual machine that allows the computer to run Java programs that hi
bytecode. The bytecode is platform independent, and will run on any computer thi
a just-in-time (IT) compiler than converts the bytecode into machine language inst
applications to run as quickly as a native executable,
Very BadThe JVM is one of the main components that make Java what itis. Having no knowl
indicates a lack of experience with the language.
Java Interview Question #14 - What are final methods and c
abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmer:
phase, there is normally a decision made with respect to whether classes should b
are marked final in order to limit potential side effects from sub-classes that were
important feature that should be utilized for more robust and maintainable code.
Correct answers
‘Amethod that is declared with the final keyword cannot be overridden in the subc
hierarchies where the implementation of the method should be consistent throug!
declaration for a class disallows sub-classing entirely. Yes, itis possible to include f
abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of c
suggests relative inexperience with the language. Even for inexperienced program,
involved with object oriented design, the concept of a fina! class should be familiar
Java Interview Question #15 - Java programming allows for «
create a thread. What are they and which is the preferred m
Rationale
Unlike C++, java contains builtin support for multithreading. This is a rich and pow
relevant and useful in many applications. As such, the candidate should be familia,
Correct answers
What happens in the case that reduce is called on an empty array without providin
accumulator value?
1] public class Javainte-vieuClass implements Runnable (
2 public void run() {
3 Systen.out.printin(
a
5
‘owy exemple public class prints this Line fronTo execute the run() method, pass an instance of the class into a Thread, as follow:
= new Thread(new Javalnterviewclass ())
‘The second way to create a thread is to extend the Thread class. The subclass will «
method, After this, simply create an instance of the class.
public class JavatnterviewClass extends Thread (
public void run() {
sten.out-printin("My example public class extends the Theead €l
To execute the thread, simple instantiate the class and call start), as follows:
1] davaintervienClass myinterview = new JavainterviewClass (); m
Bonus
While implementing the runnable interface and extending the Thread class are tw
a thread, its also possible using the Executor framework. This allows for working \
is less well-known. It includes methods such as newSingleThreadExecutor(), newFi.
submit() to create a run tasks. Knowledge of how to use the Executor framework ir
is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on
significant feature of the language. Itis important because understanding multithr
looking up the syntax for a few commands. Rather, itis an approach that should br
application is being designed and developed.
Java Interview Question #16 - Java code has built-in support
in its Thread class. Concurrency has its own set of problems
and race conditions. Briefly describe Atomic variables in Javé
are used. Next, it is given that the start() method is used to c
call stack before the run() method is used to execute a threa
yield(), sleep(), and join() methods do?Rationale
Java's support for multithreading can lead to concurrency-related problems. The ci
with respect to these issues should be evaluated and considered.
Correct answers
1. An Atomic variable is one that is “atomically updated’, meaning that data integ,
the use of non-blocking algorithms. This functionality is typically implemented
level. Java supports several atomic variables, most commonly AtomicBoolean,
‘AtomicLong, and AtomicReference. There are also several methods that suppe
modification of these variables, including get0, set(), lazySet), compareAndSet(
weakCompareAndSet(). Used properly, atomic variables can be used to implen.
(multithreading safe) methods that effectively deat with certain concurrency-re
2. yieldQ: This method informs the environment that the current thread is not coi
priority, and is prepared to pause execution, Provided that the underlying envi
emptive scheduling, it will suspend the thread if there is another one that neec
second thread, or once the second thread terminates, the current thread will r
continue executing.
3. sleep(): This method will cause the current thread to sleep, or pause execution
of milliseconds. Alternatively, a specified number of milliseconds and nanosect
the current thread is sleeping, another thread will run, or otherwise the CPU
the accuracy of the system clock and timers, the thread will regain control onc:
expired.
4, join: This method is used to join two the execution of two threads together. T
Join on Thread 8, then A will begin waiting, Once 8 has completed, or a pre-sf
expired, A will regain control and continue executing,
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems 1
can lead to serious errors. The majority of devices from desktops to mobile device:
computers now generally support multithreading and concurrency. Its important
proper use of threads, and be aware of the methods provided by java in support o
Conclusion
The questions in this article are useful for evaluating the competency of a prospect
On the topic of interview questions to prepare for a java developer, itis important
specifics of the language can be easily referenced using online help and document
of a language are not nearly as important as how one applies logic. That said, cand
position are expected to know the language and not be in need of extensive trainir
begins. The skills required will be dictated by the job that needs to be done, and th
given above will assist in making this assessment. Dont forget that one of the best
candidate's skills for your project is to perform a hands-on programming assessm«
efficient than oral interview questions to hire a highly-qualified Java programmer.Read more : C++ Int
rview questions | Python Interview questions | Javascript Interview questions
START YOUR FREE TRIAL NOW
‘CONTACT OUR ENTERPRISE TEAM
Products
> Source
> Screen
> Retain
> Pricing
> Help center
Legal
> Terms of Service> Customer Agreement
> Privacy Policy
> Cookies Policy
Resources
> Blog
> Resources:
> eBooks, guides & more
> Research studies
> Client stores
About
> About
> Conactus
Languages
Get in touch
43395439 85 49
Follow us
f vine @
Made with love in Montpellier © 2019 CodinGame Inc. All Rights Reset