Last time, WE sorted out the Internet technology interview questions and answer skills summary, I believe that everyone after reading the harvest are particularly great. So today I sorted out this set of Java easy to mistake interview questions, to share with friends.

First, easy to wrong interview questions

1. Differences between final, finally and Finalize

(1) Final: used to declare properties, methods, and classes, respectively, indicating that properties are immutable, methods cannot be overridden, and modified classes cannot be inherited.

② finally: Part of the exception handling statement structure that always executes.

(3) A method of Finalize: Object class that will call the method of the Object to be collected when the garbage collector executes it, and can override the method.

2. The difference between interfaces and abstract classes

(1) Similarities:

① Neither interfaces nor abstract classes can be instantiated. They are at the top of the inheritance tree and are intended to be implemented or inherited by other classes.

② You can use abstract classes and interfaces as reference types

③ Both excuses and abstract classes contain abstract methods

④ If a class inherits an abstract class or implements an interface, all its abstract methods must be implemented; otherwise, the class still needs to be declared as an abstract class

(2) Differences

① A class can implement multiple interfaces, but can inherit only one abstract class

(2) Constructors cannot be defined in interfaces, but can be defined in abstract classes. The constructor of an abstract class is not used to create an object, but to let subclass calls complete the initialization of the abstract class.

(3) All the methods in the interface are abstract methods. Abstract classes can have abstract methods and concrete methods.

(4) All members of an interface are public. Members of an abstract class can be private, default, protected, or public

(5) The member variables defined in the interface are actually always on. Member variables can be defined in abstract classes.

(6) An interface can not have static methods, but an abstract class can contain static methods; (Static methods can be used in interfaces after JDK1.8)

3. The difference between & and &&

(1) & : bitwise and, regardless of whether the left side is true or false, the right side will be calculated, not short circuit

(2) && : logic and, only look at the left result, if the left is true, the right will participate in the operation, if the left is false, the right will not participate in the operation, there is a short circuit function

4. The difference between Overloading and Overriding

(1) Overloading

① To see whether it is overloaded, one is to see the same method name, two is to see whether the parameters are the same. Methods with the same name and different parameters are overloaded, otherwise not.

② Method overloading is a way for classes to handle different types of data in a uniform way. Multiple functions with the same name exist at the same time with different parameter types. Overloading is a manifestation of polymorphism in a class.

(3) Java method overloading is the ability to create multiple methods in a class with the same name, but with different parameters and different definitions. Methods are called by passing them different numbers and types of arguments to decide which method to use. This is called polymorphism.

④ When overloaded, the method name is the same, but the parameter type and number are different. The return value type can be the same or different. Overloaded functions cannot be distinguished by return types.

(2) Overriding:

① Polymorphism between the parent class and the subclass, redefine the function of the parent class. If a method defined in a subclass has the same name and parameters as its parent, the method is said to be overridden. In Java, subclasses can inherit methods from their parent class. You don’t need to rewrite the same method. But sometimes a subclass doesn’t want to inherit the parent class’s methods exactly, but rather wants to modify them. This is called method overwriting. Method override is also called method override.

② If a method in a subclass has the same method name, return type, and parameter list as a method in the parent class, the new method overrides the original method. If you want a method existing in the parent class, you can use the super keyword, which references the current parent class.

③ The access modification permission of subclass functions cannot be less than that of the parent class.

④ Rewriting should follow the principle of “two with two small and one big” :

  • Identical: The method overridden by a subclass must have the same name and argument list as the method overridden by its parent class
  • Two minor: the return value type of the subclass is less than or equal to the return value type of the parent class, and the exception thrown by the subclass is less than or equal to the exception thrown by the parent class
  • One: methods overridden by subclasses must use more access than methods overridden by their parent class

Note: Subclasses cannot override methods declared as private permissions in their parent classes

Conclusion:

Overwriting is writing on one side, overloading is one more

Overwrite: the parent class has one, and the child class writes one

Rewrite: own class inside have, feel enough to write another

5. The difference between equals and equals

① = = can compare both base and reference types. Values are compared for primitive types, and memory addresses are compared for reference types.

