Java Interview Questions

20 Java Pros and Dev Leaders Share Their Favorite Java Interview Questions (and How You Should Prepare to Answer Them)

Angela Stringfellow Developer Career Development Leave a Comment

Java remains a popular programming language, and it’s still the most sought-after programming language among employers. That means if you’re looking for a programming job, prospective employers will likely be asking questions designed to gauge your knowledge of this long-established programming language. (If you’re interviewing for new developer positions, you should probably brush up on your DevOps interview questions, too.)

No worries, no SPAM. Opt-out anytime.

Because our goal at Stackify is to help you be a better developer (and land that dream job), we reached out to a panel of development leaders and Java pros and searched the web to find out what Java interview questions you should be prepared for before your next interview. We asked our panel:

“What’s your favorite Java interview question (and how should developers prepare to answer it)?”

Find out what questions to expect and how to prepare for your next DevOps interview by reading what our experts had to say below. Then, download our Comprehensive Java Developer’s Guide to get up to speed on all the tools, websites and blogs, YouTube channels, and more you can turn to to build your skillset.

Meet Our Panel of Development Leaders and Java Experts:

Find out what questions you should be prepared for in your next Java interview and how to answer them by reading what our experts had to say below.

Karolyn HartKarolyn Hart

@karolynhart

Karolyn Hart is the Chief Operating Officer for InspireHUB Inc.

“Are people still asking questions in interviews?…”

We’ve done away with interviews and have moved to auditions. We look at qualifications but our first meeting with a candidate is solely to see the inter-personal dynamic the person has with our team. We look to see if this is someone we’d enjoy spending time with during long hours. If the candidate makes it through this we offer them an audition. A small paid project they can do in their off hours that allows them to engage with our team. We’ve passed on candidates we felt confident would be successful and we’ve found team mates who gave star performances during their audition. There is no interview question that can replace a real-world experience and seeing someone actually perform the work you are hiring them to do.


Mike FeldmanMike Feldman

@caredash

As Chief Technical Officer of CareDash, Mike Feldman drives the company’s overall technology strategy as well as the development and enhancement of its digital platform. Additionally, he ensures CareDash’s leadership position in the fundamental areas of data & analytics, user experience, and software system architecture and design. Mike has always been drawn to finding new uses for technology that help and assist all people.

“A nice Java interview question that I like to ask is…”

How to implement a HashTable using only basic Java constructs. In my Java programming days this was a consistent question that I got asked in interviews. I have found that it’s a good question to ask that tests Java fundamentals, data structure understanding, logic and algorithm skills. Candidates should review and prepare the following to answer this question:

  • HashTables, how they work, bucket sizes, how to avoid collisions (in an interview, as long as they talk about collisions that is acceptable, not necessarily implement the complicated logic)
  • Java basics of bit shifting, indexing, prime number generation and seed values

Hernán FacalHernán Facal

@NearshoreTalent

Hernán Facal is the Nearshore Systems Lead Recruiter. Hernán Facal has a 10+ years of recruiting experience in the U.S., EMEA and Latin America. His work is focused on technical recruitment, with an expertise in hard-to-find talent.

“To identify the accurate Java developer is a tough job…”

But it can be done by asking a question that will allow you to asses performance, abilities, interests and character of the potential hire. Well, to be exact, a two part question:

A. Which is your most significant accomplishment?

In order to understand their work patterns, detect predictable performance and recognize their abilities.

B. Which personal skills proved to be most valuable to make it happen?

This will help you get a full sense of the developer’s character, his/her goals and the value they will provide to the company.


Kevin HayenKevin Hayen

@kphayen

Kevin Hayen is the CTO at Let’s Be Chefs.

“One of my favorite Java questions is a twist on a classic inheritance question…”

It can be a 2- or 3-parter:

a. Does Java support multiple inheritance?

No, you can only extend a single class but you can implement multiple interfaces.

b. How does this prevent the diamond problem that multiple inheritance presents in C++?

Since an interface can’t have implementations for methods, it is only possible to inherit an implementation from the single parent class.

c. Why is this no longer true?

As of Java 8, interfaces can now have default methods which means a class can inherit a method implementation from either it’s parent class or any of it’s interfaces. There should be no clashes between the implementation in the parent class an interface because the parent class takes precedence. However, if two interfaces implement the same default method, there will be a compile time error.

