In this article, we will discuss various types of interview questions in Java interviews that allow employers to test candidates' Java and common object-oriented programming capabilities. The following chapters are divided into two previous and next articles. The first article will discuss object-oriented programming and its characteristics, common questions about Java and its functions, Java collection classes, garbage collectors, and the second article will mainly discuss exception handling, Java applets, Swing, JDBC, remote method calls (RMI), Servlets and JSP.
start!
Table of contents
Object-Oriented Programming (OOP)
Common Java problems
Java threads
Java Collection Class
Garbage collector
Object-Oriented Programming (OOP)
Java is a computer programming language that supports concurrent, class-based and object-oriented. The advantages of object-oriented software development are listed below:
Object-oriented programming has many important features, such as: encapsulation, inheritance, polymorphism and abstraction. In the following chapters, we will analyze these characteristics one by one.
Package
Encapsulation provides objects with the ability to hide internal features and behaviors. An object provides some methods that can be accessed by other objects to change the data inside it. In Java, there are 3 modifiers: public, private and protected. Each modifier gives different access rights to other objects located in the same package or under different packages.
Here are some of the benefits of using encapsulation:
Refer to this document for more details and examples about encapsulation.
Polymorphic
Polymorphism is a capability of programming languages to demonstrate the same interfaces for different underlying data types. Operations on a polymorphic type can be applied to other types of values.
inherit
Inheritance provides objects with the ability to obtain fields and methods from base classes. Inheritance provides reused lines of code, and can also add new features to existing classes without modifying them.
abstract
Abstraction is the step of separating ideas from concrete instances, so create classes based on their functionality rather than implementation details. Java supports creating abstract classes that only expose interfaces but do not include method implementations. The main purpose of this abstract technique is to separate the behavior of the class from the implementation details.
The difference between abstraction and encapsulation
Abstraction and encapsulation are complementary concepts. On the one hand, abstract focuses on the behavior of objects. On the other hand, encapsulation focuses on the details of the object's behavior. Generally, encapsulation is achieved by hiding the internal state information of the object. Therefore, encapsulation can be regarded as a strategy to provide abstraction.
Common Java problems
1.What is a Java virtual machine? Why is Java called a "platform-independent programming language"?
A Java virtual machine is a virtual machine process that can execute Java bytecode. The Java source file is compiled into a bytecode file that can be executed by a Java virtual machine.
Java is designed to allow applications to run on any platform without requiring programmers to rewrite or recompile each platform separately. Java virtual machines make 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 a Java virtual machine that will execute Java programs. It also includes browser plugins required to execute applets. The Java Development Toolkit (JDK) is a complete Java software development package that includes JRE, compiler and other tools (such as JavaDoc, Java debugger), which allows developers to develop, compile and execute Java applications.
3. What does the keyword "static" mean? Can I override a private or static method in Java?
The "static" keyword indicates that a member variable or member method can be accessed without an instance variable of the class to which it belongs.
The static method in Java cannot be overwritten because method overwritten is based on runtime dynamic binding, while the static method is static binding at compile time. The static method is not related to any instance of the class, so it does not apply conceptually.
4. Is it possible to access non-static variables in a static environment?
The static variable belongs to the class in Java, and its value in all instances is the same. When the class is loaded by a Java virtual machine, the static variable will be initialized. If your code tries to access non-static variables without instances, the compiler will report an error because these variables have not been created yet and have not been associated with any instances.
5.What are the data types supported by Java? What is automatic disassembly?
The basic data types supported by Java language are:
Automatic boxing is a conversion made by the Java compiler between the basic data type and the corresponding object wrapper type. For example: convert int into Integer, double into double, etc. Otherwise, it is automatic unboxing.
6. What do method overriding and method overloading in Java mean?
Method overloading in Java occurs when two or more methods have the same method names but different parameters in the same class. In contrast, method override means that the subclass redefines the parent class's method. Method overrides must have the same method name, parameter list, and return type. The overwriter may not restrict access to the methods it covers.
7.What is a constructor in Java? What is constructor overloading? What is a copy constructor?
When a 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 will create a default constructor for the class.
Constructor overloading and method overloading in Java are very similar. Multiple constructors can be created for a class. Each constructor must have its own unique parameter list.
Java does not support copy constructors like in C++. This difference is because if you do not write the constructor yourself, Java will not create the default copy constructor.
8. Does Java support multiple inheritance?
Not supported, Java does not support multiple inheritance. Each class can only inherit one class, but can implement 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 implementations have similarities, and the differences are:
You can also refer to the difference between abstract classes and interfaces in JDK8
10.What are value passing and reference passing?
The object is passed by a value, which means that a copy of the object is passed. Therefore, even if the object copy is changed, the value of the source object will not be affected.
An object is passed by reference, which means that it is not the actual object passed, but the object's reference. Therefore, external changes to the referenced object will be reflected on all objects.
Java threads
11. What is the difference between a process and a thread?
A process is an executing application, and a thread is an execution sequence within the process. A process can have multiple threads. Threads are also called lightweight processes.
12. How many different ways are there to create threads? Which one do you like? Why?
There are three ways to create threads:
Implementing the Runnable interface is more popular because it does not require inheriting the Thread class. When other objects have been inherited in the application design, this requires multiple inheritance (while Java does not support multiple inheritance), it can only implement interfaces. At the same time, thread pools are also very efficient and easy to implement and use.
13. A summary explanation of several available states of threads.
During execution, threads can be in the following states:
14. What is the difference between synchronization method and synchronization code block?
In Java language, each object has a lock. Threads can use the synchronized keyword to obtain locks on objects. Synchronized keyword can be applied at the method level (coarse-grained lock) or at the code block level (fine-grained lock).
15. How to synchronize threads within the monitor? What level of synchronization should the program do?
Monitors and locks are used together in Java virtual machines. The monitor monitors a synchronous code block, ensuring that only one thread executes the synchronous code block at a time. Each monitor is associated with an object reference. Threads do not allow synchronization code to be executed before acquiring the lock.
16.What is deadlock?
When both processes are waiting for the other party to complete execution before continuing to execute, a deadlock occurs. The result is that both processes are trapped in infinite waiting.
17. How to 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 acquired and force the thread to acquire the locks in the specified order. Therefore, if all threads lock and release locks in the same order, there will be no deadlock.
Java Collection Class
18.What are the basic interfaces of the Java collection class framework?
Java collection classes provide a well-designed set of interfaces and classes that support operations on a set of objects. The most basic interfaces in Java collection classes are:
19. Why does the collection class not implement the Cloneable and Serializable interfaces?
The collection class interface specifies a set of objects called elements. Each specific implementation class of the collection class interface can choose to save and sort elements in its own way. Some collection classes allow duplicate keys, while others do not.
20.What is an iterator?
The Iterator interface provides many ways to iterate over collection elements. Each collection class contains iterative methods that can return an iterator instance. The iterator can delete elements of the underlying collection during iteration.
The semantics and meanings of cloning or serialization are related to specific implementations. Therefore, the specific implementation of the collection class should determine how to be cloned or serialized.
21. What is the difference between Iterator and ListIterator?
The difference is listed below:
22. What is the difference between fast failure (fail-fast) and safe failure (fail-safe)?
Iterator's security failure is based on making copies of the underlying collection, so it is not affected by modifications on the source collection. All collection classes under the java.util package fail quickly, while all classes under the java.util.concurrent package fail safely. A fast-failed iterator will throw a ConcurrentModificationException exception, while a safe-failed iterator will never throw such an exception.
23. What is the working principle of HashMap in Java?
HashMap in Java stores elements in the form of key-value pairs. HashMap requires a hash function that uses hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, HashMap will calculate the hash value of the key and then store the key value pairs on the appropriate index in the set. If the key already exists, the value will be updated to a new value. Some important features of HashMap are its capacity, load factor and threshold resizing.
24. Where does the importance of hashCode() and equals() methods reflect?
HashMap in Java uses hashCode() and equals() methods to determine the index of key-value pairs. These two methods will also be used when obtaining values based on keys. If these two methods are not implemented correctly, 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 discover duplicate elements. Therefore, the implementation of these two methods is crucial to the accuracy and correctness of HashMap.
25. What is the difference between HashMap and Hashtable?
26. What is the difference between an array (Array) and a list (ArrayList)? When should I use Array instead of ArrayList?
The following lists the differences between Array and ArrayList:
27. What is the difference between ArrayList and LinkedList?
Both ArrayList and LinkedList implement List interfaces, and they have the following differences:
ArrayList is an index-based data interface, and its underlying layer is an array. It allows random access to elements with O(1) time complexity. Correspondingly, LinkedList stores its data in the form of an element list, each element is linked to its previous and next elements. In this case, the time complexity of finding an element is O(n).
Compared with ArrayList, the insertion, addition and deletion of LinkedList is faster because when elements are added to any position in the collection, there is no need to recalculate the size or update the index like an array.
LinkedList takes up 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.
You can also refer to ArrayList vs. LinkedList.
28.What do Comparable and Comparator interfaces do? 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, 0, and positive number to indicate that the input object is less than, equal to, and greater than the already existing object.
Java provides a Comparator interface that includes two methods: compare() and equals(). The compare() method is used to sort two input parameters, returning a negative number, 0, and a positive number indicates that the first parameter is less than, equal to, and greater than the second parameter. The equals() method requires an object as a parameter, which is used to determine whether the input parameter is equal to the comparator. This method returns true only when the input parameter is also a comparator and the input parameter and the current comparator sorting result are the same.
29.What is a Java Priority Queue?
PriorityQueue is an unbounded queue based on the priority heap, and its elements are sorted in natural order. When created, we can provide it with a comparator responsible for sorting elements. PriorityQueue does not allow null values because they have no natural order, or they do not have any associated comparators. Finally, PriorityQueue is not thread-safe, and the time complexity of incoming and dequeueing is O(log(n)).
30. Do you understand the big O symbol (big-O notation)? Can you give examples of different data structures?
The big O symbol describes how good the scale or performance of the algorithm is in the worst scenario when the elements in the data structure increase.
Big O symbols can also be used to describe other behaviors, such as memory consumption. Because collection classes are actually data structures, we generally use large O symbols to choose the best implementation based on time, memory and performance. Large O symbols can give a good explanation of the performance of large amounts of data.
31. How to trade off whether to use an unordered array or an ordered array?
The biggest advantage of an ordered array is that the time complexity of the search is O(log n), while the unordered array is O(n). The disadvantage of ordered arrays is that the time complexity of the insertion operation is O(n), because elements with large values need to be moved backwards to make room for the new element. In contrast, the insertion time complexity of an unordered array is the constant O(1).
32. What are the best practices for Java collection class frameworks?
Correctly selecting the type of collection to be used according to the needs of the application is very important for performance. For example: if the size of the element is fixed and can be known in advance, we should use Array instead of ArrayList.
Some collection classes allow specifying initial capacity. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculating the hash value or expanding it.
For type safety, readability and robustness, generics are always used. At the same time, using generics can also avoid ClassCastException at runtime.
Using the immutable class provided by JDK as the key to the Map can avoid implementing the hashCode() and equals() methods for our own classes.
Interfaces are better than implementation when programming.
When the underlying collection is actually empty, return a set or array with length 0, and do not return null.
33. What are the differences between the Enumeration interface and the Iterator interface?
Enumeration is twice as fast as Iterator, while consuming less memory. However, Iterator is much safer than Enumeration, because other threads cannot modify objects in the collection being traversed by iterator. At the same time, Iterator allows the caller to delete elements in the underlying collection, which is impossible for Enumeration.
34. What is the difference between HashSet and TreeSet?
HashSet is implemented by a hash table, so its elements are unordered. The time complexity of the add(), remove(), and contains() methods is O(1).
On the other hand, TreeSet is implemented by a tree-shaped structure, and the elements inside it are ordered. Therefore, the time complexity of the add(), remove(), and contains() methods is O(logn).
Garbage Collectors
35. What is the purpose of garbage collection in Java? When will garbage be collected?
The purpose of garbage collection is to identify and discard objects that the application no longer uses to free and reuse resources.
36. What will System.gc() and Runtime.gc() do?
These two methods are used to prompt the JVM to perform garbage collection. However, starting immediately or delaying garbage collection is JVM dependent.
37. When is the finalize() method called? What is the purpose of destructors?
Before freeing the memory occupied by the object, the garbage collector calls the object's finalize() method. It is generally recommended to release resources held by objects in this method.
38. If the object's reference is set to null, will the garbage collector immediately release the memory occupied by the object?
No, this object will be recyclable in the next garbage collection cycle.
39. What does the Java heap structure look like? What is Perm Gen space in the heap?
The JVM's heap is the runtime data area, and all instances and arrays of classes are allocated memory on the heap. It is created when the JVM is 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 that survive and die. The surviving objects are accessible to the application and will not be garbage collected. The dead object is an object that is not accessible to the application and has not been recycled by the garbage collector. They will occupy heap memory space until the garbage collector reclaims these objects.
40. What is the difference between a serial collector and throughput collector?
Throughput collectors use parallel versions of the next generation of garbage collectors, which are used for applications with medium-sized and large-scale data. Serial collectors are enough for most small applications (need about 100M of memory on modern processors).
41. In Java, when can objects be garbage collected?
When an object becomes unreachable to the application currently using this object, the object can be recycled.
42. Will garbage collection occur in the permanent generation of JVM?
Garbage collection will not occur in the permanent generation. If the permanent generation is full or exceeds the critical value, it will trigger full garbage collection (Full GC). If you carefully check the output information of the garbage collector, you will find that the permanent generation is also recycled. This is why the correct permanent generation size is very important to avoid Full GC. Please refer to Java 8: From permanent generation to metadata area
(Translator's note: The permanent generation has been removed in Java 8, and a new native memory area called the metadata area has been added)
The above is a compilation of the information for Java interview questions. We will continue to add relevant information in the future. Thank you for your support to this site!