Java Interview Questions and Answers (Part 1)

This article mainly discusses object-oriented programming and its characteristics, common questions about Java and its functions, divided into 5 parts

  1. Object Oriented Programming (OOP)
  2. Common Java Questions
  3. Java thread
  4. Java Collection Class
  5. garbage collector

1. Object-Oriented Programming (OOP)

Java is a concurrent, class-based and object-oriented computer programming language. The advantages of object-oriented software development are listed below:

  1. Modular code development, easier to maintain and modify
  2. code reuse
  3. Enhanced code reliability and flexibility
  4. Increase code understandability

Object-oriented programming has many important characteristics: such as: encapsulation, inheritance, polymorphism and abstraction.

1. Package

Encapsulation provides objects with the ability to hide internal features and behavior. An object provides methods that can be accessed by other objects to change the data within it. In Java, there are 3 modifiers: public, private and protected. Each modifier grants different access rights to other objects in the same package or under different packages.

Some benefits of encapsulation:

  • Protect the state inside an object by hiding its properties
  • Improves code usability and maintainability, as the behavior of objects can be individually changed or extended
  • Improve modularity by disallowing bad interactions between objects

2. Polymorphism

Polymorphism is the ability of a programming language to present the same interface to different underlying data types. An operation on a polymorphic type can be applied to values ​​of other types

3. Inheritance

Inheritance provides objects with the ability to obtain fields and methods from base classes. Inheritance provides reusable lines of code and can also add new features to existing classes without modifying the class

4. Abstraction

Abstraction is the step of separating ideas from concrete instances, so classes are created based on their functionality rather than implementation details. Java supports the creation of abstract classes that expose only interfaces without method implementations. The main purpose of this abstraction 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, abstraction is concerned with the behavior of the object; on the other hand, encapsulation is concerned with the details of the behavior of the object. Generally, encapsulation is achieved by hiding the internal state information of the object. Therefore, encapsulation can be regarded as a strategy used to provide abstraction.

Two, common Java problems

1. What is the Java Virtual Machine? Why is Java called a "platform independent programming language"?

The Java Virtual Machine is a virtual machine process that can execute Java bytecode. Java source files are compiled into bytecode files that can be executed by the Java virtual machine. Java was designed to allow applications to run on any platform without requiring programmers to individually rewrite or recompile for each platform. The Java virtual machine makes this possible because it knows the instruction length and other characteristics 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 contains the browser plug-ins required to execute the applet. The Java Development Kit (JDK) is a complete Java software development kit that includes the JRE, compiler, and other tools (eg, JavaDoc, Java debugger) that allow developers to develop, compile, and execute Java applications.

3. What does the "static" keyword mean? Is it possible to 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 owning class. Static methods in Java cannot be overridden because method overriding is dynamically bound at runtime, while static methods are statically bound at compile time. A static method is not associated with any instance of the class, so it is not conceptually applicable.

4. Is it possible to access non-static variables in static environment?

A static variable belongs to a class in Java, and its value is the same in all instances. When a 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 complain, because these variables have not yet been created and are not associated with any instance.

5. What are the data types supported by Java? What is autoboxing?

The Java language supports 8 basic data types:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

A conversion performed by the Java compiler between the basic data type and the corresponding object wrapper type during autoboxing. For example: convert int to Integer, double convert to double, and so on. The opposite is automatic unboxing.

7. In Java, what is a constructor? What is constructor overloading? What is a copy constructor?

When a new object is created, the constructor is called. Every class has a constructor. In the case where the programmer does not provide a constructor for the class, the Java compiler will create a default constructor for the class.

Constructor overloading is very similar to method overloading in Java. Multiple constructors can be created for a class. Each constructor must have its unique parameter list.

Java doesn't support copy constructors like C++ does, the difference is because Java doesn't create a default copy constructor if you don't write your own constructor

8. Does Java support multiple inheritance?

No, Java does not support multiple inheritance. Each class can only inherit from one class, but can implement multiple interfaces.

9. What is the difference between an interface and an abstract class?

