java interview basic questions

 

1. Can a ".java" source file include multiple classes (not inner classes)? What are the restrictions?

  There can be multiple classes, but there can only be one public class, and the public class name must be the same as the file name.

2. Does Java have goto?

Reserved word in java, not used in java now.

3. Talk about the difference between & and &&.

Both & and && can be used as logical AND operators, representing logical AND (and). When the results of the expressions on both sides of the operator are true, the entire operation result is true. Otherwise, as long as one of the expressions is false, then The result is false.

&& also has the ability to short-circuit, that is, if the first expression is false, the second expression is no longer evaluated , for example, for if(str != null && !str.equals("")) expression, when When str is null, the following expression will not be executed, so NullPointerException will not occur. If && is changed to &, NullPointerException will be thrown. If(x==33 & ++y>0) y will grow, If(x==33 && ++y>0) will not grow

& can also be used as a bitwise operator. When the expressions on both sides of the & operator are not of boolean type, & represents a bitwise AND operation . We usually use 0x0f to perform & operation with an integer to get the lowest 4 bits of the integer. Bits, for example, 0x31 & 0x0f result in 0x01.

4. Can the switch statement work on byte, long, or String?

In switch(expr1), expr1 can only be an integer expression or an enumeration constant, and the integer expression can be an int basic type or an Integer wrapper type . Since byte, short, and char can all be implicitly converted to int, so, These types as well as these types of wrapper types are also possible. Obviously, neither the long nor the String type conforms to the switch syntax, and cannot be implicitly converted to an int type, so they cannot be used in switch statements.

5. short s1 = 1; s1 = s1 + 1; what's wrong? short s1 = 1; s1 += 1; what's wrong?

For short s1 = 1; s1 = s1 + 1; Since the type of the expression is automatically promoted during the operation of s1+1, the result is an int type, and when it is assigned to a short type s1, the compiler will report an error that the type needs to be cast .

For short s1 = 1; s1 += 1; Since += is an operator specified by the java language, the java compiler will treat it specially, so it can be compiled correctly. 

6. Can a Chinese character be stored in a char variable? Why?

The char type variable is used to store Unicode-encoded characters. The unicode-encoded character set contains Chinese characters, so Chinese characters can of course be stored in the char type variable. However, if a special Chinese character is not included in the unicode encoding character set, then this special Chinese character cannot be stored in this char variable . Supplementary note: unicode encoding occupies two bytes, so variables of type char also occupy two bytes.

7. When using the final keyword to modify a variable, is the reference immutable or the referenced object immutable?

When the final keyword is used to modify a variable, it means that the reference variable cannot be changed, and the content of the object pointed to by the reference variable can still be changed .

For example, for the following statement:

final StringBuffer a=new StringBuffer("immutable");
Executing the following statement will report a compile-time error:

a=new StringBuffer("");
However, the following statement can be compiled:

a.append(" broken!");

When someone defines the parameters of a method, they may want to use the following form to prevent the method from modifying the incoming parameter object:

public void method(final  StringBuffer  param){

}

In fact, this is impossible, and the following code can still be added inside the method to modify the parameter object:

param.append("a");

8. What is the difference between "==" and equals methods?

The "==" operator is specially used to compare whether the values ​​of two variables are equal, that is, to compare whether the values ​​stored in the memory corresponding to the variables are the same, to compare whether two basic types of data or two reference variables are Equal, you can only use the == operator.

If the data pointed to by a variable is of object type, then two pieces of memory are involved at this time, the object itself occupies a piece of memory (heap memory), and the variable also occupies a piece of memory (stack memory), for example Objet obj = new Object(); The variable obj is a memory, and new Object() is another memory. At this time, the value stored in the memory corresponding to the variable obj is the first address of the memory occupied by the object. For a variable that points to an object type, if you want to compare whether two variables point to the same object, that is, to see if the values ​​in the memory corresponding to the two variables are equal, then you need to use the == operator to compare .

The equals method is used to compare whether the contents of two independent objects are the same, just like comparing whether two people look the same, the two objects it compares are independent . For example, for the following code:

