Top 40 Java Interview Questions

Object-Oriented Programming (OOP)

Java is a support for concurrent, class-based and object-oriented computer programming languages. The following lists the advantages of object-oriented software development:
  • Code development is modular, easier to maintain and modify.
  • Code multiplexing.
  • Enhance the reliability and flexibility of the code.
  • Increase the comprehensibility of the code.
Object-oriented programming has a number of important features, such as: encapsulation, inheritance, polymorphism and abstraction. We will analyze these features one by one in the following sections.
Encapsulates the object with the ability to hide internal features and behaviors. The object provides some way to access it by other objects to change its internal data. In Java, there are three modifiers: public, private and protected. Each modifier gives different access to other objects that are located in the same package or under different packages.
Here are some of the benefits of using the package:
  • Protect the state of the object by hiding the properties of the object.
  • Improve the availability and maintainability of the code, because the behavior of the object can be changed individually or expanded.
  • Prohibit the poor interaction between objects to improve modularity.
Refer to this document for more details on the package and examples.
Polymorphism is a programming language that gives the same underlying data type the ability to do the same interface display. An operation on a polymorphic type can be applied to other types of values ​​above.
Inheritance gives the object the ability to get fields and methods from the base class. Inheritance provides reusable lines for code, or you can add new features to existing classes without modifying classes.
Abstraction is the step of separating the idea from the concrete instance, so the class is created according to their function rather than the implementation details. Java supports the creation of an abstract class that only traps the interface without the implementation of the method. The main purpose of this abstract technique is to separate the class’s behavior from the implementation details.
Abstract and encapsulated differences
Abstraction and encapsulation are complementary concepts. On the one hand, abstract the behavior of the object of concern. On the other hand, encapsulate the details of the object’s behavior. Usually by hiding the object internal state information to do the package, so the package can be seen as a strategy used to provide an abstract.

Common Java Interview Questions


1. What is a Java virtual machine? Why is Java called “platform-independent programming language”?

The Java Virtual Machine is a virtual machine that can execute Java bytecode. Java source files are compiled into bytecode files that can be executed by the Java virtual machine.
Java is designed to allow applications to run on any platform without the need for programmers to rewrite or recompile each platform individually. The Java virtual machine makes this possible because it knows the instruction length and other features of the underlying hardware platform.

2. What is the difference between JDK and JRE?

The Java Runtime Environment (JRE) is the Java virtual machine that will execute Java programs. It also contains the browser plugins needed to execute the applet. The Java Development Kit (JDK) is a complete Java software development package that includes JRE, compilers, and other tools (such as JavaDoc, Java Debugger) that allow developers to develop, compile, and execute Java applications.
3. What does the “static” keyword mean? Java can override (override) a private or static method?
The “static” keyword indicates that a member variable or a member method can be accessed without an instance variable of the class to which it belongs. 
Static methods in Java can not be overridden because method coverage is based on runtime dynamic binding, and static methods are compiled at compile time. The static method is not relevant to any instance of the class, so it is not conceptually applicable.
4. Can I access non-static variables in a static environment?
The static variable belongs to the class in Java, and the value in all instances is the same. When the class is loaded by the Java virtual machine, static variables are initialized. If your code tries to access non-static variables without an instance, the compiler will report an error because they have not yet been created and have not been associated with any instances.
5. What are the data types that Java supports? What is the automatic disassembly box?
The basic data types in the Java language support 8 are:
  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char
