Java59 common interview questions with answers

Basic aspects of Java:
1. The difference between the scope of public, private, protected, and when not writing
A: The difference is as follows:
Insert picture description here

The default is friendly when not writing

2, Anonymous Inner Class (anonymous inner class) can extend (inherit) other classes, whether it can implement interface (interface)
A: An anonymous inner class is an inner class without a name. Cannot extend (inherit) other classes, but an inner class can be used as an interface, implemented by another inner class
3. The difference between Static Nested Class and Inner Class
Answer: Nested Class (usually in C++), Inner Class (usually JAVA's statement). The biggest difference between Java inner classes and C++ nested classes is whether there are references to the outside. Note: Static inner classes (Inner Class) means a creation of a static class objects inside, you do not need an external object, from one object 2 can not access a static class inside an external class object
distinction 4, and & & &
A : & Is a bitwise operator, which means bitwise AND operation, && is a logical operator, which means logical and (and)
5. The difference between Collection and Collections
A: Collection is the superior interface of the collection class, and the inheritance and his interface are mainly Set And List.
Collections is a helper class for the collection class. It provides a series of static methods to realize the search, sorting, thread safety and other operations of various collections.
6. When to use assert
Answer: assertion is a common debugging method in software development, and many development languages ​​support this mechanism. In implementation, assertion is a statement in the program that checks a boolean expression. A correct program must ensure that the value of the boolean expression is true; if the value is false, the program is already in an incorrect state Next, the system will give a warning or exit. Generally speaking, assertion is used to ensure the most basic and critical correctness of the program. The assertion check is usually turned on during development and testing. In order to improve performance, after the software is released, the assertion check is usually closed.
7. String s = new String("xyz"); Several String Objects are created.
Answer: Two, one character object, one character object reference object
8. How much is Math.round(11.5)? How much is Math.round(-11.5)?
Answer: Math.round(11.5)12;Math.round(-11.5)-11;round method returns the long integer closest to the parameter, the parameter After adding 1/2, find the floor
9. Short s1 = 1; s1 = s1 + 1; What's wrong? short s1 = 1; s1 += 1; What's wrong?
Answer: short s1 = 1; s1 = s1 + 1 ; (The result of the s1+1 operation is int type, and the type needs to be coerced) short s1 = 1; s1 += 1; (can be compiled correctly)
10. Is there any goto
in Java? Use
11. Does the array have a length() method? Does a String have a length() method?
Answer: The array does not have the length() method, but has the property of length. String has
the difference between length() method 12, Overload and Override. Can the Overloaded method change the type of return value?
Answer: Method Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of polymorphism between a parent class and a subclass, and overloading is a manifestation of polymorphism in a class. If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden. When the object of the subclass uses this method, the definition in the subclass will be called. For it, the definition in the parent class is like being "shielded". If multiple methods with the same name are defined in a class, they either have different numbers of parameters or different parameter types, it is called method overloading. The Overloaded method can change the type of the return value.
13. The elements in the Set cannot be repeated, so what method can be used to distinguish whether they are repeated or not? Is it used or equals()? What is the difference between them?
Answer: The elements in Set are Cannot be repeated, then use the iterator() method to distinguish whether it is repeated or not. equals() is to judge whether two Sets are equal
equals() and == method to determine whether the reference value points to the same object equals() is overwritten in the class, in order to return when the content and type of two separate objects match Truth
14, give me a runtime exception you most often see
Answer: Common runtime exceptions are as follows: ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, IllegalArgumentException, Illegal,MonitorStateException, IllegalPathStateException, OpoundResourceOfNegativeStateException, IllegalPathStateException, Illegal,MonitorStateException, IllegalPathStateException, OpoundOut NullPointerException, ProfileDataException, ProviderException, RasterFormatException, SecurityException, SystemException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException
15. What is the difference between error and exception?
Answer: error represents a serious problem when recovery is not impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such a situation
An exception represents a design or implementation problem. In other words, it means that if the program runs normally, it will never happen.
16. List, Set, Map inherit from Collection interface
A: List, Set, Map is not
17, what is the difference between abstract class and interface
A: Statement The class that does not implement the method is called the abstract class (abstract class), it is used to create a class that reflects some basic behavior, and declare methods for the class, but the class cannot be implemented in the class Happening. Cannot create an instance of the abstract class. However, you can create a variable whose type is an abstract class and let it point to an instance of a concrete subclass. There cannot be abstract constructors or abstract static methods. Subclasses of the Abstract class provide implementations for all abstract methods in their parent class, otherwise they are also abstract classes. Instead, implement the method in the subclass. Other classes that know its behavior can implement these methods in the class.
Interface is a variant of the abstract class. In the interface, all methods are abstract. Multiple inheritance can be achieved by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. Interface can only define static final member variables. The implementation of an interface is similar to a subclass, except that the implementation class cannot inherit behavior from the interface definition. When a class implements a special interface, it defines (that is, the program body gives) all the methods of this interface. Then, it can call the methods of the interface on any object of the class that implements the interface. Because of the abstract class, it allows to use the interface name as the type of the reference variable. The usual dynamic link will take effect. Reference can be converted to interface type, or conversion from interface type, the instanceof operator can be used to determine whether an object class implements the interface
18, whether the abstract method which can be static, it is also a native, it also is synchronized
A :both are not
19. Can interfaces inherit interfaces? Can abstract classes implement interfaces? Can abstract classes inherit concrete classes?
Answer: Interfaces can inherit interfaces. Abstract class can implement (implements) interface, whether abstract class can inherit entity class, but the premise is that entity class must have a clear constructor
20, whether constructor can be overridden
A: Constructor cannot be inherited, so it cannot be overridden Overriding, but can be overloaded Overloading
21. Can the String class be inherited?
A: The String class is a final class, so it cannot be inherited.
22. There is a return statement in try {}, then the one in finally {} immediately after the try Will the code be executed, when will it be executed, before or after the return?
Answer: It will be executed, before the return.
23. Use the most efficient method to calculate how much 2 times 8 is equal to.
Answer: 2 << 3
24, two Objects have the same value (x.equals(y) == true), but they can have different hash codes. Is this sentence correct?
Answer: No, they have the same hash code
25. When an object is passed as a parameter After a method, this method can change the properties of the object and return the changed result. So, is it a value transfer or a reference transfer?
Answer: It is a value transfer. The Java programming language only has parameters passed by value. When an object instance is passed to a method as a parameter, the value of the parameter is a reference to the object. The content of the object can be changed in the called method, but the reference of the object will never change
26. Can swtich be used on byte, whether it can be used on long, and whether it can be used on String
Answer: In witch(expr1), expr1 is an integer expression. Therefore, the parameters passed to switch and case statements should be int, short, char or byte. Neither long nor string can affect swtich
27, the difference between ArrayList and Vector, and the difference between HashMap and Hashtable.
Answer: ArrayList and Vector are mainly from two aspects.
1. Synchronization: Vector is thread-safe, that is to say, it is synchronized. Yes, and ArrayList is insecure for online programs and is not synchronized.
2. Data growth: When it needs to grow, Vector grows by one by default, while ArrayList is half of the original.
HashMap and HashTable are mainly from three aspects.
1. Historical reasons: Hashtable is based on the obsolete Dictionary class. HashMap is an implementation of the Map interface introduced by Java 1.2
. 2. Synchronization: Hashtable is thread-safe, which means it is synchronous, while HashMap is not safe for online programs
Yes , not synchronized. Three. Value: Only HashMap allows you to use a null value as the key or value of a table entry.
28. Can a char variable store a Chinese character? Why?
Answer: Yes, it can be defined as a Chinese character Yes, because java is encoded in unicode, a char occupies 16 bytes, so it’s okay to put a Chinese character
29. What is GC? Why is GC?
Answer: GC means garbage collection (Gabage Collection). Memory processing is a place where programmers are prone to problems. Forgetting or wrong memory recovery can cause instability or even crash of the program or system. The GC function provided by Java can automatically monitor objects. Whether to exceed the scope to achieve the purpose of automatic memory recovery, the Java language does not provide a display operation method to release the allocated memory.
30. Is the float type float f=3.4 correct?
Answer: Incorrect. Accuracy is not accurate, and should cast as follows: float f = (float) 3.4
31, describes Collection FrameWork JAVA (including how to write your own data structure)?
Answer: Collection FrameWork as follows:
Collection
├List
│├ LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap
Collection is the most basic collection interface. A Collection represents a group of Objects, that is, the elements of the Collection. The
Map provides a key to value mapping.
32, Abstract class and interface?
Answer: Both abstract class and interface are used for abstraction, but abstract class (in JAVA) can have its own partial implementation, while interface is completely a logo (and has multiple inheritance functions).
The method for JAVA class to achieve serialization is to implement the java.io.Serializable interface
In the Collection framework,
the difference between Comparable interface and Comparator interface 33, STRING and STRINGBUFFER should be realized .
Answer: The length of STRING is immutable, and the length of STRINGBUFFER is variable. If you often operate on the content of the string, especially when the content needs to be modified, then use StringBuffer. If you need String at the end, then use the toString() method of StringBuffer.
34. Talk about the difference between final, finally, finalize.
Answer: final -Modifier (keyword) If a class is declared as final, it means that it can no longer derive new subclasses and cannot be inherited as a parent class. Therefore, a class cannot be declared as both abstract and final. Declaring variables or methods as final ensures that they will not be changed during use. The variable declared as final must be given an initial value at the time of declaration, and can only be read in future references and cannot be modified. The method declared as final can also only be used,
and finally cannot be overloaded—the finally block is provided to perform any cleanup operations during exception handling. If an exception is thrown, then the matching catch clause will be executed, and then control will enter the finally block (if any)
finalize—the method name. Java technology allows the use of the finalize() method to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector when it determines that the object is not referenced. It is defined in the Object class, so all classes inherit it. Subclasses override the finalize() method to organize system resources or perform other cleanup tasks. The finalize() method is called on the object before the garbage collector deletes it.
35. What are the object-oriented features?
Answer: There are four main aspects:
1. Abstraction:
Abstraction is to ignore those aspects of a theme that are not related to the current goal in order to pay more attention to the aspects related to the current goal. The abstraction does not intend to understand all the issues, but only select some of them, without some details for the time being. Abstraction includes two aspects, one is process abstraction, and the other is data abstraction.
2. Inheritance:
Inheritance is a hierarchical model of connecting classes, and allows and encourages the reuse of classes. It provides a way to clearly express commonality. A new class of objects can be derived from an existing class. This process is called class inheritance. The new class inherits the characteristics of the original class, the new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class. A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make it more suitable for special needs.
3. Encapsulation:
Encapsulation is to surround the process and data, and the access to the data can only be through the defined interface. Object-oriented computing begins with the basic concept that the real world can be depicted as a series of fully autonomous, encapsulated objects that access other objects through a protected interface.
4. Polymorphism:
Polymorphism refers to allowing different types of objects to respond to the same message. Polymorphism includes parametric polymorphism and inclusion polymorphism. Polymorphic language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, and it solves the problem of the same name of application functions.
36. Is String the most basic data type?
Answer: The basic data types include byte, int, char, long, float, double, boolean and short.
The java.lang.String class is of final type, so this class cannot be inherited or modified. In order to improve efficiency and save space, we should use StringBuffer class
37, what is the difference between int and Integer
Answer: Java provides two different types: reference types and primitive types (or built-in types). Int is a primitive data type of java, and Integer is a package class provided by java for int. Java provides wrapper classes for each primitive type.
The primitive type encapsulation class, booleanBoolean, character, byteByte, shortShort, intInteger, longLong, floatFloat, doubleDouble
reference types and primitive types behave completely differently, and they have different semantics. Reference types and primitive types have different characteristics and usage. They include: size and speed issues, which type of data structure is stored in this type, and when the reference type and primitive type are used as instance data of a certain class, they are specified The default value. The default value of object reference instance variables is null, and the default values ​​of primitive type instance variables are related to their types.
38. What are the similarities and differences between runtime exceptions and general exceptions?
Answer: Exceptions indicate abnormal conditions that may occur during program operation , Runtime exception means an exception that may be encountered in the normal operation of the virtual machine, and is a common operating error. The java compiler requires that the method must declare to throw non-runtime exceptions that may occur, but it does not require that it must declare to throw uncaught runtime exceptions.
39. Tell me about the storage performance and characteristics of ArrayList, Vector, LinkedList.
A: ArrayList and Vector both use arrays to store data. The number of elements in this array is greater than the actual stored data in order to add and insert elements. They all allow direct indexing of elements by sequence number , But inserting elements involves memory operations such as array element movement, so index data is fast and inserting data is slow. Vector uses the synchronized method (thread safety), which is generally worse than ArrayList in performance, while LinkedList uses a doubly linked list to achieve storage, according to the sequence number Index data needs to be traversed forward or backward, but when inserting data, you only need to record the preceding and following items of this item, so the insertion speed is faster.
40. The difference between HashMap and Hashtable.
A: HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation). They have completed the Map interface. The main difference is that HashMap allows null (key) because it is not threaded. Security and efficiency may be higher than Hashtable.
HashMap allows null as the key or value of an entry, while Hashtable does not.
HashMap removed the contains method of Hashtable and changed it to containsvalue and containsKey. Because the contains method is easy to cause misunderstanding.
Hashtable inherits from the Dictionary class, and HashMap is an implementation of the Map interface introduced by Java 1.2.
The biggest difference is that the method of Hashtable is Synchronize, while HashMap is not. When multiple threads access Hashtable, you do not need to synchronize its methods yourself, and HashMap must provide external synchronization for it.
The hash/rehash algorithms used by Hashtable and HashMap are roughly the same, so there will be no big difference in performance.
41. What is the difference between heap and stack?
A: A stack is a linear collection. The operations of adding and deleting elements should be completed in the same paragraph. The stack is processed in a last-in, first-out manner. The heap is a constituent element of the stack
42, the similarities and differences between the Java interface and the C++ virtual class
Answer: Since Java does not support multiple inheritance, it is possible that a certain class or object needs to use methods or attributes in several classes or objects. The existing single inheritance mechanism cannot meet the requirements. Compared with inheritance, the interface has higher flexibility because there is no implementation code in the interface. When a class implements an interface, the class must implement all the methods and attributes in the interface, and the attributes in the interface are public static in the default state, and all methods are public by default. A class can implement multiple interfaces.
43. The simple principle and application of the exception handling mechanism in Java.
Answer: When the JAVA program violates the semantic rules of JAVA, the JAVA virtual machine will indicate the error as an exception. Violation of semantic rules includes two situations. One is the semantic check built into the JAVA library. For example, if the array subscript is out of bounds, IndexOutOfBoundsException will be thrown; NullPointerException will be thrown when accessing a null object. Another situation is that JAVA allows programmers to extend this semantic check. Programmers can create their own exceptions and freely choose when to use the throw keyword to raise exceptions. All exceptions are subclasses of java.lang.Thowable.
44. The advantages and principles of garbage collection. And consider two recycling mechanisms.
A: A significant feature of the Java language is the introduction of a garbage collection mechanism, which solves the most troublesome memory management problem for C++ programmers. It makes Java programmers no longer need to consider memory when writing programs. management. Due to a garbage collection mechanism, objects in Java no longer have the concept of "scope", only object references have "scope". Garbage collection can effectively prevent memory leaks and effectively use available memory. The garbage collector usually runs as a separate low-level thread. Under unpredictable circumstances, the objects in the memory heap that have died or have not been used for a long time are cleaned and recycled. The programmer cannot call the garbage collector in real time to Objects or all objects are garbage collected. The recycling mechanism includes generational copy garbage collection, marked garbage collection, and incremental garbage collection.
45. What are the collection classes you know? The main method?
Answer: The most commonly used collection classes are List and Map. Specific implementations of List include ArrayList and Vector, which are variable-size lists, which are more suitable for constructing, storing and manipulating element lists of any type of object. List is suitable for accessing elements by numerical index.
Map provides a more general element storage method. The Map collection class is used to store pairs of elements (called "keys" and "values"), where each key is mapped to a value.
46. ​​Describe the principle and mechanism of JVM loading class files?
Answer: The loading of classes in JVM is implemented by ClassLoader and its subclasses. Java ClassLoader is an important Java runtime system component. It is responsible for finding and loading the classes of the class files at runtime.