String a=new String("foo");

  String b=new String("foo");

  The two new statements create two objects, and then use the two variables a and b to respectively point to one of the objects. These are two different objects, and their first addresses are different, that is, the values ​​stored in a and b. are not the same, so the expression a==b will return false, and the contents of these two objects are the same, so the expression a.equals(b) will return true.

In actual development, we often need to compare whether the content of the passed string is equal, for example, String input = ...;input.equals("quit"), many people use == for comparison without paying attention, which is Wrong, remember that string comparisons basically use the equals method.

If a class does not define its own equals method, it will inherit the equals method of the Object class. The implementation code of the equals method of the Object class is as follows:

boolean equals(Object o){

    return this==o;

  }

This shows that if a class does not define its own equals method, its default equals method (inherited from the Object class) uses the == operator, and is also comparing whether the objects pointed to by the two variables are the same object. At this time, use equals and Using == yields the same result, and always returns false if comparing two separate objects. If you write a class that wants to be able to compare the contents of two instance objects created by the class to see if the contents are the same, then you must override the equals method and write your own code to decide under what circumstances the contents of the two objects are considered to be the same.

9. What is the difference between static variables and instance variables?

The difference in syntax definition: static keyword should be added before static variable, but not before instance variable .

The difference when the program is running: Instance variables belong to the properties of an object, and an instance object must be created before the instance variables are allocated space before the instance variables can be used . Static variables do not belong to an instance object, but to a class, so they are also called class variables. As long as the program loads the bytecode of the class without creating any instance objects, the static variables will be allocated space, and the static variables can be used . In short, instance variables must be created before they can be used through this object, and static variables can be directly referenced using the class name.

For example, for the following program, no matter how many instance objects are created, only one staticVar variable will always be allocated, and each time an instance object is created, this staticVar will increase by 1; however, each time an instance object is created, an instanceVar will be allocated , that is, multiple instanceVars may be allocated, and the value of each instanceVar is only incremented once.

public class VariantTest{

public static int staticVar = 0;

public int instanceVar = 0;

public VariantTest(){

staticVar++;

instanceVar++;

System.out.println(“staticVar=” + staticVar + ”,instanceVar=” + instanceVar);

}

}

10. Is it possible to call a non-static method from inside a static method?

Can not. Because a non-static method is to be associated with an object, an object must be created before a method call can be made on the object, while a static method does not need to create an object and can be called directly . That is to say, when a static method is called, no instance object may be created. If a call to a non-static method is issued from a static method, which object is the non-static method associated with? This logic cannot be established, so a call to a non-static method cannot be issued inside a static method .

11. The difference between Integer and int

int is one of the 8 primitive data types provided by java. Java provides wrapper classes for each primitive type, Integer is the wrapper class provided by java for int. The default value of int is 0, and the default value of Integer is null, that is, Integer can distinguish the difference between unassigned and 0, while int cannot express the unassigned situation , for example, to express not taking the exam and exam If the score is 0, only Integer can be used. In JSP development, the default value of Integer is null, so when the el expression is used to display in the text box, the value is a blank string, and the default default value of int is 0, so when the el expression is used to display in the text box, The result is 0, so, int is not suitable as the type of form data in the web layer.

In Hibernate, if the OID is defined as an Integer type, then Hibernate can judge whether an object is temporary based on whether its value is null. If the OID is defined as an int type, it is also necessary to set its unsaved- in the hbm mapping file. The value attribute is 0.

In addition, Integer provides a number of operation methods related to integers, such as converting a string into an integer. Integer also defines constants representing the maximum and minimum values ​​of integers.

12. Please tell the difference between the scope public, private, protected, and not writing

The visible ranges of these four scopes are shown in the table below.

Description: If no access modifier is written on the modified element, it means friendly.

13. The difference between Overload and Override. Can an Overloaded method change the type of the return value?

Overload means overloading , Override means overriding, that is, rewriting .

Overloading means that there can be multiple methods with the same name in the same class, but the parameter lists of these methods are different (that is, the number or types of parameters are different).

