See what HOLE I buried in the Object generic method

Did you use equals? Look at this problem and tell us what is the difference between equals method before and after?

It makes no difference.

False. Beginners or people who type too little code can make this mistake.

Test1 will directly raise null pointer exceptions. Null. Equals How can a null pointer have a method right,

* * development: = = = = = = = = = = = = = = = = I really shouldn’t,

Tell me the difference between equlas and ==

The equals method compares the contents of strings for equality, while == compares object addresses.

That’s also true, but we’d like to hear a more professional answer like:

First in Java data types can be divided into two kinds, one kind is the basic data types, also known as the primitive data types, such as byte, short, char, int, long, float, double, Boolean comparison between them, the double equal sign (= =), and compare their values.

The other is compound data types, including classes, which when compared with (==) compare their locations in memory, so unless they are the same new object, the result of the comparison is true, the result of the comparison is false.

All classes in JAVA inherit from the base class Object. The equals method is defined in the base class Object. The initial behavior of this method is to compare the memory addresses of objects, but in some libraries this method is overridden. Among these classes, equals (String,Integer,Date) has its own implementation, rather than comparing the addresses of the classes in the heap.

This answer shows both professional and awesome, but also the atmosphere on the grade, you learn to waste?

Talk about understanding the hashCode and equals methods

When asked this question, a candidate can usually answer:

If two objects are equal to their equals methods, they must have the same hashCode;

If two objects have the same hashCode, their equals() methods are not necessarily equal.

The return value of hashCode() of two objects is equal, but the return value of hashCode() of two objects is not equal.

So what does hashCode do? Why is it so normative

Basically beginners or fresh graduates in this step is stuck by me, prevaricant answers can not much, basically are here to drop marks, because the above standard answer baidu a large number of, but have a deep understanding of the role of hashCode is very few, this question can also see a person’s professional level.

The correct answer is:

The purpose of hashCode is to improve the efficiency of lookups in the hash structure. Of course, the performance of hash storage can only be improved if the hashCode of each Object is as different as possible, which is why all objects provide different hash codes by default.

Here’s an example:

In the case of a HashSet, to ensure that the elements are not duplicated, you need to call the equals method of the object to compare them once. However, if the structure contains many elements, such as 5000 times, you need to compare 5000 times each time you add elements without hashCode, which is different if you have hashCode. The hashCode method is called when a collection is about to add a new element, so that the address of the element can be located without multiple judgments.

What is the result of the clone method?

Every time you ask this question, most people say 2, and a few people say 1.

All wrong. The correct answer is to report an error

Why is that? Since clone is the protect method of Object, subclasses are required to override the Clone method and implement the Cloneable interface.

So the question is, right? What about the Cloneable interface? Is it 2 or 1?

This is another pit I dug to test candidates’ understanding of shallow and deep copies

The final result is actually 2, because the clone copy is a shallow copy, and the reference type of the copied object and the original object are still the same object.

If you want to implement deep copy, you need to rewrite it yourself within the Clone method.

** In enterprise development, we generally do not allow clone method to do copy directly, which may lead to the risk of throwing exceptions and requires type conversion. If I review this code, I will tell my colleagues directly: In Effective Java, it is better not to use Clone (), we can use copy constructor or copy factory to copy an object, such as this

Conclusion: We all know that Java is Object oriented programming. In fact, my understanding is that it is necessary for a beginner programmer to properly use and understand the principles of Equals and hashCode, and the understanding of shallow copy and deep copy is also basic among the basics. I hope to finish reading this series. You can know, the next time you meet this kind of interview question, just blow.

See what I’ve done with abstract classes and interfaces

Test the candidate’s coding skills and explain your understanding of abstract classes

Abstract classes and methods are both declared using the abstract keyword. If a class contains abstract methods, the class must be declared as abstract, and the biggest difference between abstract classes and ordinary classes is that abstract classes cannot be instantiated, but can only be inherited.

Bingo, the answer is right, but it’s not good enough