Equals is a method that belongs to the Java Object and defaults to “= =” if the method is not overridden; It is common to override equals *** to compare the equality of corresponding attributes in a class.

6. Difference between Error and exception

(1) Similarities

  • Both the Error and Exception classes have Throwable parents

(2) Differences

  • The Error class generally refers to serious errors that cannot be resolved by the Java virtual machine, such as system crashes, virtual machine errors, insufficient memory, and method call stack overflow.
  • The Exception class represents other problems caused by programming errors or accidental external factors that a program can handle, catch, and fix.

Throw throws

(1) Throw:

  • A throw statement is used in a method body to indicate that an exception is thrown and is handled by a statement in the method body
  • A throw is an action that specifically throws an exception. It throws an exception instance.

(2) throws:

  • Throws statement is behind the method statement, said if thrown a bed, by the caller of the method for exception handling.
  • Throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws throws
  • Throws represents a possibility of an exception that is not necessarily expected.

8, StringBuilder, StringBuffer

(1) A String is a final, immutable sequence of characters. Once a String has been created, the sequence of characters contained in that String cannot be changed until the object is destroyed. That is:

String a="Zhang"; a="123";// Print 123
System.out.println(a);
Copy the code

As you can see, the next assignment to A does not reassign the original instance object in the heap, but generates a new instance object that points to the string 456. A refers to the newly produced instance object. The previous instance object still exists and will be garbage collected if it is not referenced again.

(2) The StringBuilder class also stands for mutable string objects. In fact, StringBudiler is basically similar to StringBuffer except that StringBuffer is thread-safe, while StringBuilder does not implement thread-safe features and thus performs slightly better

StingBuffer represents a string with a variable sequence of characters. When a StringBuffer is created, Append (), Insert (), reverse (), setCharAt (), setLength (), and other methods provided by StringBuffer can modify the character sequence of this string object. Once the StringBuffer spawns the final desired String, its toString () method can be called to convert it to a String object.

StringBuffer b= new StringBuffer("123");
b.append("456");
//b The output is 123456
System.out.println(b);
Copy the code

  • A StringBuffer object is a variable string with a sequence of I characters that does not regenerate an object; And you can concatenate new strings in the original object.

Summary: String has final, immutable character sequences; StringBuffer mutable character sequences, which are inefficient but thread-safe; StringBuilder variable character sequences are efficient but not thread-safe.

9. How is StringBuffer thread safe

The StringBuffer class implements the following methods:

Thus, methods in the StringBuffer class add the synchronized keyword, which adds a lock to the method to keep it thread-safe.

The improvement of Java9

  • Java9 improves the implementation of strings, including String, StringBuffer, and StringBuilder. Prior to Java9, strings used the char[] array to hold characters, each character of the string was 2 bytes; Java9 strings use a byte[] array with an encoding-Flag field to hold characters, so each character of the string is only 1 byte. So Java9 strings are much more space-efficient, and the string functionality methods are not affected.

10. Differences between ArrayList and LinkedList

Neither thread is safe, but it is more efficient than Vector

  • The underlying ArrayList is stored as an array, and randomly accessing the elements in the collection is faster than LinkedList because LinkedList moves the pointer
  • LinkedList is an internal list of the data in the universal village collection, which accesses the elements of the collection slowly, but adds and deletes them faster than ArrayLIst because ArrayLIst moves the data

The difference between Equals and HashCode

  • If two objects are equal to equals, their Hashcode must be equal.
  • If two objects are not equal to equals, then it is possible that their Hashcode is equal
  • If two objects have hashcode equal, their equals is not necessarily equal
  • If two objects hachcode is not equal, their equals is not necessarily equal

Access control permissions for Java class members

Public > protected > default > private

13. Differences between Hashtable and HashMap

(1) Similarities

  • Hashtable and Hashmap are both subinterfaces of maps

(2) Differences

  • Hashtable is thread-safe and does not support null keys and values. Keys cannot be repeated, but values can be repeated. Key () and value cannot be null
  • The Hashmap thread is unsafe because it supports null keys and values. The key cannot be repeated, but the value can be repeated and the key and value can be null

