Java development interview questions and answers
Today, take the time to sort out the things in the Java development interview, and help those brothers and sisters who are looking for a job or want to find a job!
Share the current interview questions and answers to common Java development questions for your reference.
Java basic learning materials click below! ! !
Java complete learning materials
1. Can the String class be inherited?
The String class is modified with the final keyword when it is declared, and the class modified by the final keyword cannot be inherited.
Next we can look at the source code snippet of the String class:
public final class String
implements java.io.Serializable, Comparable<String>,CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
● Why do Java language developers define the String class as final?
Because the string pool is only possible if the string is immutable. The implementation of string pool can save a lot of heap space at runtime, because different string variables all point to the same string in the pool. But if the string is variable, then String interning will not be implemented, because in this case, if the variable changes its value, the value of other variables pointing to this value will also change. If the string is variable, it will cause serious security problems. For example, the user name and password of the database are passed in in the form of strings to obtain the database connection, or in socket programming, the host name and port are passed in in the form of strings. Because the string is immutable, its value cannot be changed. Otherwise, hackers can exploit the loophole and change the value of the object pointed to by the string, causing security vulnerabilities.
Because strings are immutable, they are multi-thread safe, and the same string instance can be shared by multiple threads. This eliminates the need to use synchronization because of thread safety issues. The string itself is thread-safe.
Because the string is immutable, the HashCode is cached when it is created and does not need to be recalculated. This makes the string very suitable as a key in the Map, and the processing speed of the string is faster than other key objects. This is that the keys in HashMap often use strings.
● In addition to modifying the class, what other uses of the final keyword are there?
- The final modified variable, once assigned, cannot be reassigned;
- The final modified method cannot be overridden;
- The final modified instance variables must be manually assigned, and the system default values cannot be used;
- Final modified instance variables are generally used in conjunction with static to declare constants;
Note: final cannot be combined with abstract keyword.
In short, final means final and immutable.
2. The difference between & and &&?
● The & operator is: logical AND; && operator is: short-circuit AND.
● The final operation results of & and && in the program are exactly the same, but && has a short-circuit phenomenon. When the result of the expression on the left of the && operator is false, the expression on the right is not executed, and a short-circuit occurs. Phenomenon. If it is the & operator, then no matter whether the expression on the left is true or false, the expression on the right will definitely be executed. This is the essential difference between the two of them.
● Of course, the & operator can also be used in binary bit operations, such as bitwise AND operations.
3. Two objects with the same value equals result true, but they can have different hashCodes. Is this sentence correct?
No, if two objects x and y satisfy x.equals(y) == true, their hash values (hashCode) should be the same. Java stipulates the equals method and the hashCode method as follows:
(1) If two objects are the same (the equals method returns true), then their hashCode values must be the same;
(2) If the hashCode of two objects is the same, they are not necessarily the same. Of course, you may not follow the requirements, but if you violate the above principles, you will find that when using the set, the same object can appear in the Set collection, and the efficiency of adding new elements will be greatly reduced (for the use of hash storage System, if the hash code conflicts frequently, the access performance will drop sharply).
About equals and hashCode methods, many Java programmers know, but many people just know it. In Joshua Bloch’s masterpiece "Effective Java" ("Effective Java" is a must-read book for Java programmers in many companies, if you Haven't read it yet, so hurry up and buy a copy) The equals method is introduced in this way:
First, the equals method must satisfy reflexivity (x.equals(x) must return true), symmetry (when x.equals(y) returns true, y.equals(x) must also return true), and transitivity (x. When equals(y) and y.equals(z) both return true, x.equals(z) must also return true) and consistency (when the object information referenced by x and y has not been modified, call x.equals multiple times (y) should get the same return value), and for any non-null value reference x, x.equals(null) must return false.
The tricks to achieve a high-quality equals method include:
- Use == operator to check "whether the parameter is a reference to this object";
- Use the instanceof operator to check "whether the parameter is of the correct type";
- For the key attributes in the class, check whether the attributes of the parameter passed into the object match it;
- After writing the equals method, ask yourself whether it satisfies symmetry, transitivity, and consistency;
- Always rewrite hashCode when rewriting equals;
- Do not replace the Object object in the equals method parameter with another type, and do not forget the @Override annotation when rewriting.
4. In Java, how to break out of the current multiple nested loops?
Add a mark such as outfor before the outermost loop, and then use break outfor; to jump out of multiple loops.
for example the following code:
public class TestBreak {
public static void main(String[] args) {
outfor: for (int i = 0; i < 10; i++){
for (int j = 0; j < 10; j++){
if (j == 5){
break outfor;
}
System.out.println("j = " + j);
}
}
}
}
The running result of
j = 0
j = 1
j = 2
j = 3
j = 4
5. What is the difference between overload and override? Can overloaded methods be distinguished based on the return type?
Method overloading and rewriting are both ways to achieve polymorphism. The difference is that the former achieves compile-time polymorphism, while the latter achieves runtime polymorphism.
Overloading occurs in a class, and methods with the same name are considered to be overloaded if they have different parameter lists (different types, different numbers, and different orders).
The overriding occurs between the subclass and the parent class. The overriding requires that the method after the subclass override has the same return type as the overridden method of the parent class. It is better to access than the overridden method of the parent class and cannot be compared to the parent class. The overridden method declares more exceptions (Liskov Substitution Principle). Overloading has no special requirements for the return type.
● Rules for method overloading:
- The method names are the same, and the order, type, and number of parameters in the parameter list are different.
- Overloading has nothing to do with the return value of the method, it exists in the parent class and the subclass, in the same kind.
- Different exceptions can be thrown, and there can be different modifiers.
● Rules for method rewriting:
- The parameter list, method name, and return value type must be exactly the same;
- The construction method cannot be overridden;
- The method declared as final cannot be overridden;
- There is no overriding for the method declared as static (rewriting and polymorphic union only make sense);
- The access authority cannot be lower than the parent class;
- The rewritten method cannot throw a broader exception;
6. When an object is passed as a parameter to a method, this method can change the properties of the object and return the changed result. Then, is it passed by value or by reference?
It is value transfer. Method calls in the Java language only support parameter value passing. When an object instance is passed to a method as a parameter, the value of the parameter is the memory address of the object. After this value (memory address) is passed, the same memory address points to the same object in the heap memory, so by which reference to manipulate this object, the properties of the object are changed.
7. Why can't the method distinguish overloads based on the return type?
Let's look at the following code:
public void testMethod(){
doSome();
}
public void doSome(){
}
public int doSome(){
return 1;
}
In the Java language, when a method is called, even if the method has a return value, we can also not receive the return value. For example, the above two methods doSome(), when called in testMethod(), the Java compiler cannot distinguish the called Which method is specific. So for the compiler, the doSome() method is not overloaded but repeated, and the compiler reports an error. Therefore, the distinction between these two methods cannot rely on the return value type of the method.
8. What are the similarities and differences between abstract class and interface?
Difference:
● Constructors can be defined in abstract classes, but interfaces cannot;
● Abstract classes can have abstract methods and concrete methods, while interfaces cannot have concrete methods;
● The members in the interface are all public, and the members in the abstract class can be modified with private, public, protected, default, etc.;
● Member variables can be defined in abstract classes, and only constants can be used in interfaces;
● Classes with abstract methods must be declared as abstract classes, and abstract classes do not necessarily have abstract methods;
● The abstract class can contain static methods, and the interface cannot have static methods;
● A class can only inherit one abstract class, and a class can implement multiple interfaces;
:
● Cannot be instantiated;
● You can use abstract classes and interface types as reference types;
● If a class inherits an abstract class or implements an interface, all abstract methods in it need to be implemented, otherwise the class still needs to be declared as an abstract class;
9. Can a Chinese character be stored in a char variable? Why?
The char type can store a Chinese character, because the encoding used in Java is Unicode (do not choose any specific encoding, use the number of the character in the character set directly, this is the only way to unify), a char type occupies 2 bytes ( 16 bits), so it’s okay to put a Chinese.
Supplement: Using Unicode means that characters have different manifestations inside and outside the JVM. Inside the JVM, they are all Unicode. When this character is transferred from inside the JVM to the outside (for example, stored in the file system), encoding conversion is required. So there are byte streams and character streams in Java, as well as conversion streams that convert between character streams and byte streams, such as InputStreamReader and OutputStreamReader. These two classes are adapter classes between byte streams and character streams. The task of code conversion.
10. Can abstract methods be static at the same time, can they be native methods at the same time, and can they be synchronized at the same time?
both are not.
● Abstract methods need to be rewritten by subclasses, while static methods cannot be rewritten, so the two are contradictory.
● Native methods are methods implemented by native codes (such as C++ code), while abstract methods are not implemented and contradictory.
● Synchronized is related to the implementation details of the method, and abstract methods do not involve implementation details, so they are also contradictory.
11. What is the difference between == and equals?
The biggest difference between equals and == is that one is the method and the other is the operator.
● ==: If the compared object is a basic data type, it compares whether the value is equal; if it compares a reference data type, it compares whether the address value of the object is equal.
● equals(): Used to compare whether the contents of the two objects of the method are equal. The equals method cannot be used for variables of basic data types. If the equals method is not rewritten, the address of the object pointed to by the variable of the reference type is compared.
12. Explain the difference between static variables and instance variables?
No matter how many objects are created, there is one and only one static variable in the memory; the instance variable must depend on an instance, and the object needs to be created and then accessed through the object. Static variables can be implemented to allow multiple objects to share memory.
13. What is the difference between break and continue?
● Both break and continue are statements used to control loops.
● break is used to completely end a loop, jump out of the loop body and execute the statement following the loop.
continue is used to skip this cycle and continue to the next cycle.
14. String s = "Hello"; s = s + "world!"; After these two lines of code are executed, has the content of the original String object changed?
No.
Because String is designed as an immutable class, all its objects are immutable objects.
In this code, s originally pointed to a String object with the content "Hello", and then we performed a "+" operation on s. Has the object pointed to by s changed?
The answer is no. At this time, s does not point to the original object, but points to another String object with the content "Hello world!". The original object still exists in the memory, but the reference variable s no longer points to it.
Through the above description, we can easily derive another conclusion. If you often make various changes to the string, or unforeseen changes, then using String to represent the string will cause a lot of memory overhead. Because the String object cannot be changed after it is created, a String object is needed to represent each different string. At this time, you should consider using
StringBuffer/StringBuilder class, which allows modification instead of generating a new object for each different string. Moreover, the conversion of these two types of objects is very easy. At the same time, we can also know that if you want to use a string with the same content, you don't need to new a String every time. For example, if we want to initialize a String reference variable named s in the constructor and set it to the initial value, we should do this:
s = new String("Power node, the Java Whampoa Military Academy of word of mouth");
Instead of doing this:
s = new String("Power node, the Java Whampoa Military Academy of word of mouth");
The latter will call the constructor every time to generate a new object, which has low performance and high memory overhead, and is meaningless, because the String object cannot be changed, so for strings with the same content, only one String object can be used to represent them. In other words, if the above constructor is called multiple times to create multiple objects, their String type properties all point to the same object.
The above conclusion is also based on the fact that for string constants, if the content is the same, Java considers them to represent the same String object. Invoking the constructor with the keyword new will always create a new object, regardless of whether the content is the same.
As for why the String class is designed as an immutable class, it is determined by its purpose. In fact, not only String, but many classes in the Java standard library are immutable. When developing a system, we sometimes need to design immutable classes to pass a set of related values, which is also a manifestation of object-oriented thinking. Immutable classes have some advantages, for example, because its objects are read-only, there will be no problems with concurrent access by multiple threads. Of course, there are some shortcomings. For example, each different state must be represented by an object, which may cause performance problems. Therefore, the Java Standard Class Library also provides a variable version, namely StringBuffer.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。