Java provides and supports creating abstract classes and interfaces. Their implementations have something in common, the differences are:

  • All methods in an interface are implicitly abstract. An abstract class can contain both abstract and non-abstract methods
  • A class can implement multiple interfaces, but can only inherit from one abstract class
  • For a class to implement an interface, it must implement all the methods declared by the interface. However, the class can not implement all the methods declared by the abstract class, of course, in this case, the class must also be declared as abstract
  • An abstract class can implement an interface without providing an implementation of the interface's methods
  • Variables declared in a Java interface are final by default. Abstract classes can contain non-final variables
  • Member functions in Java interfaces are public by default. Member functions of abstract classes can be private, protected or public
  • Interfaces are absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be called if it contains a main method
10. What is pass-by-value and pass-by-reference?
Objects are passed by value, meaning that a copy of the object is passed. Therefore, even changing the object copy will not affect the value of the source object.
Objects are passed by reference, which means that what is passed is not the actual object, but a reference to the object. Therefore, external changes to the referenced object will be reflected on all objects.
3. Java thread
11. What is the difference between a process and a thread?
A process is an executing application, and a thread is a sequence of execution within a process. A process can have multiple threads. Threads are also called lightweight processes.
12. How many different ways are there to create a thread? Which one do you like? Why?
There are three ways to create a thread:
  • Inherit from the Thread class
  • Implement the Runnable interface
  • Applications can use the Executor framework to create thread pools

Implementing the Runnable interface is preferred because it does not require subclassing the Thread class. In the case where other objects have been inherited in the application design, this requires multiple inheritance (and Java does not support multiple inheritance), and only interfaces can be implemented. At the same time, the thread pool is also very efficient and easy to implement and use

13. Briefly explain the several available states of the thread

During execution, a thread can be in the following states:

  • Ready (Runnable): The thread is ready to run, not necessarily immediately
  • Running: The process is executing the code of the thread
  • Waiting (Waiting): The thread is in a blocked state, waiting for the end of external processing
  • Sleeping: The thread is forced to sleep
  • Blocked on I/O: waiting for an I/O operation to complete
  • Blocked on Synchronization: acquire waiting locks
  • Dead: The thread has finished executing

14. What is the difference between a synchronized method and a synchronized code block?

In the java language, each object has a lock. Threads can use the synchronized keyword to acquire locks on objects. The synchronized keyword can be applied at the method level (coarse-grained locking) or the code block level (fine-grained locking)

15. Inside the monitor, how to do thread synchronization? What level of synchronization should the program do?

Monitors and locks are used together in the Java Virtual Machine. A monitor monitors a block of synchronized code to ensure that only one thread executes the synchronized block at a time. Each monitor is associated with an object reference. A thread is not allowed to execute a synchronized block of code until it acquires the lock.

16. What is a deadlock (deadlock)?

A deadlock occurs when both processes are waiting for the other to finish executing before continuing. The result is that both processes are stuck in an infinite wait.

17. How to ensure that N threads can access N resources without causing deadlock?

When using multithreading, a very simple way to avoid deadlocks is to specify the order in which locks are acquired, and force threads to acquire locks in the specified order. Therefore, if all threads acquire and release locks in the same order, there will be no deadlock.

Fourth, the 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 the Java collection class are:

  • Collection: represents a set of objects, each object is its child element
  • Set: Collection that does not contain duplicate elements
  • List: an ordered collection and can contain repeating elements
  • Map: An object that can map keys to values, keys cannot be repeated

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 concrete implementation of the collection class interface can choose to store and order elements in its own way. Some collections allow duplicate keys, some do not.

20. What is an Iterator?

The Iterator interface provides many methods for iterating over the elements of a collection. Each collection class contains iterator methods that return an iterator instance. Iterators can delete elements of the underlying collection while iterating.

The semantics and implications of cloning or serialization are implementation specific. Because, it should be determined by the concrete implementation of the collection class how to be cloned or serialized.

21. What is the difference between Iterator and ListIterator?

