Java basic interview knowledge points

Java basic interview knowledge points

Java basic knowledge related

The difference between == and equals and hashCode in Java

For the relational operator ==

  • If the type of the operand is a basic data type , the relational operator judges whether the values of the left and right operands are equal
  • If the type of the operand is a reference data type , the relational operator determines whether the memory addresses of the left and right operands are the same. In other words, if true is returned at this time, the operator must act on the same object.

For the equals method, the internal implementation is divided into three steps:

  1. First compare whether the references are the same (whether they are the same object),
  2. Then judge whether the types are consistent (whether they are the same type),
  3. Finally compare whether the content is consistent

The implementation steps of equals methods of all built-in classes in Java are the same, especially wrapper classes such as Integer and Double. As Stringin the equalsmethod implementation

//String.java 
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
 

Hashcode is used by the system to quickly retrieve objects

The equals method is intended to determine whether the referenced objects are consistent

When rewriting the equals method and the hashcode method, the member variables used in the equals method must also be used in the hashcode method, except that the former is used as a comparison item, and the latter is used as an information item for generating a summary. Essentially, the data used is The same, so as to ensure the consistency of the two

reference

How many bytes does int, char, and long occupy?

The number of bytes occupied by Java basic types

  • 1 byte: byte, boolean
  • 2 bytes: short, char
  • 4 bytes: int, float
  • 8 bytes: long, double

Note: 1 byte (byte) = 8 bits (bits)

The difference between int and integer

  • Integer is a wrapper class of int, int is a basic data type of java
  • Integer variables must be instantiated before they can be used, and int variables do not need
  • Integer is actually a reference to an object. When an Integer is new, it actually generates a pointer to the object; and int directly stores the data value
  • The default value of Integer is null, the default value of int is 0
reference

Understanding of Java polymorphism

Polymorphism means that when a method of a parent class is overridden by a subclass, it can produce its own functional behavior. The same operation acts on different objects, which can have different interpretations and produce different execution results.

3.necessary conditions for polymorphism:

  1. Inherit the parent class.
  2. Override the method of the parent class.
  3. The reference of the parent class points to the object of the child class

Then you can use the combined Richter substitution rule to further talk about understanding

Richter's Substitution Rule-All references to the base class must be able to transparently use objects of its subclass

  • The subclass must fully implement the methods of the parent class

Note that the parent class or interface must be used when calling other classes in the class. If the parent class or interface cannot be used, the design of the class has violated the LSP principle

Note that if the subclass cannot fully implement the methods of the parent class, or some methods of the parent class have been "distorted" in the subclass, it is recommended to break the parent-child inheritance relationship and use dependency, aggregation, combination and other relationships instead of inheritance.

  • Subcategories can have their own personalities
  • Input parameters can be enlarged when overriding or implementing the method of the parent class
  • The output result can be reduced when overriding or implementing the method of the parent class

In the project, when using the Richter substitution principle, try to avoid the "personality" of the subcategory. Once the subcategory has a "personality", the relationship between the subcategory and the parent category will be difficult to reconcile. Treat the subcategory as the parent category Use, the "personality" of the sub-category is obliterated-a little wronged; using the sub-category as a business alone will make the coupling relationship between codes become confusing and confusing-lack of standards for class replacement

The difference between String, StringBuffer, StringBuilder

StringBuffer and String are both used to store strings, but because of their different internal implementations, they use different ranges. For StringBuffer, if it modifies strings when processing strings, It does not generate a new string object, so it is better than String in terms of memory usage

StringBuilder is also a variable string object. The difference between it and StringBuffer is that it is not thread-safe. Based on this, its speed is generally faster than StringBuffer.

The splicing of String strings will be parsed by JVM into StringBuilder object splicing. In this case, the speed of String is faster than that of StringBuffer.

str += b is equivalent to str = new StringBuilder(str).append( b ).toString();

Detailed internal class

The inner class makes the multiple inheritance solution more complete

The most attractive reason for using inner classes is that each inner class can independently inherit a (interface) implementation, so no matter whether the outer class has inherited a certain (interface) implementation, it has no effect on the inner class.

Use internal classes to achieve multiple inheritance

  • The inner class can use multiple instances, each instance has its own state information, and is independent of the information of other peripheral objects.
  • In a single outer class, multiple inner classes can implement the same interface in different ways, or inherit the same class.
  • The moment of creating the inner class object does not depend on the creation of the outer class object.
  • The inner class does not have a confusing "is-a" relationship, it is an independent entity.
  • The inner class provides better encapsulation, except for the outer class, no other classes can be accessed.

When we are creating an inner class object of a certain outer class, the inner class object must capture a reference to that outer class object, as long as we access the members of the outer class, we will use this reference to select the outer class the member of

Member inner class

Pay attention to two points in the member inner class,

  • There can be no static variables and methods in the inner class of the member
  • The member inner class is attached to the outer class, so the inner class can only be created if the outer class is created first

Static inner class

