The most common interview questions on the Java surface

Source: Internet
Author: User

Object-Oriented programming (OOP)

1. What are the aspects of object-oriented features?

Encapsulation, inheritance, polymorphism, and abstraction. Below we will analyze these features one by one.

Encapsulation gives an object the ability to hide internal attributes and behaviors. Object provides 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 that are located in the same package or under different packages.
Some of the benefits of using encapsulation are listed below:
Protects the state inside an object by hiding its properties.
Increases the usability and maintainability of the code, because the behavior of the object can be changed individually or extended.
Prevents undesirable interactions between objects to improve modularity.
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 other types of values.
Inheriting to an object provides the ability to get fields and methods from a base class. Inheritance provides a reusable line of code, or you can add a new attribute to an existing class without modifying the class.
Abstraction is the step of separating ideas from specific instances, so create classes based on their functionality rather than the implementation details. Java supports the creation of abstract classes that only burst interfaces and do not contain method implementations. The main purpose of this abstraction is to leave the class's behavior and implementation details apart.

Different points of abstraction and encapsulation

Abstraction and encapsulation are complementary concepts. On the one hand, abstract the behavior of the object. On the other hand, encapsulation focuses on the details of the object's behavior. Encapsulation is typically done by hiding the internal state information of an object, so encapsulation can be seen as a strategy to provide abstraction.

Common Java Issues

1. What is the difference between the access modifier public,private,protected and the Do not write (default)?

modifier current class same package subclass other packages
public √ √ √ √
Protected √ √ √ x
private √ x x x
default √ √ x x

Defaults to default when members of a class do not write access adornments.
The default is equivalent to exposing (public) to other classes in the same package, and for other classes that are not in the same package are equivalent to private (private). A protected (protected) subclass is equivalent to exposing a class that is not a parent-child relationship in the same package as private. In Java, the modifiers of an outer class can only be public or default, and the members of the class (including inner classes) can have the four modifiers.

What is the difference between 2.JDK and JRE?

The Java Runtime Environment (JRE) is the Java virtual machine that will execute the Java program. It also contains the browser plug-in needed to execute the applet. The Java Development Kit (JDK) is a complete Java software development package that includes a JRE, a compiler, and other tools (such as the Javadoc,java debugger) that enable developers to develop, compile, and execute Java applications.

What are the data types supported by 3.Java? What is auto-unboxing?

The Java language provides the wrapper type for each primitive type:
-Original type: boolean,char,byte,short,int,long,float,double
-Package Type: boolean,character,byte,short,integer,long,float,double
Auto-Boxing is a conversion of the Java compiler between the base data type and the corresponding object wrapper type. For example: Convert int to integer,double into double, and so on. The reverse is automatic unpacking.

