My personal note for your next Java interview

Mahjoub Saifeddine
Javarevisited
Published in
8 min readJul 9, 2020

Sharing my personal note to help you prepare your next Java interview.

Introduction

I’m sharing with you my personal note that I’ve used to prepare my interviews. Java interviews are not easy, there are many topics to cover and the number of questions that could be asked is quite large. My approach is simple, it consists of asking myself some questions (frequently asked by interviewers) that cover both basic and advanced concepts.

Disclaimer: Please consider my answers as a memory refresh for the things you already know. If it’s not the case, please search for a dedicated tutorial on a particular topic and try to practice more on your own.

Creating a Java Program

What happens If we set the main method to private?

The code will compile and the main private function will be considered as an ordinary static function. However, the program won’t run because the public main function is missing.

What happens if we execute this command with a java file ?

java HelloWorld.java

java’ is used to run compiled files. In this case, however, it will compile the given java class in memory and run it immediately.

Decisions and loops

What is the difference between the break and continue in a loop ?

A ‘break’ statement results in the termination of the statement to which it applies (switch, for, do, or while).

A ‘continue’ statement is used to end the current loop iteration and return control to the loop statement.

What is the difference between while {..} do and do {..} while ?

While loop is executed zero or multiple times since it starts looping when a given condition is true. Whereas, the do-while loop is executed at least one time since the condition is checked after the loop body is executed.

Working with the Java Core API

What is the result of the following code? Can you explain?

String a = "Hello world";        
String b = "Hello world";
System.out.println(a == b);

The result will be true. For objects, the == operator is used to compare the reference. For this code, however, the first String will be stored in the String Pool. The second String, also, will have the same reference to the object pulled back from the String pool to make both a and b two variables with the same reference.

What is AutoBoxing ?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an ‘int’ to an ‘Integer’, a ‘float’ to a ‘Float’, and so on. If the conversion goes the other way, this is called unboxing.

Float f1 = new Float(6.f); // Boxing
float f2 = (float)f; // Unboxing
Float f3 = 6.f; // AutoBoxing

What is the purpose of AutoBoxing ?

It allows us to switch between primitive and object types easily without casting or wrapping. Also, it allows us to work with generic types because generics, in java, does not support primitive types.

What is the difference between StringBuilder/StringBuffer ?

StringBuffer is thread-safe and synchronized whereas StringBuilder is not. This explains why the StringBuilder is faster than the StringBuffer.

Describe the JAVA stream API ?

The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result and it supports parallel execution.

List<String> greetings =
Arrays.asList("Hello", "Hola", "Bonjour", "Hallo");

greetings
.stream()
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
// BONJOUR
// HALLO
// HELLO
// HOLA

Serialization

What is meant by Serialization ?

Serialization is a mechanism of converting the state of an object into a byte stream.

What is SerialVersionUID ?

SerialVersionUID is used during deserialization to verify that the sender and receiver of a serialized object are compatible.

What is the ‘transient’ keyword?

The ‘transient’ keyword is used to mark the attribute, not serialization.

Understanding Methods and Encapsulation

Can you explain access levels in Java?

What is the purpose of encapsulation?

The main purpose of data encapsulation is to hide implementation details of a class or a method from other classes. Also, it can help us set validation rules for encapsulated attributes using getters and setters.

What is the difference between method overriding and method overloading?

Overriding a method is creating a method with the same signature (name and parameters) in the subclass. The overriding is also called dynamic polymorphism since it happens at run time.

Overloading a method is declaring two or more methods in a class with the same method name but different parameters. The overloading is also called static polymorphism since it happens at compile time.

Class design

What is the difference between static and instance methods ?

Static methods belong to the class. It’s associated with the class as a whole rather than a specific instance. Each object will share a common copy of the static methods. There is only one copy per class, no matter how many objects are created from it. However, instance method is associated with the object. It requires an instance object to be created before it can be used. An Instance method can access both instance and static (fields/methods), whereas a static method can access to static (fields/methods) only.

What happens when a class implements two interfaces having the same default method name ?

Since each interface has its own default implementation, the java compiler will ask to set a new implementation for the method.

Why do we need to implement ‘hashcode’ and ‘equals’ methods ?

Un-overridden ‘hashCode()’ and ‘equals()’ prevent your object from working well in hash based collections. The contract between ‘equals()’ and ‘hashCode()’ is:

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal ‘collusion’.