Their differences are listed below:

  • Iterator can be used to traverse Set and List collections, but ListIterator can only be used to traverse List
  • Iterator can only traverse the collection forward, and ListIterator can traverse both forward and backward
  • ListIterator implements the Iterator interface and includes other functions, such as: adding elements, replacing elements, getting the index of the previous and next elements, etc.

22. What is the difference between fail-fast and fail-safe?

Iterator's failsafe is based on making a copy of the underlying collection, so it is not affected by modifications on the source collection. All collection classes under the java.util package are fail-fast, while all classes under the java.util.concurrent package are fail-safe. Fail-fast iterators will throw ConcurrentModificationException, while fail-safe iterators 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 which uses hashCode() and equals() methods to add and retrieve elements to/from the collection. When the put() method is called, the HashMap calculates the hash value of the key and stores the key-value pair at the appropriate index in the collection. If the key already exists, the value will be updated with the new value. Some important properties of HashMap are its capacity, load factor and threshold resizing

24. What is the importance of hashCode() and equals() methods?

HashMap in Java uses the hashCode() and equals methods to determine the index of the key-value pair, and these two methods are also used when fetching according to the key. 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 collection. Moreover, these two methods are also used to find repeating elements. So the implementation of these two methods is crucial to the accuracy and correctness of HashMap

25. What is the difference between HashMap and HashTable?

  • Both HashMap and HashTable implement the Map interface, so many features are very similar. However, they differ in the following ways:
  • HashMap allows keys and values ​​to be null, while HashTable does not allow keys or values ​​to be null
  • HashTable is synchronous while HashMap is not. Therefore, HashMap is more suitable for single-threaded environment, while HashTable is suitable for multi-threaded environment
  • HashMap provides a collection of keys that the application can iterate over, so HashMap is fail-fast. On the other hand, HashTable provides an enumeration of keys (Enumeration)
  • HashTable is generally considered a legacy class

26. What is the difference between an array (Array) and a list (ArrayList)? When should I use Array instead of ArrayList?

The differences between Array and ArrayList are listed below:

  • Array can contain primitive types and object types, ArrayList can only contain object types
  • Array size is fixed, ArrayList size is dynamic
  • ArrayList provides more methods and features, such as: addAll(), removeAll(), iteraor(), etc.
  • For primitive types, collections use autoboxing to reduce coding effort. However, this approach is relatively slow when dealing with fixed-size primitive types

27. What is the difference between ArrayList and LinkedList?

Both ArrayList and LinkedList implement the List interface, and they have the following differences:

  • ArrayList is an index-based data interface, and its bottom layer is an array. It can perform random access to elements in O(1) time complexity. Correspondingly, LinkedList stores its data in the form of a list of elements, each element is linked with its previous and next elements, in this case, the time complexity of finding an element is O( n)
  • Compared with ArrayList, LinkedList is faster to insert, add, and delete operations, because when an element is 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 applications for each node, one points to the previous element and one points to the next element
28. What are the Comparable and Comparator interfaces for? list their differences
  • Java provides the Comparable interface which contains only one compareTo() method. This method can sort two objects. Specifically, it returns subordinate, 0, a positive number indicating that the input object is less than, equal to, or greater than an already existing object
  • Java provides Comparator interface which contains compare() and equals() methods. The compare() method to sort the two input arguments returns dependent, 0, a positive number indicating that the first argument is less than, equal to, or 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 parameter is also a comparator and the sorting result of the input parameter and the current comparator is the same
29. What is a Java priority queue (Priority Queue)?
  • PriorityQueue is an unbounded queue based on a priority heap, and its elements are sorted in natural order. At creation time, you can provide it with a comparator that is responsible for sorting the elements. PriorityQueues don't allow null values ​​because they have no natural ordering, or they don't have any associated comparators. Finally, Priority is not thread-safe, the time complexity of enqueuing and dequeuing is O(log(n))