Answer: The methods of sorting are: insertion sort (direct insertion sort, Hill sort), exchange sort (bubble sort, quick sort), selection sort (direct selection sort, heap sort), merge sort, allocation sort (box sort, Radix sort)
pseudo code for quick sort.
//Use the quick sort method to sort
a[ 0 :n- 1 ]. Select an element from a[ 0 :n- 1] as the middle, which is the pivot point
to split the remaining elements into two segments left and right, making left The elements in are all less than or equal to the pivot, and the elements in right are greater than or equal to the pivot
. Use the quick sort method to sort left
recursively Use the quick sort method to sort right recursively
The result is left + middle + right
47, how about JAVA language For exception handling, what do the keywords: throws, throw, try, catch, and finally represent? Can an exception be thrown in a try block?
Answer: Java uses object-oriented methods to handle exceptions, classifies various exceptions, and provides a good interface. In Java, every exception is an object, which is an instance of the Throwable class or other subclasses. When an exception occurs in a method, an exception object is thrown. The object contains exception information. Calling the method of this object can catch the exception and handle it. Java's exception handling is implemented through five keywords: try, catch, throw, throws and finally. Under normal circumstances, try is used to execute a program. If an exception occurs, the system will throw an exception. At this time, you can catch it by its type, or finally by the default processor. To deal with.
Use try to specify a program that prevents all "exceptions". Immediately after the try program, a catch clause should be included to specify the type of "exception" you want to catch.
The throw statement is used to explicitly throw an "exception".
throws is used to indicate the various "exceptions" that a member function may throw.
Finally, to ensure that a piece of code is executed no matter what "exception" occurs.
You can write a try statement outside a member function call, and write another try statement inside the member function to protect other code. Whenever a try statement is encountered, the frame of the "exception" is placed on the stack until all the try statements are completed. If the next-level try statement does not handle a certain "exception", the stack will expand until it encounters a try statement that handles this "exception".
48. Can a ".java" source file include multiple classes (not inner classes)? What are the restrictions?
Answer: Yes. There must be only one class name that is the same as the file name.
49. How many types of streams are there in java? JDK provides some abstract classes for each type of stream for inheritance. Please tell us which classes they are?
Answer: byte stream, character stream. The byte stream is inherited from InputStream OutputStream, and the character stream is inherited from InputStreamReader OutputStreamWriter. There are many other streams in the java.io package, mainly to improve performance and ease of use.
50. Will there be a memory leak in java? Please describe briefly.
Answer: Yes. There may be memory leaks when you implement the heaped data structure yourself, see effective java.
51. What is the mechanism for achieving polymorphism in java?
Answer: Method Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of polymorphism between a parent class and a subclass, and overloading is a manifestation of polymorphism in a class.
52. What is the basic principle of the garbage collector? Can the garbage collector reclaim memory immediately? Is there any way to actively notify the virtual machine to perform garbage collection?
A: For GC, when the programmer creates an object, the GC starts to monitor the address, size, and usage of the object. Generally, the GC uses a directed graph to record and manage all objects in the heap. In this way, determine which objects are "reachable" and which objects are "unreachable". When the GC determines that some objects are "unreachable", the GC is responsible for reclaiming these memory spaces. can. The programmer can manually execute System.gc() to notify the GC to run, but the Java language specification does not guarantee that the GC will be executed.
53. What is the difference between static variables and instance variables?
Answer: static i = 10; //constant class A a; ai =10;//variable
54. What is java serialization and how to realize java serialization?
Answer: Serialization is a mechanism for processing object streams. The so-called object stream is to stream the content of objects. You can read and write the streamed objects, and you can also transfer the streamed objects between networks. Serialization is to solve the problems caused by reading and writing the object stream.
The realization of serialization: The class that needs to be serialized implements the Serializable interface. The interface has no methods that need to be implemented. The implements Serializable is just to mark that the object can be serialized, and then use an output stream (such as: FileOutputStream) to construct An ObjectOutputStream (object stream) object, and then use the writeObject(Object obj) method of the ObjectOutputStream object to write out the object whose parameter is obj (that is, save its state), and use the input stream to restore it.
55. Is it possible to call a non-static method from within a static method?
Answer: No, if it contains the method() of the object; the object initialization is not guaranteed.
56. When writing the clone() method, there is usually a line of code. What is it?
Answer: Clone has a default behavior, super.clone(); he is responsible for generating the correct size of space and copying it bit by bit.
57. How to break out of the current multiple nested loops in JAVA?
Answer: Use break; return method.
58. What are the characteristics of the three interfaces of List, Map, and Set when accessing elements?
Answer: List holds elements in a specific order and can have duplicate elements. Set cannot have duplicate elements, internal sorting. Map stores the key-value value, and the value can be multiple values.
59. Name some commonly used classes, packages, and interfaces, please cite 5 each.
Answer: Commonly used classes: BufferedReader BufferedWriter FileReader FileWirter String Integer
Commonly used packages: java.lang java.awt java.io java.util java.sql
Commonly used interface: Remote List Map Document NodeList

Summarized some interview questions for 2020. The modules included in this interview question are divided into 19 modules, namely: Java basics, container, multithreading, reflection, object copy, JavaWeb exception, network, design pattern, Spring/SpringMVC , SpringBoot/SpringCloud, Hibernate, MyBatis, RabbitMQ, Kafka, Zookeeper, MySQL, Redis, JVM.

Obtain the following information: [ click here, secret code CSDN! ! !
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_47345084/article/details/112469903