14, Java Object class common methods

(1) the clone ();

  • Creates and returns a copy of this object.

(2) the equals ();

  • Indicates whether some other object is “equal” to this object.

(3) the finalize ();

  • This method is called by the object’s garbage collector when the garbage collector determines that no reference to the object exists

(4) getClass ();

  • Returns the runtime class of this Object

(5) notify () and notifyAll ();

  • Wake up a single thread notify() waiting on this object’s monitor;
  • NotifyAll () wakes up all threads waiting on the monitor of this object;

(6) the toString ();

  • Returns a string representation of the object.

The difference between Java compile-time exception and runtime exception, and several runtime exceptions

(1) Compile-time exceptions

  • Failed at compile time:
  • A compilation exception occurred when assigning a String to an array of int

(2) Runtime exception

  • No exception at compile time, but an error is reported at run time (array out-of-bounds exception and null pointer exception) :

Common exceptions of type RuntimeException

  • ArithmeticException Mathematical calculation exception
  • NullPointerException NullPointerException
  • NegativeArraySizeException negative abnormal length
  • ClssCastException type casting exception
  • SecurityException Exception that violates security rules
  • Abnormal ArrayIndexOutOfBoundsException an array

Too many different interview questions to write an essay? My question is not answered in this article? Don’t worry, I sorted out the interview questions of many Internet companies, the interview materials of many big names, as well as Java learning materials, and more interview skills. Friends in need can click into access. Code word: nuggets. Let’s learn!

16. Talk about the concept of reflection in Java and its advantages and disadvantages

Reflection refers to a program that analyzes the capabilities of a class at runtime. First of all, we need to know that under normal circumstances, if we use a class, we must go through several steps:

  • Use important to import the package where the class resides.
  • Class objects are instantiated by the keyword new
  • To generate an object, use object. Property “to call a property in a class
  • Call a method in a class through object.method ()

In reflection, using a class does not require importing the package in which the class resides, as long as the class’s full path is known. Reflection does not need to have an explicit type object; all objects are represented using Objiect. Methods in a class can be invoked directly through a mixture of Object and reflection mechanisms. Simply put, reflection is a mechanism by which a program can retrieve information about itself as it runs.

In Java, all information about a class can be retrieved by reflection, given the name of the class.

(1) Why use reflection? How does it work in real compilation?

  • Static compilation: The type is determined at compile time and the bound object passes.
  • Dynamic compilation: Determine the type and bind the object at run time. Dynamic compilation maximizes the flexibility of Java, enables the application of polymorphism, and reduces the coupling between classes.

(2) Advantages and disadvantages of reflection

  • Advantages: Can achieve dynamic object creation and compilation, reflecting a great deal of flexibility
  • Disadvantages: Performance is affected. Using reflection is basically an interpretation of operations where we tell the JVM what we want to do and it meets our needs. This type of operation is always slower than performing the same operation directly.

It can be seen from the question:

Filed and Method Constructor are used to describe the class’s and, methods and constructors respectively. The Class is in the java.lang. Reflet package and the Class is in the java.lang

② Is correct. Dynamic proxy implements the interface, and then we can access all the information of the class through the class path. (See the dynamic proxy principle below);

The common functions of reflection are: dynamically loading a class, dynamically fetching information about a class (attributes, methods, constructors);

Dynamically constructed objects; Dynamically invoke arbitrary methods and constructors of classes and objects;

Dynamically invoke and process properties;

Get generic information; Deal with annotations

Reflection can get all information about a class through the path of the class.

Reflection can dynamically call any method of a class or object

⑤ The disadvantage of reflection is that it has an impact on performance

⑥ Reflection will reduce efficiency, but set to prohibit safety checks, to improve the speed of reflection;

Principle of dynamic proxy

Since interfaces can be implemented dynamically through the above reflection, we are talking about dynamic proxies. Before we understand dynamic proxies, we need to understand what proxies are.

What is Proxy mode: a Proxy object is provided to a target object and the reference to the target object is controlled by the Proxy object

