Since its introduction 23 years ago, in 1995, Java has dominated the world of computing: boasting numerous “Language of the Year” awards and first places in “Most Popular Programming Language” contests, Java has become omnipresent. Many programmers picked this language up to create all kinds of products — and in this large pool of available Java developers, how to make sure that you hire the best one?
Continuing our series with Java Interview Questions, we will provide you with the best Java Interview Questions and Answers to help you become the master of technical interviews!
Java Fundamentals
Java as a technology does not exist in a vacuum: there are certain principles, design philosophies and best practices that allow for a great Java product — and the job candidate should be proficient in them.
1. What is JVM?
JVM — Java Virtual Machine — is a process virtual machine designed to execute Java bytecode. Java’s goal was to be platform-independent, without forcing the programmer to design, write, and test application programs for each platform — this feat is possible thanks to JVM, which acts as a buffer between Java code and given hardware platform, allowing Java code to run practically anywhere.
2. What advantages does Java have?
The (arguably) most popular programming language is bound to have some great features. Some of these are:
- “Write once, run everywhere” approach: designed to run on any platform with the help of JVM, Java code is platform-independent both at the source and binary levels, enabling simple development
- Object-Oriented: although OOP is a controversial topic for some programmers, the advantages it can offer are numerous: most importantly, OOP allows for the creation of modular programs and reusable code — which also simplifies development
- Reliability: as Java compilers perform extensive checks for any possible error, collect garbage and allocate memory in an efficient way, Java code is extremely robust
- Security: Java compilers, interpreters and runtime environment are designed to protect users from malicious programs and JVM boasts a verification mechanism to identify and check the bytecode before running it
3. What drawbacks of Java should we look out for?
Some of Java’s greatest features are related to the language’s problems: trade-offs are sometimes unavoidable. Generally, Java’s drawbacks are considered to include:
- Poor performance: the very mechanism that allows for Java’s cross-platform feature — JVM — leads to a decrease in performance due to additional abstraction level in the form of the virtual machine. Java’s garbage collectors, bad caching configs, thread deadlocks and instances of OutOfMemoryError can all lead to significantly degraded performance, forcing the programmer to be constantly aware of these issues
- Non-native look of desktop applications: solutions that create graphical user interfaces for Java programs are not able to provide the native look and user experience of a desktop program. This leads to design inconsistencies in Java programs
- Code complexity: although not the ultimate deciding factor for a programming language to be considered as either good or bad, Java’s code verbosity does pose a problem: complex code is harder to understand and write which slows the overall development process. In this regard, Java’s competitors like Python have an upper hand
4. What data types are supported by Java?
There are eight primitive data types: byte, short, int, long, float, double, boolean, char
. Additionally, there are two concepts related to these types: autoboxing
and unboxing
. Autoboxing refers to the automatic conversion from primitive types to their corresponding object wrapper classes, e.g. int to Integer or double to Double; unboxing is the reverse process.
5. What are some of the essential tools Java can be enhanced with?
Various software can enhance the way Java applications are built — here are some of them:
- Git as the go-to version control solution
- Maven and Gradle to build and manage Java projects: compile source files, run unit tests, deploy to live environments, manage dependencies
- Eclipse and IntelliJ IDEA as the go-to IDEs
- Docker to assemble apps in a quick and effective manner, managing containers of an app as a single group in order to optimize resources
- Jenkins to utilize continuous integration, used for building, testing and deploying a project in a continuous mode
- Selenium to test web pages via its browser automation feature
- Chef to utilize infrastructure automation: building a server or installing a program
6. What general methods can be used for optimization?
To counter Java’s performance problems, we can use different techniques and tricks to optimize Java projects.
- Avoid premature optimization: ironically, a good way to optimize a Java project is to put restraints on unnecessary optimization. In early stages of development, the developer may be tempted to write their code and optimize it at the same time — however, this leads to more complex code (which can later be scrapped altogether if the team decides to focus on other features instead). Once the project is somewhat mature, we can measure how fast the code runs and what elements should be improved
- Caching: to avoid continuous usage of resources, we can cache certain elements of our project — for instance, we can do this with database connections in a pool to save time when establishing new connections. However, before we utilize caching, we need to calculate whether additional memory associated with caching overhead would be lower than the memory needed for these resources in the first place.
- Java performance tools: solutions like Java Mission Control or VisualVM can help us analyze our project’s performance
- Starting with minimum memory allocation: using the range of 1GB to 7GB as the starting point, we can later increase the allocation if a program requires it
7. What is a deadlock?
Deadlock occurs when two processes are stuck in a loop, waiting for each other to complete — which results in both processes staying in the wait-mode endlessly.
Applied Java Knowledge
Having tested a Java developer’s fundamental knowledge, we move on to more concrete examples and problems. Curiously enough, you are not forced to go for pure coding questions only — there is an abundance of interesting abstract concepts of Java you can discuss with a prospective job candidate.
8. What states can Java threads have?
Java threads can have a number of states which are defined by the Thread.State
enum. If we want to check the current state of a given thread, the Thread.getState()
method can be used to monitor or debug any concurrency issues that our program may be experiencing. The states are:
NEW
: default state for a newly created thread
RUNNABLE
: acquires this state as soon as a thread starts executing
BLOCKED
: should a thread get blocked waiting for a monitor lock, it moves to this state. This happens in two cases: 1) the thread is either waiting to acquire a lock to enter a synchronized block/method or 2) waiting to reacquire the monitor lock of an object on which it invoked the Object.wait method.
WAITING
: acquires this state when invokes one of these methods: 1) Object.wait
without a timeout; 2) Thread.join
without a timeout; 3) LockSupport.park
TIMED_WAITING
: acquires this state when invokes one of these methods: 1) Thread.sleep
; 2) Object.wait
with a timeout; 3) Thread.join
with a timeout; 4) LockSupport.parkNanos
; 5) LockSupport.parkUntil
TERMINATED
: once a thread is terminated, it acquires this state
There is a number of possible state transitions as detailed here:
9. How can a thread be created?
The three options are:
- When a class extends the
Thread
class - When a class implements the
Runnable
interface - When an application utilizes the
Executor
framework to create a thread pool
What is the optimal option? The best practice would be the Runnable
one due to its independence from the Thread
class object inheritance.
10. In what aspects are Arrays and ArrayLists different?
Their main differences are best shown in comparison:
- What they contain:
Array
contains primitive or objects;ArrayList
can only contain objects - Size:
Array
has a fixed size;ArrayList
has a dynamic size - Features:
ArrayList
boasts additional features likeaddAll
,removeAll
,iterator
and so on.
11. Why does this code print 0? How do you make this code print 0.5 instead?
final double d = 1 / 2; System.out.println(d);
Answer: This issue happens because the expression 1 / 2
has integer literals on both sides of the operator: 1 and 2. Then, an integer division is performed, and the result of 1 divided by 2 in an integer division is 0.
To make the result double as expected, at least one operand must be a double. For example:
final double d = 1 / 2.0; or: final double d = 1.0 / 2;
12. How can you swap the values of two numeric variables (x and y) without using any other variables?
You can swap two values a and b without using any other variables as follows:
x = x + y; y = x - y; x = x - y;
13. In this code block, what will be the list’s contents and why?
final List list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.remove(2);
Answer: The contents will be: [ 1, 2 ]
. Since the list contains two concurrent removal operations — remove(int index)
and remove(Object obj)
— JVM prefers the most specific overload of a method. In this instance, we pass int as an argument, forcing the code to remove the element at index 2. In order to discard the _element_ 2
from the list, we can add this code:
list.remove(Integer.valueOf(2));
14. Write a simple Java program to check if a given string is palindrome or not (Palindrome is a string which is equal to the reverse of itself — for example, the reverse of “radar” is also “radar”)
public static boolean istPalindrom(String word){ char[] wordArray = word.toCharArray(); int left = 0; int right = wordArray.length - 1; while (right > left) { if (wordArray[left] != wordArray[right]) { return false; } ++left; —right; } return true; }
15. Write a java program to find intersection of two arrays?
Via the iterative method:
class CommonElements { public static void main(String[] args) { String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"}; String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"}; HashSet set = new HashSet(); for (int i = 0; i < s1.length; i++) { for (int j = 0; j < s2.length; j++) { if(s1[i].equals(s2[j])) { set.add(s1[i]); } } } System.out.println(set); //OUTPUT : [THREE, FOUR, FIVE] } }
Via retainAll()
Method:
class CommonElements { public static void main(String[] args) { Integer[] i1 = {1, 2, 3, 4, 5, 4}; Integer[] i2 = {3, 4, 5, 6, 7, 4}; HashSet set1 = new HashSet<>(Arrays.asList(i1)); HashSet set2 = new HashSet<>(Arrays.asList(i2)); set1.retainAll(set2); System.out.println(set1); //Output : [3, 4, 5] } }
Conclusion
As it turns out, hiring a Java developer is a doable task — you only need to use these Java interview questions to improve your hiring strategy!