Automatic boxing is a transformation of the Java compiler between the basic data type and the corresponding object wrapper type. For example: the int into Integer, double into double, and so on. The other hand is automatically unpacking.
6. What is the meaning of Overriding and Overloading?
Method overload in Java occurs in the same class where two or more methods have the same method name but different parameters. In contrast, method coverage means that subclasses redefine the parent class. Method coverage must have the same method name, parameter list, and return type. The overlay may not restrict access to the methods it covers.
7.Java, what is the constructor? What is the constructor overload? What is a copy constructor?
When the new object is created, the constructor is called. Each class has a constructor. When the programmer does not provide a constructor to the class, the Java compiler creates a default constructor for the class.
Java constructor overload and method overload are very similar. You can create multiple constructors for a class. Each constructor must have its own unique list of parameters.
Java does not support replication constructors like C ++, because the Java does not create a default copy constructor if you do not write your own constructor.
8.Java support more inheritance?
Not supported, Java does not support multiple inheritance. Each class can only inherit a class, but can achieve multiple interfaces.
9. What is the difference between an interface and an abstract class?
Java provides and supports the creation of abstract classes and interfaces. Their implementation has in common, the difference is:
  • All the methods in the interface are implicitly abstract. While abstract classes can contain both abstract and non-abstract methods.
  • Classes can implement many interfaces, but only inherit an abstract class
  • Class If you want to implement an interface, it must implement all the methods that the interface declares. However, classes can not implement all the methods of abstract class declarations, and of course, in this case, the class must also be declared as abstract.
  • An abstract class can implement an interface without providing an interface method implementation.
  • The variables declared in the Java interface are final by default. Abstract classes can contain non-final variables.
  • The member function in the Java interface is public by default. The abstract class member function can be private, protected or public.
  • The interface is absolutely abstract and can not be instantiated. Abstract classes can not be instantiated, but if it contains a main method, it can be called.
10. What is value passing and reference passing?
An object is passed by value, meaning that a copy of the object is passed. Therefore, even if you change the copy of the object, it will not affect the value of the source object.
An object is passed by reference, meaning that it is not an actual object, but a reference to an object. As a result, changes made to the reference object are reflected on all objects.
Java thread
11. What is the difference between a process and a thread?
The process is an executing application, and the thread is an execution sequence inside the process. A process can have multiple threads. Threads are also called lightweight processes.
12. There are several different ways to create a thread? Which do you like? why?
There are three ways that can be used to create threads:
  • Inherit the Thread class
  • Implement the Runnable interface
  • An application can use the Executor framework to create a thread pool
Implementing the Runnable interface This approach is more popular because it does not need to inherit the Thread class. In the application design has been inherited in the case of other objects, which requires more inheritance (and Java does not support multiple inheritance), can only achieve the interface. At the same time, the thread pool is also very efficient, easy to implement and use.
13. General explanation of the available state of the next thread.
Thread in the implementation process, you can be in the following states:
  • Ready (runnable): thread ready to run, not necessarily immediately can begin execution.
  • Running: The code in which the process is executing the thread.
  • Waiting: The thread is in a blocked state and waits for an external process to end.
  • Sleeping: The thread is forced to sleep.
  • I / O Blocking (I / O): Wait for I / O to complete.
  • Blocked on Synchronization: Wait for a lock.
  • Dead: The thread completes execution.
14. What is the difference between the synchronization method and the synchronization code block?
In the Java language, each object has a lock. Threads can use the synchronized keyword to get locks on objects. The synchronized keyword can be applied at the method level (coarse-grained lock) or the code block level (fine-grained lock).
15. In the monitor (Monitor) internal, how to do thread synchronization? What level of synchronization should the program do?
Monitors and locks are used in a Java virtual machine. The monitor monitors a block of sync blocks, ensuring that only one thread executes the sync block at a time. Each monitor is associated with an object reference. The thread does not allow execution of the synchronization code until the lock is acquired.
16. What is deadlock?
The two processes are waiting for the implementation of the other side to continue down when the implementation of the deadlock occurred. The result is that both processes are in an infinite wait.
17. How can I ensure that N threads can access N resources without causing deadlocks?
When using multithreading, a very simple way to avoid deadlocks is to specify the order in which the locks are obtained and force the threads to get the locks in the specified order. Therefore, if all the threads are locked in the same order and release the lock, there will be no deadlock.
Java collection class
18. What are the basic interfaces of the Java collection framework?
The Java collection class provides a well-designed interface and class that supports the operation of a set of objects. Java collection class which is the most basic interface:
  • Collection: represents a group of objects, each object is its sub-elements.
  • Set: Collection that does not contain duplicate elements.
  • List: A sequence of collections, and can contain duplicate elements.
  • Map: the key (key) can be mapped to the value (value) of the object, the key can not be repeated.