The exact questions I ask to get all of those details can vary and I would expect most senior developers to give me most of if not all of that information with one or two questions. However, I am still surprised that, 3 years after release, many Java developers are still not familiar with basic Java 8 changes such as default methods.


Brian GillBrian Gill

@gwdatarecovery

Brian Gill is CEO of Gillware Inc. He holds a computer science degree from the University of Wisconsin.

“Write me a hashmap implementation from scratch…”

Every developer knows what a hashmap is and how to utilize it, so I don’t have to spend a lot of time explaining the goal. But there’s a lot of thought that goes into hashing algorithms for the keys, when its appropriate to expand the amounts of buckets and re-juggle, and it’s a good opportunity to discuss Big O notation. Many developers have probably not spent a lot of time thinking about a good default load factor for such a collection and that’s a good opportunity to see how they think on their feet. The simplicity of the question and their innate familiarity with the problem space gives me a really good glimpse into their level of experience and understanding. The best way to prepare for such a question would be to break out the source for HashMap!


Matt FergusonMatt Ferguson

@zeeto_io

Matt Ferguson is the CTO at Zeeto. Matt Ferguson has over 23 years of progressive experience in the architecture, development, and management of software products and services. Mr. Ferguson has led engineering and product management teams individually and combined to bring quality and effective customer-driven solutions to market. Prior to joining Zeeto, he was Sr. Director at Sensus.

“When interviewing potential developers…”

I prefer open ended questions and exercises vs testing specific skills that merely exercise memorization. I really want to see that the candidate can communicate deep understanding, communicate it in a story and engage me in problem solving session. Hence instead of the rote language specific question about variables, arrays, interfaces, packages, serialization etc. I prefer to see the developer use the language in a series of simple exercise that should last no more that 2 to 5 minutes each.

For example, here is one that can be adapted to any language and quickly see if the candidate can put their skills to use:  Create a class “myStrings”  with a constructor that takes a string like “ Hello World “ and has a method where I can request this string reversed. Now add a method reversing the words only.  Extend the class “myStrings” preserving all existing functionality but adding a constructor where a 2nd parameter N of type int is required that enables a new method to stream out to the consoled the reversed string N number of times.

Such simple interactive practical questions lets you inspect technical knowledge while insuring the communication skills are there to discuss interpretation of requirements. It is pretty straight forward to create simple exercises like this around a languages common nuances to insure technical competency. But instead of getting a text book question /answer there is now an opportunity to ask follow-up questions based on the common ground the exercise.


Phil SwitzerPhil Switzer

@mi_marketing

Phil Switzer is the CEO of Modern Influence.

“Our favorite question for an interview is…”

To develop a function that determines whether the input value is a power of three. Most answer the question as a multiple instead of a power, so they are excluded early on. We are looking for creative answers to determine if the individual understands the language and can also apply mathematical computations for faster throughput. The basic answer is easy – recursive function that determines if the underlying value is a three or not. A much more fun implementation is to use log functions to provide a very clean and mathematical answer that has a big O of 1. Our second favorite question that is not language dependent is to describe yourself using binary and decimal. We give the user a lookup chart to see if they can do basic binary compilation. See below for the question details.

Describe yourself in Hexadecimal using the following key

Binary Keys for Person Configuration
Bit 0 – Male – 0 / Female – 1
Bit 1 – Short – 0 / Tall – 1
Bit 2 – English – 0 / Other – 1
Bit 3 – Glasses – 0 / No Glasses – 1
Bit 4 – Hair Color Bit 1
Bit 5 – Hair Color Bit 2
Bit 6 – Hair Color Bit 3

Hair Color Decimal Values
0 – bald
1 – red
2 – black
3 – brown
4 – blonde
5 – blue
6- purple
7 – pink


Neel SomaniNeel Somani

@NeelJSomani

Neel Somani is a student at the University of California, Berkeley, studying computer science and business administration. He is currently interning at Google.

“My favorite Java interview question is a simple one, but…”

== compares the memory addresses of the two Strings (or objects in general). To test for equality, you’d have to use the String.equals() function. The difference is between identity and equality. The confusion comes because == can also be used to compare primitives. To prepare for a question like this, you should have good fundamentals regarding pointers (or references in Java) and OOP.


JavaTpoint JavaTpoint

@pagejavatpoint

JavaTpoint (SSS IT Pvt Ltd) provides website development services in affordable cost. We develop websites on WordPress, Core PHP, CakePHP, CodeIgnitor, Open Cart, Servlet-JSP, Struts 2 and Spring technologies.