30. Do you understand big-O notation? Can you give examples of different data structures?
  • Big O notation describes how well the algorithm scales or new energy works in the green ring scenario as the elements in the data structure increase
  • Big O notation can also be used to describe other behaviors, such as memory consumption. Because sets are actually data structures, we generally use Big-O notation to choose the best implementation based on time, memory, and performance. Big O notation can give a good indication of performance on large amounts of data
31. How to balance whether to use an array without an array or an ordered array?
  • The biggest advantage of ordered arrays is that the time complexity of search is O(log n), while the time complexity of unordered data is O(n). The disadvantage of sorted arrays is that the insertion operation has a time complexity of O(n), because elements with large values ​​have to be moved backward to make room for new elements. In contrast, the insertion time complexity of an unordered array is constant O(1)
32. What are the best practices for the Java collection class framework?

The correct choice of the type of collection to use according to the needs of the application is very important for performance, for example: if the size of the elements is fixed and known in advance, we should use Array instead of ArrayList.

Some collection classes allow specifying an initial capacity. Therefore, if we can estimate the number of elements stored, we can set the initial capacity to avoid redesigning the hash value or expanding the capacity.

Generics are always needed for type safety, readability, and robustness reasons. At the same time, using generics can also avoid ClassCastException at runtime.

Using the immutable class provided by the JDK as the key of the map can avoid implementing the hashCode() and equals() methods for our own class.

Interfaces are better than implementations when programming.

If the underlying collection is actually empty, return a collection or array with a length of 0, do not return null.

33. What are the differences between the Enumeration interface and the Iterator interface?

Enumeration is 2 times faster than Iterator while taking up less memory. However, Iterators are far safer than Enumerations because other threads cannot modify objects in the collection traversed by Iterators. At the same time, Iterator allows the caller to delete elements in the underlying collection, which is not possible with Enumeration.

34. What is the difference between HashSet and TreeSet?

HashSet is implemented by a hash table, therefore, its elements are unordered. The time complexity of add(), remove(), contains() methods is O(1)

On the other hand, TreeSet is implemented by a tree-like structure, and the elements in it are ordered. So, the time complexity of add(), remove(), contains() methods is O(logn)

5. Garbage Collectors

35. What is the purpose of garbage collection in Java? When does garbage collection take place?

The purpose of garbage collection is to identify and discard objects that are no longer used by the application to free and reuse resources

36.System.gc () and Runtime.gc () will do things?

These two methods are used to prompt the JVM to perform garbage collection. However, it is up to the JVM to start immediately or to delay garbage collection.

37. When is the finalize() method called? What is the purpose of a destructor (finalization)?

Before freeing the memory occupied by the object, the garbage collector calls the finalize() method of the object. It is generally recommended to release resources held by the object in this method.

38. If the reference of the object is set to null, will the garbage collector immediately release the memory occupied by the object?

No, in the next garbage collection cycle, the object will be recyclable.

39. What is the structure of the Java heap? What is the Perm Gen space in the heap?

The JVM's heap is the runtime data area, and all class instances and arrays are allocated memory on the heap. It is created when the JVM starts. The heap memory occupied by objects is reclaimed by the automatic memory management system, also known as the garbage collector.

Heap memory is made up of live and dead objects. Surviving objects are accessible to the application and will not be garbage collected. Dead objects are objects that are inaccessible to the application and have not yet been collected by the garbage collector. These objects will occupy memory space until the garbage collector collects them.

40. What is the difference between a serial collector and a throughput collector?

The throughput collector uses a parallel version of the young generation garbage collector, which is used for medium- and large-scale data applications. The serial collector is sufficient for most small applications (about 100M of memory on modern processors).

41. In Java, when can an object be garbage collected?

An object can be reclaimed when it becomes unreachable to the application currently using it.

42. Will garbage collection occur in the permanent generation of the JVM?

Garbage collection does not occur in the permanent generation. If the permanent generation is full or exceeds a critical value, a full garbage collection (Full GC) will be triggered. If you look closely at the output of the garbage collector, you will find that the permanent generation is also collected. .This is why the correct permanent generation size is very important to avoid Full GC.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325159868&siteId=291194637