19. Why does the collection class implement the Cloneable and Serializable interfaces?
The collection class interface specifies a set of objects called elements. Each concrete implementation class of a collection class interface can choose to save and sort elements in its own way. Some collection classes allow duplicate keys, some are not allowed.
20. What is an Iterator?
The Iterator interface provides a number of ways to iterate over the collection elements. Each collection class contains an 
iterative method that can return an iterator instance . The iterator can remove the elements of the underlying collection during the iteration.
The semantics and meaning of cloning or serialization are related to concrete implementations. Therefore, it should be determined by the specific implementation of the collection class how to be cloned or serialized.
21. What is the difference between Iterator and ListIterator?
The following lists their differences:
  • Iterator can be used to traverse the Set and List collections, but the ListIterator can only be used to traverse the List.
  • Iterator on the collection can only be forward traversal, ListIterator can either forward or backward.
  • The ListIterator implements the Iterator interface and contains other functions, such as adding elements, replacing elements, getting the index of the previous and subsequent elements, and so on.
22. What is the difference between fail-fast and fail-safe?
The Iterator’s security failure is based on copying the underlying collection, so it is not affected by changes in the source collection. java.util package below all the collection class is a quick failure, and java.util.concurrent package below all the class is a security failure. A fast failed iterator throws a ConcurrentModificationException exception, and a safe failed iterator never throws such an exception.
23. What is the working principle of HashMap in Java?
HashMap in Java is a key-value (key-value) in the form of storage elements. HashMap requires a hash function that uses the hashCode () and equals () methods to add and retrieve elements from the collection / collection. When the put () method is called, HashMap computes the hash value of the key, and then stores the key-value pairs in the appropriate index in the collection. If key already exists, value is updated to a new value. Some of the important features of HashMap are its capacity, load factor, and threshold resizing.
24.hashCode () and equals () methods?
HashMap in Java uses the hashCode () and equals () methods to determine the index of a key-value pair, which is used when the value is obtained by the key. If these two methods are not properly implemented, two different keys may have the same hash value, and therefore may be considered equal by the set. Moreover, these two methods are also used to find duplicate elements. So the implementation of these two methods on the accuracy and correctness of HashMap is essential.
25. What is the difference between HashMap and Hashtable?
  • Both HashMap and Hashtable implement the Map interface, so many features are very similar. But they have the following differences:
  • HashMap allows keys and values ​​to be null, while Hashtable does not allow keys or values ​​are null.
  • Hashtable is synchronized, and HashMap is not. Therefore, HashMap is more suitable for single-threaded environment, and Hashtable for multi-threaded environment.
  • HashMap provides a collection of keys that can be used to apply iteration, so the HashMap is a quick failure. On the other hand, Hashtable provides an enumeration of keys (Enumeration).
    • Hashtable is generally considered a legacy class.
26. Array (Array) and list (ArrayList) What is the difference? When should I use Array instead of ArrayList?
The following lists the differences between Array and ArrayList:
  • Array can contain basic types and object types, and ArrayList can only contain object types.
  • Array size is fixed, ArrayList size is dynamic changes.
  • ArrayList provides more methods and features, such as: addAll (), removeAll (), iterator () and so on.
  • For basic type data, the collection uses automatic boxing to reduce the amount of coding effort. However, when dealing with fixed-size basic data types, this approach is relatively slow.
27.ArrayList and LinkedList What is the difference?
ArrayList and LinkedList have implemented the List interface, they have the following differences:
  • ArrayList is an index-based data interface whose bottom is an array. It can randomly access the elements with O (1) time complexity. Correspondingly, LinkedList stores its data as an element list, and each element is linked to its previous and subsequent elements. In this case, the time complexity of finding an element is O ( n).
  • Compared to ArrayList, LinkedList insert, add, delete operation faster, because when the element is added to the collection of any position, do not need to recalculate the size of the array or update the index.
  • Linked List is more memory than ArrayList, because LinkedList stores two references for each node, one pointing to the previous element and one pointing to the next element.