The above is the standard answer, which can be found in any Java book, but can be added to your understanding of the application, which can reflect your level of coding, I add my ideal answer:

Abstract classes can implement code reuse, the template method design pattern is a typical application of the abstract class, for example we are going to have the same game all the activities of initialization, but initialization time need according to different activities for different function open judgment, then it is possible to define the base class for an activity, make it an abstract methods to estimate the open function Let all activities inherit from the base class, and then turn on judgment in subclass override.

Add your own understanding of the application, which can fully reflect your expertise, and the interviewer will certainly listen to the heart of a hell of a cow.

Go ahead and test the candidate’s coding skills and tell me what you understand about interfaces

An interface is an extension of an abstract class, and all methods in the interface must be abstract. In fact, the method definition in the interface defaults to the public abstract type and the member variable type in the interface defaults to the public Static final type.

You know, this is another standard answer, in fact, not good enough, you can add the following

Starting with Java8, interfaces can also have default method implementations. Why did the Java team support this?

In fact, in Java subsoil years old driver interface no default implementation actually is, maintenance cost is too high, you think about it, if you there are now 100 class implements an interface, and at the same time, need to give interfaces, a new method, yao Java8 before don’t allow to interface with the default implementation, so you have to change to 100 classes, What the hell is that supposed to do to somebody?

Truth: be able to tell the understanding of abstract class and interface application of candidates is not much, basically out of my heart is to blow cow force, capital, because it fully embodies a developer to code in terms of thinking, you don’t know any think and write code that a clean and tidy, rather than simply realize the function of programmers, supervisor will be more like it!!!!!!

A really straightforward answer is the difference between an abstract class and an interface

  • Abstract classes can have constructors; interfaces cannot.

  • Abstract classes can have ordinary member variables, but interfaces do not

  • An abstract class can contain non-abstract ordinary methods, and all methods in an interface must be abstract, with no non-abstract ordinary methods.

  • Abstract classes can contain static methods, but interfaces cannot

  • Abstract classes and interfaces can contain static member variables. The access type of static member variables in an abstract class can be any, but the variables defined in the interface can only be of the public static final type, which is the default type.

  • A class can implement multiple interfaces, but can only inherit from one abstract class.

This is the standard answer, but we are hope can be in response to the difference between the interviewer expand their do answer, when will the understanding of the interface and abstract class above all say it again, not as an endorsement of answer, remember, answer questions, meet understand knowledge, try to do to expand, combined with their own understanding, one is to show the interviewer you professional, Second, you can procrastinate and try to avoid letting the interviewer think of more difficult questions to trap you

Summary: see here, estimate a lot of people to abstract class and interface are sniffed at, are casually can say the answer, but, you think we just want to listen to your endorsement type of answer, wrong, we want to know is behind your expansion and understanding, this can reflect your coding ability and professional.

See what HOLE I put in rewriting and reloading

Take a look at the following question, and tell us what the result is.

This problem is simply, many years ago WHEN I came to apply for division I also met this problem, to tell the truth, fresh students and primary around this problem, now directly to everyone bright card:

To show you how to understand this kind of problem, you need to understand the following principles:

When the JVM calls a method, it first looks for the corresponding method in the class, and if not in the parent class to see if it inherits from the parent class.

What if not? The JVM then transforms the argument into a parent class to see if there is a corresponding method.

In general, the priority of method calls is as follows:

  • this.func(this)
  • super.func(this)
  • this.func(super)
  • super.func(super)

Just remember the process.

Start digging holes to see if the following is a method overload?

class TestMain {

    public int show(int x) {
        return x;
    }

    public void show(int x) { System.out.println(x); }}Copy the code

I interviewed most of the primary or this year will answer is, have to say that this problem is too pit, not joking, you see that pile of people buried by this problem inside have me.

Remember, overloading is defined as a method in the same class that has the same name as an existing method and has at least one different parameter type, number, or order. There’s no return value in this sentence, so it’s not an overload at all if the return value is different and everything else is the same.