Generics and Collections

What are generics and why do we use them?

Generics are used to create classes, interfaces, and methods that have placeholders for the types they use. It enables the implementation of generic solutions, which can be reused with multiple types without casting.

Difference between Vector/ArrayList ?

Both Vector and ArrayList are resizable arrays. The main difference is that Vector’s methods are synchronized while ArrayList’s methods are not.

How does HashMap work internally ?

HashMap contains an internal array (16 elements by default) of linked lists called Buckets to store nodes . For each element the hashmap divides the hashcode by the array size and takes the rest as position in the bucket and adds the value to the linked list if it’s not exist.

Handling Exceptions

Explain types of exceptions in JAVA ?

In Java we have 2 types of exceptions:

  1. Checked Exception: Is an exception that must be declared or handled by the application code where it is thrown. It’s a subclass of ‘Exception’.
  2. Unchecked Exception: Is an exception is any exception that does not need to be declared or handled by the application code where it is thrown. It’s a subclass of ‘RuntimeException’.

Concurrency and multithreading

What is the difference between a process and a thread ?

Process
A process, referred as a task, consists of multiple threads. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

Thread
A thread is a subset of a process and shares its address space. The thread can communicate easily with the other threads in the same process using ‘wait()’, ‘notify() ’and ‘notifyAll()’ methods.

Different methods to run a thread in java ?

  • Inherit from ‘Thread’ class and override the ‘run()’
  • Implement ‘Runnable’ interface

What is the ‘synchronized’ keyword ?

It’s used to only allow one thread at a time into a particular section of code thus allowing us to protect, for example, variables or data from being corrupted by simultaneous modifications from different threads.

What is the disadvantage of synchronization ?

The main disadvantage of synchronized keywords is it increases waiting time of thread and affects the performance of the system. If there is no specific requirement it is never recommended to use it.

What is the difference between thread run() and start() ?

if you just invoke ‘run()’ directly, it’s executed on the calling thread, just like any other method call. ‘Thread.start()’ is required to actually create a new thread so that the runnable’s run method is executed in parallel.

Explain thread life cycle ?

  1. New: New is the thread state for a thread which was created but has not yet started.
  2. Runnable: The thread is currently being executed.
  3. Blocked: The thread is waiting for a monitor lock is in this state.
  4. TimedWaiting: The thread is waiting for a specified time.
  5. Waiting: The thread is waiting for unspecified time.
  6. Terminated: After the thread has completed the execution of the ‘run()’ method, it is moved into the terminated state.

Garbage collector

What is the garbage collector ?

Java garbage collection is the process by which Java programs perform automatic memory management. The garbage collection is an automatic process. It implements a generational garbage collection strategy that categorizes objects by age.

What are the different generations in JVM Memory?

There are 3 generations:

  1. Young (Eden, Survivor 1 and Survivor 2) generation: Newly created objects. They are collected in minor collection event.
  2. Old (or Tenured) generation: Survived objects from the young generation. They are collection in major collection event.
  3. Perm Generation (for the old versions of java). Since Java 8, it’s replaced with Metaspace: Objects are cleaned when the Metaspace reaches it maximum size.

What are the Different Types of GC Algorithms?

  • Serial: All garbage collection events are conducted serially in one thread. Compaction is executed after each garbage collection.
  • Parallel: Multiple threads are used for minor garbage collection. A single thread is used for major garbage collection and Old Generation compaction.
  • CMS (Concurrent Mark Sweep): Multiple threads are used for minor garbage collection using the same algorithm as Parallel. Major garbage collection is multi-threaded. (Deprecated in JDK 9)
  • G1 (Garbage First): A replacement for CMS. It is parallel and concurrent like CMS, but it works quite differently under the hood.
  • The Z Garbage Collector (ZGC): ZGC performs all expensive work concurrently, without stopping the execution of application threads. (available from JDK 11)

Conclusion:

In this post, we explored multiple questions frequently asked by interviewers with simple answers. I hope this post will be part of your assets for your preparations for your next Java interview. Good Luck!

References:

https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

https://docs.oracle.com/javase/tutorial/collections/streams/index.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html

https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.State.html

https://docs.oracle.com/en/java/javase/11/gctuning/available-collectors.html

--

--