NOTE: The following information is excerpted from 201 Core Java Interview Questions via Java T Point. 

“One common Java interview question is…”

What is difference between JDK,JRE and JVM?

JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. It is a specification.

JVMs are available for many hardware and software platforms (so JVM is platform dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.


Java HungryJava Hungry

Java Hungry provides Java developer tutorials and coding.

NOTE: The following information is excerpted from Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers via Java Hungry. 

“One frequently-asked Java interview question is…”

What is immutable object? Can you write immutable object?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.


Pankaj KumarPankaj Kumar

@JournalDev

NOTE: The following information is excerpted from 40 Java Collections Interview Questions and Answers via Journal Dev. 

“One question you may be asked related to Java Collections is…”

What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.

This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.


Java Code GeeksSotirios-Efstathios (Stathis) Maneas

@javacodegeeks

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

NOTE: The following information is excerpted from 115 Java Interview Questions and Answers – The ULTIMATE List via Java Code Geeks.

“One important Java interview question relates to exceptions…”

What are the two types of Exceptions in Java? Which are the differences between them?

Java has two types of exceptions: checked exceptions and unchecked exceptions. Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause, if they can be thrown by the execution of the method or the constructor, and propagate outside the method or constructor boundary. On the other hand, checked exceptions must be declared in a method or a constructor’s throws clause. See here for tips on Java exception handling.


Vidhi RungtaVidhi Rungta

@guru99com

Vidhi Rungta is a Computer Engineer and has worked in an IT MNC. Then she got married and became a lecturer. The dearth of quality Interview Q & A websites has always baffled her and she had to struggle a lot to gather challenging interview questions and answers from an assortment of websites and then actually clear the interview. CareerGuru99 is an effort to save you valuable time searching for quality interview Q & A.

NOTE: The following information is excerpted from Top 100 Java Interview Questions with Answers via CareerGuru99. 

“One Java interview question is…”

What is data encapsulation and what’s its significance?

Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.


ToptalToptal

@toptal

Toptal was created by engineers. They are entrepreneurs, all passionate about growing their exclusive network of the top freelance software developers, designers, and finance experts in the world.

NOTE: The following information is excerpted from 20 Essential Java Interview Questions via Toptal. 

“One question you may be asked in a Java interview is…”

Describe and compare fail-fast and fail-safe iterators. Give examples.

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.


IntelliPaatIntelliPaat

@intellipaat

IntelliPaat offers online training courses on Java and other programming languages.

NOTE: The following information is excerpted from Top Java Interview Questions And Answers via IntelliPaat. 

“One of the most basic Java interview questions is…”

What do you understand by Java?

Java is an object-oriented computer language. It is a high-level programming language developed by James Gosling in Sun Microsystem in 1995. Java is a fast, secure and reliable language used for many games, devices, and applications. Go through this Java Tutorial to get a better understanding of the concept.


Java67 Java67

Java67 offers Java programming tutorials and interview questions.

NOTE: The following information is excerpted from Top 10 Tricky Java interview questions and Answers via Java67.

“One question you may be asked in a Java interview is…”

What does the following Java program print?

public class Test { public static void main(String[] args) { System.out.println(Math.min(Double.MIN_VALUE, 0.0d)); } }

This question is tricky because unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0. I have asked this question to Java developer having experience up to 3 to 5 years and surprisingly almost 70% candidate got it wrong.


Interview CakeInterview Cake

@InterviewCake

Interview Cake is focused on being the fastest, easiest way to become the kind of candidate companies fight over.

NOTE: The following information is excerpted from Java Interview Questions via Interview Cake. 

“One technical Java interview question is…”

In Java, how do I decide whether to use a string literal or a string object?

To hard-code a string in Java, we have two options. A string literal:

String username = "CakeLover89";

And a string object:

String username = new String("CakeLover89");

What’s different about these two options?

When you use a string literal, the string is interned. That means it’s stored in the “string pool” or “string intern pool”. In the string pool, each string is stored no more than once. So if you have two separate variables holding the same string literals in a Java program:

String awayMessage = "I am the cake king.";
String emailSignature = "I am the cake king.";

Those two Strings don’t just contain the same objects in the same order, they are in fact both pointers to the same single canonical string in the string pool. This means they will pass an ‘==’ check.

String awayMessage = "I am the cake king.";
String emailSignature = "I am the cake king.";

awayMessage == emailSignature; // True -- same object!
awayMessage.equals(emailSignature) // True -- same contents

If our Strings were instantiated as objects, however, they would not be “interned,” so they would remain separate objects (stored outside of the string pool).

String awayMessage = new String("I am the cake king.");
String emailSignature = new String("I am the cake king.");

awayMessage == emailSignature; // False -- different objects!
awayMessage.equals(emailSignature) // True -- same contents

In some languages, like Lisp and Ruby, interned strings are called “symbols.”

Can you intern a string “by hand?” Absolutely:

String awayMessage = new String("I am the cake king.");
String emailSignature = new String("I am the cake king.");

// intern those strings!
awayMessage = awayMessage.intern();
emailSignature = emailSignature.intern();

awayMessage == emailSignature; // True -- same object!
awayMessage.equals(emailSignature) // True -- same contents

Given this, String literals can be thought of as syntactic sugar for instantiating a String and immediately interning it.

So which should you use, string literals or String objects?

You should almost always use String literals. Here’s why:

It saves time. Comparing equality of interned strings is a constant-time operation, whereas comparing with .equals() is O(n) time.

It saves space. You can have several variables referencing one string while only storing that set of characters in one canonical place (the string pool).

Use String objects only if you want to be able to have two separate string objects with the same contents.


Edureka!Edureka!

@edurekaIN

Edureka! is an online learning ecosystem for continuing education, in partnership with corporates and academia.

NOTE: The following information is excerpted from Top 75 Java Interview Questions You Must Prepare For In 2017 via Edureka!

“In a Java interview, you may be asked to…”

Explain public static void main(String args[]).

public : Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class.

void : It is the return type of the method. Void defines the method which will not return any value.

main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.

String args[] : It is the parameter passed to the main method.


Vimal BeraVimal Bera

@vimalbera92

Vimal Bera is a Full Stack developer born & raised in India, and currently working at Oracle.

NOTE: The following information is excerpted from What are the common questions asked to a one-year-experienced person in an interview for Java? via Quora. 

“I will brief you out about the interview for 1-2 year experienced. I have been in few interviews with my colleague. And this is how we start…”

First, we ask for a basic introduction and your past experience with Java and the projects on which candidate works. Also, we went to ask about how many frameworks are involved and on which he/she has worked. This is basically to evaluate the domain on which candidate worked and how much he/she is involved in it. Also, it helps him/her to become comfortable in the interview, as the interview is about judging the level of a person, and more comfortable he/she becomes, more transparently you can judge.

Then we slowly migrate to basic OOPS concept but we go in depth once few basic question goes well. Following are the basic question we ask in any interview. (We do have few questions stored in our database :P)

What is the meaning of object oriented programming? And the basic understanding of encapsulation, inheritance, polymorphism and abstraction and practical usage of everyone. Note that many couldn’t answer properly on this concept. So it will be good if you go thoroughly through it.

Then we move on to little bit complex about data structure and collections framework, its difference and usages. And for a particular scenario, we asked him/her to design the data structure and which collection he/she will use. This is to measure how he thinks about the problem. Here we don’t need a correct answer but we keen to measure his analytical strength.

After that, if the candidate has experienced in certain Java frameworks, then we ask about it and why he uses it. A few frameworks are Hibernate, Spring, Struts, EJB etc. and we will ask a basic question related to it. Like how can we configure it in our web application, what’s the benefit of it over conventional approach. And few more common question on it.

Last we ask “Do you have any question for us?” if he/she has one, we try to answer it else “Our HR department will get back to you. Thank You :)”


Buggy BreadBuggy Bread

@buggy_bread

Buggy Bread provides a comprehensive, searchable database of interview questions and answers, diagrams, tutorials, practice tests, and more.

NOTE: The following information is excerpted from Search Java Interview Questions via Buggy Bread. 

“Here’s an advanced technical question you should be prepared to answer…”

Why is String immutable in Java ?

1. String Pool – When a string is created and if it exists in the pool, the reference of the existing string will be returned instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

Example –

String str1 = "String1";
String str2 = "String1"; // It doesn't create a new String and rather reuses the string literal from pool

// Now both str1 and str2 pointing to same string object in pool, changing str1 will change it for str2 too

2. To Cache its Hashcode – If string is not immutable, One can change its hashcode and hence it’s not fit to be cached.

3. Security – String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.