Of course, IDEA is directly prompt error, this is why I did not cut idea source out for you to see the reason, a look at the red you know there is a problem. But again, this does not mean that you can not understand what IDEA can detect, which is the basis.

Conclusion: to be honest, in the pen test overloading and rewrite the two problem is all too common, ninety percent of the fresh graduates or primary development have been pit, so remember to read this article collection, did you watch the not remember, but remember before the interview to see it again, but this relationship to your offer on the glittering number limit

See what I’ve done with reflection

Finally reflection, which our interviewers really liked and used to weed out a lot of API engineers

Know anything about reflection? What is reflection?

At runtime, Java reflection, can obtain any kind of name, package information, all of the properties, methods, annotations, type, class loader, realistic interface, etc., and you can call any method and instantiate any of a class alone, through reflection we can realize dynamic assembly, reduce the coupling and realize the dynamic proxy of code, However, overuse of reflection can severely consume system resources.

The above answer is pretty standard, but I dig a little deeper. You mentioned the function of reflection in your previous answer. Where is the reflection mechanism used?

There are many examples, such as:

  • In JDBC, reflection is used to load the database driver dynamically.
  • Sevlet’s service methods are invoked in the Web server using reflection.
  • There are many frameworks that use reflection, inject properties, and call methods, such as Spring.

Basically answer a few can, here because not to the framework module, so not Spring, JDBC and other source code for deep digging, generally is the basis of the topic finished, began to dig the use of the framework and the understanding of the source code.

Keep digging, our interviewers love detail, so make sure you know everything you’re talking about, otherwise hey, hey, hey, you were talking about dynamic proxy, what do you understand about dynamic proxy, and what does it do

Dynamic proxies are simply run-time dynamically generated proxy classes. Applications for dynamic proxies include Spring AOP, back-end mock testing frameworks, RPC, Java annotation object acquisition, and more.

How to implement dynamic proxy?

At present, dynamic proxy can provide two kinds, divided into JDK native dynamic proxy and CGLIB dynamic proxy;

Native JDK dynamic proxies are implemented based on the interface, and additional is based on the inherited current class subclass implementation, when the target class have interface will use the JDK dynamic proxy, because actually the JDK dynamic proxy to agent a class that is no interface, because the JDK dynamic proxy is the use of reflection mechanism to generate an implementation of anonymous proxy interface classes;

CGLIB implements proxying for classes, essentially generating a subclass of a given class and overriding its methods.

You mentioned above that Spring AOP is useful for dynamic proxies. What is the way AOP is used?

Most will answer JDK native dynamic proxies, and a few will answer CGLIB.

But in fact, both are wrong, this is I dug a good pit, too many candidates only know AOP with a dynamic proxy, but can fully answer what kind of is very few, after all, only read the source of talent to answer this question, generally able to answer, I will add extra points

The actual answer is: JDK dynamic proxies are used by default in Spring, and are converted to CGLIB proxies unless the target class does not implement an interface. < AOP :aspectj-autoproxy proxy-target-class=”true” />

In SpringBoot, however, the CGLIB agent has been used by default since 2.0. **

Talk about the pros and cons of reflection

Advantages: Dynamic execution, dynamically executing methods and accessing properties according to business functions during runtime, maximizes the flexibility of Java. Disadvantages: Performance impact, such operations are always slower than directly executing Java code.

Performance is affected. How can I solve this problem?

Basically, a lot of candidates can’t answer at this point. I’ve seen too many people talk about performance at the beginning, but when it comes to how to solve it, they basically falter and fail to answer.

Remember, if you’re talking about performance, think about how you’re going to answer optimization questions, otherwise you’re shooting yourself in the foot.

In fact, it can be answered from the following aspects:

  • When the system starts up, the reflected metadata is saved and used only by calling it from memory.

  • Try to use the higher JDK because the higher version of the virtual machine will be optimized for more frequently executed methods, such as using jit technology, while the lower version will not be implemented at that time.

  • Consider using high-performance reflection libraries, some of which are available in Spring.