There are two scenarios used:

  • The client does not want to directly access the real object, or there is a technical barrier to access the real object, so the proxy object as a bridge to complete the profile access;
  • Enhance a method without changing the target object method.

Agents are divided into static agents and dynamic agents

① Static proxy

  • What if you want to add functionality without breaking the interface implementation classes? Can lead to dynamic proxy, in fact, is to create an implementation of the interface class, and internal maintenance of an interface member variables point to the object of the original interface, through the proxy object method internal call the original interface instance method;
  • Create an interface with a method inside it.
public interface IDveloper {
public void writeCode(a);
}
Copy the code
public class Developer  implements  IDveloper{
private  String name;
public Developer(String name){
this.name = name;
}
@Override
public void writeCode(a) {
System.out.print("Developer " +name + " wrters code"); }}Copy the code
public class DeveloperTest {
public static void main(String[] args) {
IDveloper wrto = new Developer("wtao"); wrto.writeCode(); }}Copy the code

  • Advantages of static proxies:

Easy to understand and implement. The relationship between proxy classes and real classes is determined statically at compile time and has no overhead at execution compared to dynamic proxies

  • Disadvantages of static proxies:

When interfaces and proxies are 1 to 1, multiple interfaces need multiple proxies or methods in the interface, so it is necessary to create multiple proxy classes or implement methods in the interface, which is tedious

② Dynamic proxy

Static proxies are limited by the implementation of the interface. Dynamic proxy is to dynamically obtain the type of the abstract interface through reflection, so as to obtain the relevant features for proxy.

There are three steps to using dynamic proxies:

  • To create a proxy execution class, you must implement the InvocationHandler interface, ostensibly a dynamic proxy execution class.
  • The invoke (Object[] Proxy,Method,Object[] args) Method of the InvocationHandler interface.
  • NewProxylnstance static method proxy. newProxylnstance static method proxyl.newProxylnstance static method proxyl.newProxylnstance static method proxyl.newProxylnstance static method proxyl.newProxylnstance

The code is as follows:

Method to get a proxy class object, passing in three arguments: the first argument is the classloader; The second parameter is the interface type of the delegate class. The proxy class returns the type of the same implementation interface, keeping the type returned by the proxy class.

The third parameter is the proxy class itself, which tells the proxy class which invoke method should be invoked when the proxy class encounters a primitive method.

You can also define a proxy execution class by writing a public method directly into the class to get the proxy class object

The code is as follows:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DeveloperProxy implements InvocationHandler {
private  Object target; // The proxied class
public Object getProxyInstance(Object target){
this.target = target;
Object object = Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
return  object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.print("Still up? ");
Object result = method.invoke(target,args);
System.out.print("You're still up? ");
returnresult; }}Copy the code
public class DeveloperTest {
public static void main(String[] args) {
// Create the proxied object
IDveloper wtao = new Developer("wato");
// Create the object to be executed by the agent
DeveloperProxy jdkProxy = new DeveloperProxy();
// Give the proxy object to the proxy class for maintenance and get the proxy objectIDveloper WtaoProxy = (IDveloper) jdkProxy.getProxyInstance(wtao); WtaoProxy.writeCode(); }}Copy the code

③ The difference between static proxy class and dynamic proxy class

  • A static proxy class needs to write its own proxy class and implement the target methods one by one, and the proxy class must implement the same interface as the target object.
  • The dynamic proxy does not need to implement the proxy class itself. It uses the JDKAPI to dynamically build the proxy object in memory by passing in the proxied class and implementing all the target methods by default.

Two, write at the end

The above is to sort out some of the easy error in the interview of Java technology post, limited by the level, I sort out the inevitable shortage, if there is improper, or can have a supplement, welcome to correct!

Learning is a lifelong process. The rapid technological change brought about by the rapidly changing times requires that each of us keep learning.

This article is just a drop in the ocean, the original idea is also hope to be helpful to everyone.

Life is limited, and learning is endless, I hope we can continue to learn, continuous progress, to become a better themselves. Thank you for watching!

Finally, don’t forget to “like”, “save” and “forward” (hint ~ hint () +). Thank you!