There is one biggest difference between a static inner class and a non-static inner class. We know that a non-static inner class will implicitly save a reference after the compilation is complete. The reference refers to the outer periphery where it was created, but the static inner class No. The absence of this reference means:

  • Its creation does not need to rely on peripheral classes.
  • It cannot use any non-static member variables and methods of the outer class.

reference

Why can an anonymous inner class in Java only access final modified external variables?

Anonymous inner class usage

public class TryUsingAnonymousClass {
    public void useMyInterface() {
        final Integer number = 123;
        System.out.println(number);

        MyInterface myInterface = new MyInterface() {
            @Override
            public void doSomething() {
                System.out.println(number);
            }
        };
        myInterface.doSomething();

        System.out.println(number);
    }
}
 

Compiled result

class TryUsingAnonymousClass$1
        implements MyInterface {
    private final TryUsingAnonymousClass this$0;
    private final Integer paramInteger;

    TryUsingAnonymousClass$1(TryUsingAnonymousClass this$0, Integer paramInteger) {
        this.this$0 = this$0;
        this.paramInteger = paramInteger;
    }

    public void doSomething() {
        System.out.println(this.paramInteger);
    }
}
 

Because the anonymous inner class will eventually be compiled into a separate class, and the variables used by the class will be passed to the class in the form of constructor parameters, for example: Integer paramInteger, if the variable is not defined as final, paramInteger is inside the anonymous The class can be modified, which will cause inconsistency with the external paramInteger. In order to avoid this inconsistency, Java stipulates that anonymous inner classes can only access final modified external variables

The difference between abstract class and interface

  1. The default method implementation abstract class can have the default method implementation is completely abstract. There is no implementation of methods at all in the interface
  2. To implement abstract classes, use the extends keyword to inherit abstract classes. If the subclass is not an abstract class, it needs to provide the implementation of all the methods declared in the abstract class. The subclass uses the implements keyword to implement the interface. It needs to provide the implementation of all the methods declared in the interface.
  3. Abstract classes can have constructors, but interfaces cannot have constructors
  4. Abstract methods can have public, protected, and default modifiers. The default modifier for interface methods is public. You cannot use other modifiers.
  5. The abstract class in the Java language represents an inheritance relationship. A subclass can only have one parent class, but there can be multiple interfaces.
  6. Abstract methods are faster than interfaces, and interfaces are slightly slower because it takes time to find methods implemented in the class.
  7. If you add a new method to an abstract class, you can provide it with a default implementation. Therefore you do not need to change your current code. If you add methods to the interface, then you must change the class that implements the interface
reference

The difference between extends and super in generics

Can the static method of the parent class be overridden by the subclass

Static methods and static member variables can be inherited, but cannot be overridden. It is hidden from subclasses, so static methods cannot achieve polymorphism

The difference between process and thread

The main difference between processes and threads is that they are different operating system resource management methods. A process has an independent address space. After a process crashes, it will not affect other processes in the protected mode, and a thread is just a different execution path in a process. Threads have their own stacks and local variables, but there is no separate address space between threads. The death of a thread means the death of the entire process. Therefore, a multi-process program is more robust than a multi-threaded program, but it is costly when the process is switched. The resources are larger and the efficiency is worse. But for some concurrent operations that require simultaneous execution and share certain variables, only threads can be used, not processes.

The difference between final, finally, finalize

  • final is used to declare properties, methods, and classes, which respectively indicate that properties are immutable, methods cannot be overridden, and classes cannot be inherited.

  • finally is part of the structure of the exception handling statement, which means that it is always executed.

  • finalize is a method of the Object class. This method of the recycled object will be called when the garbage collector is executed. This method can be overridden to provide other resource recovery during garbage collection, such as closing files. JVM does not guarantee that this method will always be called .

reference

The difference between Parcelable and Serializable

Serializable is a serialization interface in Java. It is simple to use but expensive. The serialization and deserialization process requires a lot of I/O operations. Parcelable is the serialization method in Android, so it is more suitable for use on the Android platform. Its disadvantage is that it is a little more troublesome to use, but it is very efficient. This is the serialization method recommended by Android, so we should prefer Parcelable . Parcelable is mainly used for memory serialization. It is also possible to serialize objects to storage devices through Parcelable or transmit the objects through the network after serialization, but this process will be slightly more complicated, so it is recommended in these two cases Everyone uses Serializable.

reference

Why can't there be static properties in non-static inner classes

Talk about the understanding of kotlin

Varies from person to person, please sort out the answers yourself

The method and principle of converting String to integer

Integer a = 2;
private void test() {
    String s1 = a.toString();  //
    String s2 = Integer.toString(a);  //
    String s3 = String.valueOf(a);  //
}
 

Method one source code:

    public String toString() {
        return toString(value);
    }

    public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
    }
 

It can be seen that the final call is

Through the toString() method, an integer (including 0) can be converted into a string, but if the Integer is null, a null pointer exception will be reported

Method three source code:

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
 

It can be seen that when Integer is null, the returned String is the string "null" instead of null