class autounboxingtest {public  static  void  main  (string[] args)        {Integer A = new  Integer (4 );                  Integer B = 4 ;        //4 automatically boxed into an integer type         int  c = 4 ; System.     out . println (A = = B);        //false two references do not reference the same object  System.     out . println (A = = c); //true a automatically unboxing into int type and C comparison }}  

4. Explain the difference between final, finally and finalize.
-final: Modifier (keyword) has three usages: if a class is declared final, it means that it can no longer derive a new subclass, i.e. it cannot be inherited, so it and abstract are antonyms. Declaring variables as final ensures that they are not changed in use, and that the variable declared as final must be given the initial value at the time of declaration, whereas in subsequent references only the non-modifiable can be read. A method that is declared final can also be used only and cannot be overridden in a subclass.
-finally: usually put in try...catch ... The subsequent construct always executes the code block, which means that the program executes either normally or unexpectedly, the code here can be executed as long as the JVM is not closed, and the code that frees the external resource is written in the finally block.
-the method defined in the Finalize:object class allows the use of the Finalize () method in Java to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed, and by overriding the Finalize () method, you can defragment the system resources or perform other cleanup work.

can I overwrite (override) a private or static method in 5.Java?

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 cannot be overwritten, static modifiers are statically bound, and method overrides are for polymorphism and dynamic binding, so static decorated methods do not need to be overwritten.
The private-decorated method cannot be overridden because the private-decorated parent method is not visible in the subclass.

what does the method overlay (overriding) and method overloading (overloading) in 6.Java mean?

Method overloads in Java occur when the same class has two or more methods with the same name but different parameters. In contrast, the method overrides the method that the subclass redefined the parent class. Method overrides must have the same method name, parameter list, and return type. The override may not restrict access to the methods it covers.

in 7.Java, what is a constructor function? What is a constructor overload? What is a copy constructor?

When a new object is created, the constructor is called. Each class has a constructor function. The Java compiler creates a default constructor for this class in cases where the programmer does not provide a constructor for the class.

Constructor overloading and method overloading are similar in Java. You can create multiple constructors for a class. Each constructor must have its own unique argument list.

Java does not support copy constructors like in C + + because Java does not create a default copy constructor if you do not write the constructor yourself.

8. 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 something in common, and the difference is that:

All methods in an interface are implicitly abstract. Abstract classes can contain both abstract and non-abstract methods.
A class can implement many interfaces, but only one abstract class is inherited
Class if you want to implement an interface, it must implement all the methods that the interface declares. However, a class can not implement all methods of an abstract class declaration, and of course, in this case, the class must also be declared 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. An abstract class can contain non-final variables.
The member functions in the Java interface are public by default. The member functions of an abstract class can be private,protected or public.
An interface is absolutely abstract and cannot be instantiated. An abstract class can also not be instantiated, but it can be called if it contains the main method.

does 9.Java support multiple inheritance?

Not supported, Java does not support multiple inheritance. Each class can inherit only one class, but it can implement multiple interfaces.

10. What is value passing and reference passing?

Value passing: When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the change of the execution form parameter value in the method does not affect the value of the actual parameter.
Reference delivery: Also known as a pass-through address. When a method is called, the reference to the actual argument (that is, the value of the address, not the parameter) is passed to the corresponding formal parameter in the method,
Executing the action on the formal parameter in the method is actually the operation of the actual parameter (the address operation), so that changes in the value of the formal parameter in the method's execution will affect the value of the actual parameter.

Java Threads

1. What is the difference between a process and a thread?

A process is an application that executes, and a thread is an execution sequence within a process. A process can have multiple threads. Threads are also called lightweight processes.

2. How do I create threads in several different ways? Which is the optimal one? Why?

There are three ways to create threads:

Inherit the thread class
Implementing the Runnable Interface
Applications can use the executor framework to create a thread pool

Implementing the Runnable interface is more popular because this does not require inheriting the thread class. This requires multiple inheritance (while Java does not support multiple inheritance) in cases where other objects have been inherited in the design of the application, and only interfaces can be implemented. At the same time, the thread pool is very efficient and easy to implement and use.

3. What are some of the available states of the thread?

Threads can be in the following States during execution:

Ready (Runnable): The thread is ready to run, not necessarily immediately start execution.
Running (Running): The code of the thread that the process is executing.
Waiting (Waiting): The thread is in a blocked state, waiting for the external processing to end.
Sleep (sleeping): The thread is forced to sleep.
I/O blocking (Blocked on I/O): Waits for I/O operation to complete.
Synchronous blocking (Blocked on synchronization): Waits for a lock to be acquired.
Death (Dead): The thread completed execution.

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

In the Java language, each object has a lock. A thread can use the Synchronized keyword to obtain a lock on an object. The Synchronized keyword can be applied at the method level (coarse-grained locks) or at the code block level (fine-grained locks).

5. How does thread synchronization work inside the monitor? What level of synchronization should the program do?

Monitors and locks are used in Java virtual machines. The monitor monitors a block of synchronization code to ensure that only one thread executes the synchronized code block at a time. Each monitor is associated with an object reference. The thread does not allow synchronization code to be executed until the lock is acquired.

6. What is a deadlock (deadlock)?

A deadlock occurs when two processes are waiting for the other party to execute until execution is complete. As a result, two processes are trapped in infinite waiting.

7. How do I ensure that n threads can access n resources without causing a 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 order specified. Therefore, if all the threads lock and release the lock in the same order, there will be no deadlock.

8. What is the difference between the sleep () method of a thread and the yield () method?
-The Sleep () method gives other threads the opportunity to run without taking into account the priority of the thread, thus giving the low-priority thread a chance to run, and the yield () method only gives the same priority or higher priority to the thread that runs the opportunity;
-the thread executes the sleep () method and then goes into a blocking (blocked) state, and the yield () method is transferred to the ready State;
-The Sleep () method declaration throws interruptedexception, and the yield () method does not declare any exceptions;
The-Sleep () method is more portable than the yield () method, which is related to operating system CPU scheduling.

9. Examples of synchronous and asynchronous.

If there is a critical resource in the system (a resource with fewer resources than the number of threads competing for resources), such as when the data being written may be read by another thread, or the data being read may have been written by another thread, then the data must be accessed synchronously (the exclusive lock in the database operation is the best example). When an application calls a method that takes a long time to execute on an object and does not want the program to wait for the method to be returned, it should use asynchronous programming, which is often more efficient in many cases with asynchronous approaches. In fact, the so-called synchronization refers to the blocking operation, and asynchronous is non-blocking operation.

10. Does starting a thread call the run () or start () method?

Starting a thread is calling the start () method so that the virtual processor represented by the thread is in a running state, which means that it can be dispatched and executed by the JVM, which does not mean that the thread will run immediately. The run () method is the method by which a callback (callback) is to be made after the thread starts.

Java Collection Classes

What are the basic interfaces of the 1.Java collection class framework?

The Java Collection class provides a set of well-designed interfaces and classes that support the manipulation of a set of objects. The most basic interfaces within the Java Collection class are:

Collection: Represents a set of objects, each of which is its child element.
Set: A collection that does not contain duplicate elements.
List: A sequence of collection, and can contain repeating elements.
Map: You can map a key (key) to an object with a value, and the key cannot be duplicated.

2. 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 optionally save and sort the elements in its own way. Some collection classes allow duplicate keys, some are not allowed.
The semantics and meanings of cloning (cloning) or serialization (serialization) are related to specific implementations. Therefore, the specific implementation of the collection class should determine how to be cloned or serialized.

3. What is an iterator (Iterator)?

The iterator interface provides many ways to iterate over a collection element. Each collection class contains an instance of the iterator that can be returned
Iterative methods. Iterators can delete elements of the underlying collection during the iteration.

What is the difference between 4.Iterator and listiterator?

Their differences are listed below:

The iterator can be used to traverse the set and list collection, but Listiterator can only traverse the list.
Iterator to a collection can only be forward traversal, listiterator can be either forward or back.
Listiterator implements the iterator interface and includes other functions such as adding elements, replacing elements, getting the index of the previous and subsequent elements, and so on.

5. What is the difference between fast failure (fail-fast) and security failure (fail-safe)?

Iterator's security failure is based on a copy of the underlying collection, so it is not affected by modifications on the source collection. All of the collection classes below the Java.util package are fast failures, and all classes under the Java.util.concurrent package fail safely. A fast-failing iterator throws an concurrentmodificationexception exception, and a security-failed iterator never throws such an exception.

How does the HashMap in 6.Java work?

HashMap in Java is a key-value pair (Key-value) that stores elements. HashMap requires a hash function that uses the hashcode () and Equals () methods to add and retrieve elements to the collection/collection. When the put () method is called, HashMap calculates the hash value of the key and stores the key-value pair on the appropriate index in the collection. If the key already exists, value is updated to the new value. Some of the important features of HashMap are its capacity (capacity), load factor (payload factor) and expansion limit (threshold resizing).

Where does the importance of the 7.hashCode () and Equals () methods manifest?

HashMap in Java uses the hashcode () and Equals () methods to determine the index of key-value pairs, which are used when the values are obtained by 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 discover duplicate elements. So the realization of these two methods is very important to the accuracy and correctness of hashmap.

What is the difference between 8.HashMap and Hashtable?

HashMap and Hashtable both implement the map interface, so many features are very similar. However, they have the following different points:
HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null.
The Hashtable is synchronous, while HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multithreaded environments.
HashMap provides a collection of keys that can be used for iteration, so HashMap is a quick failure. On the other hand, Hashtable provides an enumeration of keys (enumeration).
Hashtable is generally considered to be a legacy class.

9. What is the difference between arrays (array) and list (ArrayList)? When should I use array instead of ArrayList?

The different points of the array and ArrayList are listed below:

An array can contain primitive types and object types, and ArrayList can only contain object types.
The array size is fixed, and the size of the ArrayList is dynamically changing.
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 coding effort. However, this approach is relatively slow when dealing with fixed-size base data types.

What is the difference between 10.ArrayList and LinkedList?

ArrayList and LinkedList all implement the list interface, they have the following different points:

ArrayList is an index-based data interface, and its underlying is an array. It can randomly access elements with an O (1) time complexity. In contrast, LinkedList stores its data as a list of elements, with each element linked to its previous and subsequent elements, in which case the time complexity of finding an element is O (n).

It is faster to insert, add, and delete than Arraylist,linkedlist, because when an element is added anywhere in the collection, it is not necessary to recalculate the size as an array or to update the index.

LinkedList accounts for more memory than ArrayList because LinkedList stores two references for each node, one to the previous element, and one to the next.

What are the 11.Comparable and comparator interfaces for? List the differences between them.

Java provides a comparable interface that contains only one CompareTo () method. This method can be used to sort two objects in a single order. Specifically, it returns a negative number, 0, a positive number 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 of compare () and Equals (). The Compare () method is used to sort two input parameters, return a negative number, 0, and a positive number indicates that the first parameter is less than, equal to, greater than the second argument. The Equals () method requires an object as a parameter that determines whether the input parameters are equal to comparator. This method returns true only if the input parameter is also a comparator and the input parameter is the same as the current comparator's ordering result.

12. What is the Java priority queue?

Priorityqueue is an unbounded queue based on a priority heap whose elements are sorted in natural order (natural orders). At the time of creation, we can provide it with a comparator that is responsible for ordering the elements. Priorityqueue do not allow null values because they do not have a natural order, or they do not have any associated comparators. Finally, Priorityqueue is not thread-safe, and the time complexity of the queue and the queue is O (log (n)).

13. Do you know the big O symbol (big-o notation)? Can you give examples of different data structures?

The large O symbol describes how well the size of the algorithm or performance is in the worst scenario when the elements in the data structure increase.
The large o symbol can also be used to describe other behaviors, such as memory consumption. Because the collection class is actually a data structure, we generally use the large O notation to choose the best implementation based on time, memory, and performance. The large o symbol provides a good indication of the performance of a large amount of data.

14. How do I weigh the use of unordered arrays or ordered arrays?

The greatest benefit of an ordered array is that the time complexity of the lookup 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 elements with large values need to be moved backward to make the new element space. Instead, the insertion time complexity of an unordered array is constant O (1).

What are the best practices for the 15.Java collection class framework?

It is important for performance to correctly select the type of collection to use according to the needs of the application, such as: if the size of the element is fixed and can be known beforehand, we should use array instead of ArrayList.
Some collection classes allow you to specify the initial capacity. Therefore, if we can estimate the number of elements stored, we can set the initial capacity to avoid recalculation of hash values or expansion.
For type safety, the reason for readability and robustness is always to use generics. Also, using generics avoids classcastexception at run time.
Using the invariant Class (immutable Class) provided by the JDK as the key to the map avoids implementing the hashcode () and Equals () methods for our own classes.
The interface is better than the implementation when programming.
The underlying collection is actually empty, the return length is a collection of 0 or an array, do not return null.

What are the differences between the 16.Enumeration interface and the iterator interface?

The enumeration is twice times faster than iterator and consumes less memory at the same time. However, iterator is far more secure than enumeration because other threads are not able to modify objects in the collection that is being traversed by iterator. At the same time, iterator allows the caller to delete elements from the underlying collection, which is not possible for enumeration.

What is the difference between 17.HashSet and TreeSet?

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

On the other hand, TreeSet is implemented by a tree-shaped structure in which the elements are ordered. Therefore, the time complexity of the add (), remove (), contains () method is O (Logn).

garbage collector (garbage collectors)

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

The purpose of garbage collection is to identify and discard objects that the app is no longer using to free and reuse resources.

What will 2.system.gc () and RUNTIME.GC () do?

These two methods are used to prompt the JVM for garbage collection. However, starting or delaying a garbage collection immediately depends on the JVM.

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

The garbage collector calls the object's Finalize () method before releasing the memory occupied by the object. It is generally recommended that the resources held by the object be disposed of in this method.

4. If the object's reference is set to NULL, will the garbage collector immediately release the memory occupied by the object?

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

What is the structure of the 5.Java heap like? What is the permanent generation in the heap (Perm Gen space)?

The JVM's heap is the run-time 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 that the object occupies is reclaimed by the automatic memory management system, which is the garbage collector.

Heap memory is made up of surviving and dying objects. The surviving objects are accessible to the app and are not garbage collected. The object of death is the object that the app is inaccessible and has not been reclaimed by the garbage collector. Until the garbage collector reclaims these objects, they will occupy the heap memory space.

6. What is the difference between a serial (serial) collector and a throughput (throughput) collector?

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

7. In Java, when can objects be garbage collected?

This object can be recycled when the object becomes inaccessible to applications that currently use the object.

Is there a garbage collection in the permanent generation of 8.JVM?

Garbage collection does not occur in a permanent generation, and if it is permanently full or exceeds the threshold, a full GC is triggered. If you look closely at the output 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 for avoiding full GC. Please refer to the following Java8: from the permanent generation to the Meta data area

Note: The JAVA8 has been removed from the permanent generation, and a new native memory area called the metadata area has been added.

The most common interview questions on the Java surface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.