Rewriting Override means that the method in the subclass can have the same name and parameters as a method in the parent class. When calling this method through the instance object created by the subclass, the defined method in the subclass will be called, which is equivalent to calling the method in the subclass. The exact same method defined in the parent class is overridden, which is also a manifestation of the polymorphism of object-oriented programming. When a subclass overrides the method of the parent class, it can only throw fewer exceptions than the parent class, or throw a child exception of the exception thrown by the parent class, because the child class can solve some problems of the parent class, and cannot be more than the parent class. There are more questions. The access rights of subclass methods can only be greater than those of the parent class, not less. If the method of the parent class is of the private type, then the subclass has no coverage restriction, which is equivalent to adding a brand new method to the subclass.

As for whether the Overloaded method can change the type of the return value, it depends on what you want to ask? This topic is very vague. If the parameter lists of several Overloaded methods are different, their returner types can of course be different. But I guess the question you want to ask is: If the parameter lists of two methods are exactly the same, is it possible to overload Overload by making their return values ​​different ? This is not possible, we can use the method of rebuttal to illustrate this problem, because sometimes we can call a method without defining the return result variable, that is, don't care about the return result . For example, when we call the map.remove(key) method, Although the remove method has a return value, we usually do not define a variable that receives the returned result. At this time, suppose that there are two methods with the same name and parameter list in the class. Only the return type is different, and java cannot determine the programmer. The bottom line is which method you want to call, because it cannot be determined by the return result type. 

Override can be translated to override, literally, it overrides a method and overrides it to achieve a different effect. The most familiar coverage to us is the implementation of interface methods. Generally, only methods are declared in the interface. When we implement them, we need to implement all the methods declared by the interface . In addition to this typical usage, we may also override methods in parent classes in subclasses in inheritance. Pay attention to the following points when overriding:

1. The flag of the overridden method must exactly match the flag of the overridden method to achieve the effect of coverage;

  2. The return value of the overridden method must be consistent with the return value of the overridden method;

  3. The exception thrown by the overridden method must be the same as the exception thrown by the overridden method, or a subclass thereof;

  4. The overridden method cannot be private, otherwise only a new method is defined in its subclass, and it is not overridden.

Overload may be familiar to us and can be translated as overloading . It means that we can define some methods with the same name, distinguish these methods by defining different input parameters, and then call them, the VM will be based on different parameters. style, to choose the appropriate method to execute. Note the following points when using overloading:

  1. You can only pass different parameter styles when using overloads. For example, different parameter types, different number of parameters, different parameter order (of course, several parameter types in the same method must be different, for example, they can be fun(int,float), but not fun(int,int) ));
  2. Cannot be overloaded by access rights, return types, and thrown exceptions;
  3. The exception type and number of methods will not affect overloading;
  4. For inheritance, if a method is priavte in the parent class, it cannot be overloaded in the subclass. If it is defined, it only defines a new method without overloading. Effect.

14. The difference between has a and is a

is-a represents the relationship of belonging . For example, a rabbit belongs to an animal (inheritance relationship).

has-a means combination, including relationship . For example, the rabbit contains legs, first and other components.

15. How does ClassLoader load classes?