Conclusion: It is recommended to play with reflection, not just API calls, for our interviewers, familiar with and understanding reflection is a prerequisite for an intermediate programmer.

Look at the hole I dug with exceptions and annotations

As a Javer, you should be familiar with Error and Exception

Currently, there are two types of classes that can be thrown as exceptions: Error and Exception.

Error is an Error that cannot be handled by the JVM.

  • Exception: use try… catch… Statements are caught and processed, and can be recovered from exceptions;
  • Unchecked Exception: a program runtime error, for example, dividing by 0 causes the Arithmetic Exception to crash and cannot be recovered.

What are annotations? And what does it do

Annotations provide an annotation-like mechanism for associating any information or data with a class, method, or member variable.

Annontation is used like a modifier in declarations of packages, types, constructors, methods, member variables, parameters, and local variables.

Annotations can be used for many purposes. Here are two common examples:

  • Generate documentation. This is the most common and earliest annotation provided in Java, and the system will scan the class that uses the annotation and generate a document based on the annotation information.
  • Format checking is done at compile time. If @Override comes before a method, it will be checked at compile time if your method does not override a superclass method.

Java.lang. Annotation provides four meta-annotations. What are they? What’s the use?

There are several meta annotations in JAVA:

  • @target: The Target of the annotation
  • @Retention: The life cycle of annotations
  • Documented: Whether an annotation should be included in a JavaDoc document
  • @Inherited: Whether a child class is allowed to inherit this annotation

Yes, these meta annotations are all too common, but few people actually use them well.

What are the targets of @target?

There are multiple Target types for @target.

Basically just a few answers, but remember, the TYPE above refers to the class, meaning that this annotation applies to the class.

What are the life cycles of @Retention annotations? What’s the difference?

The life cycle of @Retention annotations can be divided into the following:

  • Etentionpolicy. SOURCE: The current annotation is visible at compile time and is not written to the class file
  • Retentionpolicy. CLASS: discarded during CLASS loading and written to the CLASS file
  • Retentionpolicy. RUNTIME: permanently saved and can be retrieved by reflection

The difference is:

The first is visible only at compile time and then discarded.

The second type is compiled by the compiler into a class file. Classes, methods, and even fields have property tables. The JAVA virtual machine also defines several annotation property tables to store annotation information, but this visibility cannot be carried to the method area and is discarded when the class is loaded.

And the third is the visibility of permanence, which can be reflected, which is basically the dominant one.

For annotating the lifecycle of the understanding can avoid some holes, or the same sentence, basically annotating this can answer the more fluent, the explanation is played with the component or read the source code, because for developing a component, annotations are too common.

The parent class uses an annotation. Does a subclass inherit an annotation from the parent class? If not, how do you implement this process?

This is a question that very few people will answer, because this @Inherited meta-annotation is very new to you.

When using @inherited on an annotation, this annotation will be Inherited by the child classes. Note that this annotation only applies to the class. Members and methods are not affected by this annotation

Therefore, if you want a child class to inherit the annotations from its parent, you need to give the annotations a meta-annotation @Inherited.

Development: Generally, annotations are not used in the initial development, because annotations are mostly used to write components. Our project team likes to customize some annotations to implement components, because it is too comfortable to use.

Error and Exception are the basic questions you will be asked about in the following section:

The last

Thank you for your support. Thank you for your support.

Java foundation series is almost the same, to tell the truth, these two articles pit point, as long as you remember, Java foundation this basically no problem.

Follow-up arrangements:

  • 【 Good interview 】Java collection series

  • [good interview] Java position often test algorithm

  • Caffeine source code

Interested in my attention a wave, Java interviewers take you across one interview pit, guaranteed not to lose.

Public number: Rice talk about programming

Original link: mp.weixin.qq.com/s/F73r_f5Yc…

Thank you for your support 👍👍👍!