28.Comparable and Comparator interface is doing? List their differences.
Java provides a Comparable interface that contains only one compareTo () method. This method can sort two objects. Specifically, it returns a negative number of 0, positive to indicate that the input object is less than, equal to, greater than the already existing object.
Java provides a Comparator interface that contains two methods, compare () and equals (). The compare () method is used to sort two input parameters, return a negative number, 0, positive number indicates that the first argument is less than, equal to, greater than the second argument. The equals () method takes an object as a parameter, which is used to determine whether the input parameter is equal to the comparator. This method returns true only if the input argument is also a comparator and the input argument is the same as the result of the current comparator.
29. What is the Java Priority Queue?
PriorityQueue is an unbounded queue based on a priority heap whose elements are sorted by natural order. At the time of creation, we can give it a comparator that is responsible for ordering the elements. PriorityQueue does not allow null values ​​because they do not have a natural order, or that they do not have any associated comparators. Finally, PriorityQueue is not thread-safe, and the time complexity of entering and leaving teams is O (log (n)).
30. Do you know big-O notation? Can you give examples of different data structures?
The large O symbol describes how well the algorithm’s size or performance is in the worst case when the elements in the data structure are added. 
Large O symbols can also be used to describe other behaviors, such as memory consumption. Because the collection class is actually a data structure, we generally use large O symbols based on time, memory and performance to choose the best implementation. Large O symbols give a good description of the performance of large amounts of data.
31. How do you weigh the use of disordered arrays or ordered arrays?
The greatest advantage of an ordered array is that the time complexity of finding is O (log n) and the unordered array is O (n). The disadvantage of an ordered array is that the time complexity of the insert operation is O (n) because the large value of the element needs to be moved back to the new element position. In contrast, the insertion time complexity of a disordered array is constant O (1).
32. What are the best practices for the Java collection framework?
  • Depending on the needs of the application, it is important to choose the type of collection you want to use. For example, if the size of the element is fixed and we can know in advance, we should use Array instead of ArrayList.
  • Some collection classes allow you to specify the initial capacity. So, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculating the hash value or expansion.
  • For reasons of type safety, readability and robustness always use generics. At the same time, the use of generic can also avoid the runtime ClassCastException.
  • Using the immutable class provided by JDK as a Map key avoids implementing hashCode () and equals () methods for our own classes.
  • Programming interface is better than implementation.
  • If the set of the underlying layers is actually empty, return a collection of length 0 or an array, and do not return null.
33.Enumeration interface and Iterator interface What are the differences?
Enumeration speed is 2 times the Iterator, while taking up less memory. However, Iterator is far more secure than Enumeration, because other threads can not modify objects that are being traversed by iterator. At the same time, Iterator allows the caller to delete the elements inside the underlying collection, which is not possible for Enumeration.
34.HashSet and TreeSet What is the difference?
HashSet is a hash table to achieve, so its elements are disordered. The time complexity of the add (), remove (), contains () methods is O (1).
On the other hand, the TreeSet is implemented by a tree structure whose elements are ordered. Thus, the time complexity of the add (), remove (), contains () methods is O (logn).
Garbage Collectors
35. Java garbage collection for what purpose? When is the garbage collection?
The purpose of garbage collection is to identify and discard applications that are no longer used to release and reuse resources.
36.System.gc () and Runtime.gc () will do anything?
These two methods are used to prompt the JVM for garbage collection. However, whether to start or delay the garbage collection is dependent on the JVM.
37. When will the finalize () method be called? What is the purpose of the finalization?
The garbage collector calls the object’s finalize () method before releasing the memory that the object occupies. It is generally recommended that the resources held by the object be released in the method.
38. If the object’s reference is set to null, will the garbage collector immediately release the memory that the object occupies?
No, in the next garbage collection cycle, this object will be recyclable.
39. What is the structure of Java heap? What is the Perm Gen space in the heap?
JVM heap is the run-time data area, all classes of examples and arrays are allocated memory on the heap. It was created when the JVM was started. The heap memory occupied by the object is collected by the automatic memory management system, that is, the garbage collector.
Heap memory is composed of objects of survival and death. The surviving object is the application that can be accessed and will not be garbage collected. The object of death is that the application is inaccessible and has not yet been recovered by the garbage collector. Until the garbage collector to recover these objects before they will always occupy the heap memory space.
40. What is the difference between a serial collector and a throughput collector?
The throughput collector uses a parallel version of the Cenozoic Garbage Collector, which is used for mid-sized and large-scale data applications. The serial collector for the majority of small applications (in the modern processor requires about 100M of memory) is enough.
41. In Java, when can an object be garbage collected?
This object can be reclaimed when the object becomes unacceptable to the application that is currently using the object.
42. JVM permanent generation will occur garbage collection?
Garbage collection does not occur on permanent generation, and if it is permanently full or exceeds the critical value, it will trigger full garbage collection (Full GC). If you look closely at the output of the garbage collector, you will find that the permanent generation is also being recycled. This is why the correct permanent generation size is a very important reason to avoid Full GC.

Leave a Reply

Your email address will not be published. Required fields are marked *