There are multiple class loaders in jvm, and each class loader can be responsible for loading classes in a specific location. For example, bootstrap class loading is responsible for loading classes in jre/lib/rt.jar. The classes in jdk we usually use are located in rt.jar. The extclassloader is responsible for loading the classes in jar/lib/ext/*.jar, and the appclassloader is responsible for the classes in the directory or jar specified by the classpath . In addition to bootstrap, other class loaders are themselves java classes, and their parent class is ClassLoader.

16. The benefits of layered design

Each function is modularized according to the calling process. The advantage of modularization is that it can be combined at will . For example, if you want to register a user, the process is to display the interface and receive the user's input through the interface, and then perform business logic processing. Processing business logic and accessing the database, if we write all these steps in one method in the way of running account, this is also possible, but the disadvantage of this is that when the interface needs to be modified, the code is all in one method. , the code of business logic and database access may be damaged. Similarly, when the code of business logic or database access is modified, other parts of the code will also be damaged. Layering is to write the code of the interface part, business logic part, and database access part in their own independent methods or classes, so that there will be no problems that affect the whole body. After layering in this way, it is easy to switch between layers. For example, the original interface is Swing, and now it needs to be changed to BS interface. If it was originally designed according to layers, you don't need code involving business and data access at this time, just write A web interface will do.

The benefits of layering:

1. Realize the decoupling between software;

  2. Facilitate the division of labor

  3. Easy to maintain

  4. Improve the reuse of software components

  5. It is easy to replace a certain product . For example, the persistence layer uses hibernate. If you need to replace the product with toplink, you don't need to use other business codes and directly change the configuration.

  6. Facilitate the expansion of product functions.

  7. It is convenient to adapt to the changing needs of users

17. What is the function of the hashCode method?

The hashcode method is used to identify whether two objects are equal.

The equals method and the hashCode method are both used to determine whether two objects are equal, but they are different.

Generally speaking, the equals method is called by the user. If you want to determine whether two objects are equal, you can override the equals method and call it in the code to determine whether they are equal. To put it simply, the equals method is mainly used to judge whether two objects are equal on the surface or from the content. For example, if there is a student class, the attributes are only name and gender, then we can think that as long as the name and gender are equal, then the two objects are said to be equal.

The hashcode method is generally not called by users. For example, in the hashmap, since the key cannot be repeated, he judges the hashcode method when judging whether the key is repeated, and also uses the equals method. What cannot be repeated here means that as long as there is one difference between equals and hashcode, it is fine! So in simple terms, hashcode is equivalent to the encoding of an object, just like md5 in a file. It is different from equals in that it returns an int, which is not intuitive to compare. We generally override hashcode while overriding equals to make their logic consistent . For example, in the example just now, if the name and gender are equal, even if the two objects are equal, then the hashcode method also returns the hashcode value of the name plus the hashcode value of the gender, so that logically, they are consistent.

To physically judge whether two objects are equal, use ==. If the physical (memory) addresses of the two objects are equal, then the two objects must be the same object.

18. What is AOP?

1. Introduction to the concept of AOP

The so-called AOP, that is, Aspect orientied program, is aspect-oriented (aspect) programming.

  Aspect-Orlented-Programming, or AOP, is a powerful complement to object-oriented thinking.

  The advantage of AOP is that you can dynamically add and remove logic on the aspect without affecting the original execution code

2. Explain what an aspect (aspect) is

The so-called aspect (aspect) means that a function of the system that runs through each module of the system is an aspect (aspect ) , such as logging, unified exception handling, transaction processing, and permission checking. These functions are all part of the software system. A face, not a point, should appear in each module.

3. What is Aspect Oriented Programming

Aspect-oriented programming is the process of encapsulating the functions of one aspect of the system into objects.

4. How to perform aspect-oriented programming

The object corresponding to the function module is embedded into the original system modules as an aspect, and the agent technology is used, the agent will call the target, and at the same time add the code (object) of the aspect function. Therefore, when configuring the proxy object with spring, you only need to configure two properties, which represent the target and the aspect object (Advisor).

 19. Talk about your understanding of mvc

MVC is the abbreviation of Model-View-Controler. That is Model-View-Controller. MVC is a design pattern that enforces separation of application input, processing, and output.

Models, views, and controllers in MVC are responsible for different tasks.

  • View: A view is the interface that the user sees and interacts with. Views display relevant data to the user and accept user input. Views do not do any business logic processing.
  • Models: Models represent business data and business processes. Equivalent to JavaBean. A model can provide data for multiple views. This improves the reusability of the application
  • Controller: When the user clicks the submit button in the web page, the controller accepts the request and invokes the corresponding model to process the request. Then the corresponding view is called according to the processing result to display the processing result.

The processing process of MVC: First, the controller accepts the user's request, calls the corresponding model for business processing, and returns data to the controller. The controller calls the corresponding view to display the result of the processing. and presented to the user through the view

 

Guess you like

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