day2 java basic serial 10 questions, how many questions can you hold on to? [interview]

⭐ ️ ⭐ Key points: update 10 interview questions every day
⚠️⚠️ Important things: if you are a freshman or sophomore, you will read 10 interview questions every day, and your knowledge will be more solid. You can be handy when you are ready to find a job in your junior. If you are a junior or senior, you will not be too nervous when you read 10 interview questions every day. If you have gone to work, review 10 questions every day to solve the midlife crisis, ha ha ha
📋📋 Follow up content: at present, bloggers are continuously outputting classic interview questions on java Foundation (there are many more in sorting). In the follow-up, there will be spring, mybatis, mybatis plus, SpringBoot, SpringCloud, juc concurrent programming, jvm, etc. of course, there will be data structure, operating system, computer network, http, etc.
⭐ ️ ⭐ Last article: Java basic serial 15 questions, how many questions can you hold on to? [interview]
You can watch 10 interview questions with bloggers every day. Welcome to praise 👍➕ Collection ⭐ ️ ➕ comment 💬 Support bloggers 🤞

👉 How are static methods different from instance methods?

1. Call mode

When calling static methods externally, you can use the class name You can also use objects as method names Method name, while the instance method has only the latter. That is, calling a static method eliminates the need to create an object.

However, it should be noted that objects are generally not recommended Method name to call a static method. This approach is very confusing. Static methods do not belong to an object of a class, but to this class.

Therefore, it is generally recommended to use class names Method name to call a static method.

public class Person {
    public void method() {
      //......
    }

    public static void staicMethod(){
      //......
    }
    public static void main(String[] args) {
        Person person = new Person();
        // Call instance method
        person.method();
        // Call static method
        Person.staicMethod()
    }
}

2. Are there restrictions on accessing class members

When accessing members of this class, static methods only allow access to static members (i.e. static member variables and static methods), and instance members (i.e. instance member variables and instance methods) are not allowed. However, this restriction does not exist for instance methods.

👉 The difference between overloading and rewriting

Overloading is the same method, which can make different processing according to different input data.
Rewriting is when the subclass inherits the same method from the parent class and the input data is the same, but it needs to make different decisions
 When responding to the parent class, you need to override the parent class method.

heavy load

If it occurs in the same class (or between parent and child classes), the method name must be the same, the parameter types, number and order must be different, and the method return value and access modifier can be different.

The Book Java core technology introduces overloading as follows:
If multiple methods (such as the construction method of StringBuilder) have the same name and different parameters, overloading occurs.

StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder("HelloWorld");

The compiler must select which method to execute. It selects the corresponding method by matching the parameter type given by each method with the value type used by a specific method call. If the compiler cannot find a matching parameter, it will generate a compile time error because there is no match at all, or none is better than the others (this process is called overload resolution).

Java allows you to overload any method, not just constructor methods.

To sum up: overloading means that multiple methods with the same name in the same class perform different logical processing according to different parameters.

rewrite
Rewriting occurs at run time. It is the subclass's rewriting of the implementation process of the parent's allowed access methods.

  1. The method name and parameter list must be the same. The return value type of the subclass method should be smaller or equal than that of the parent method. The range of exceptions thrown is less than or equal to that of the parent class, and the range of access modifiers is greater than or equal to that of the parent class.
  2. If the access modifier of the parent method is private/final/static, the subclass cannot override the method, but the method modified by static can be declared again.
  3. Constructor cannot be overridden

To sum up: rewriting is the re transformation of the parent method by the subclass. The external appearance cannot be changed and the internal logic can be changed.

The rewriting of methods should follow the principle of "two in common, two small and one large" (the following is excerpted from Crazy Java handout):
1. "Two identical" means that the method name is the same and the formal parameter list is the same;
2. "Two small" means that the return value type of the subclass method should be smaller or equal than that of the parent method, and the exception class thrown by the subclass method declaration should be smaller or equal than that thrown by the parent method declaration;
3. "One large" means that the access rights of subclass methods should be greater or equal than those of parent methods.

⭐ ﹥ for the rewritten return value type, it needs to be explained here. The above description is not clear and accurate: if the return type of the method is void and basic data type, the return value cannot be modified during rewriting. However, if the return value of a method is a reference type, the subclass of the reference type can be returned when overridden.

public class Hero {
    public String name() {
        return "Superhero Movie";
    }
}
public class SuperMan extends Hero{
    @Override
    public String name() {
        return "superman";
    }
    public Hero hero() {
        return new Hero();
    }
}

public class SuperSuperMan extends SuperMan {
    public String name() {
        return "Superheroes";
    }

    @Override
    public SuperMan hero() {
        return new SuperMan();
    }
}

👉 What is a variable length parameter?

Starting from Java 5, Java supports the definition of variable length parameters. The so-called variable length parameters are parameters that allow variable length to be passed in when calling methods. For example, the printVariable method below can accept 0 or more parameters.

public static void method1(String... args) {
   //......
}

In addition, the variable parameter can only be used as the last parameter of the function, but it can be preceded by or without any other parameters.

public static void method2(String arg1, String... args) {
   //......
}

What to do in case of method overloading? Will the method of matching fixed parameters or variable parameters be preferred?

The answer is that methods with fixed parameters will be matched first, because methods with fixed parameters have higher matching degree.

Let's prove it by the following example.

public class VariableLengthArgument {

    public static void printVariable(String... args) {
        for (String s : args) {
            System.out.println(s);
        }
    }

    public static void printVariable(String arg1, String arg2) {
        System.out.println(arg1 + arg2);
    }

    public static void main(String[] args) {
        printVariable("a", "b");
        printVariable("a", "b", "c", "d");
    }
}

Output:
ab
a
b
c
d


In addition, Java's variable parameters will actually be converted into an array after compilation. We can see from the class file generated after compilation.

public class VariableLengthArgument {

    public static void printVariable(String... args) {
        String[] var1 = args;
        int var2 = args.length;

        for(int var3 = 0; var3 < var2; ++var3) {
            String s = var1[var3];
            System.out.println(s);
        }

    }
    // ......
}

👉 Do you know several basic data types in Java?

There are eight basic data types in Java:
6 digital types:
Four integer types: byte, short, int, long
Two floating point types: float and double
1 character type: char
One boolean: boolean.

The default values of these eight basic data types and the size of the space occupied are as follows:

For boolean, the official document does not clearly define it, and it depends on the specific implementation of the JVM manufacturer. Logically, it is understood to occupy 1 bit, but in practice, the factor of efficient computer storage will be considered.

In addition, the storage space occupied by each basic type of Java will not change with the change of machine hardware architecture like most other languages. This invariance in the size of storage space is one of the reasons why Java programs are more portable than programs written in most other languages (mentioned in Section 2.2 of Java programming ideas).
be careful:

  1. long data used in Java must be followed by L, otherwise it will be parsed as an integer.
  2. char a = 'h' char: single quotation mark, String a = "hello": double quotation mark.

These eight basic types have corresponding wrapper classes: Byte, Short, Integer, Long, Float, Double, Character and Boolean.

👉 What is the difference between basic type and packaging type?

  • The wrapper type is null without assignment, while the basic type has a default value and is not null.
  • Wrapper types can be used for generics, but base types cannot.
  • The local variables of the basic data type are stored in the local variable table in the Java virtual machine stack, and the member variables of the basic data type (not modified by static) are stored in the heap of the Java virtual machine. Wrapper types are object types, and we know that almost all object instances exist in the heap.
  • Compared with object types, basic data types take up very little space.
  • Why almost all object instances? This is because after introducing JIT optimization, the HotSpot virtual machine will analyze the escape of objects. If it is found that an object does not escape outside the method, it may be allocated on the stack through scalar replacement to avoid allocating memory on the heap.

⚠️ Note: it is a common mistake to store basic data types in the stack! If the member variables of the basic data type are not modified by static (this is not recommended, but the wrapper type corresponding to the basic data type should be used), they are stored in the heap.

class BasicTypeVar{
  private int x;
}

👉 Do you know the constant pool technology of packaging type?

Most of the wrapper classes of Java basic types implement constant pool technology.

Byte, short, integer and long create corresponding types of cached data for the value [- 128127] by default, Character creates cached data with the value in the range of [0127], and Boolean directly returns True or False.

Integer cache source code:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static {
        // high value may be configured by property
        int h = 127;
    }
}

Character cache source code:

public static Character valueOf(char c) {
    if (c <= 127) { // must cache
      return CharacterCache.cache[(int)c];
    }
    return new Character(c);
}

private static class CharacterCache {
    private CharacterCache(){}
    static final Character cache[] = new Character[127 + 1];
    static {
        for (int i = 0; i < cache.length; i++)
            cache[i] = new Character((char)i);
    }

}

Boolean cache source code:

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

If the corresponding range is exceeded, new objects will still be created. The size of the cache range is only a trade-off between performance and resources.

Two floating-point type wrapper classes, float and double, do not implement constant pool technology.

Integer i1 = 33;
Integer i2 = 33;
System.out.println(i1 == i2);// Output true

Float i11 = 333f;
Float i22 = 333f;
System.out.println(i11 == i22);// Output false

Double i3 = 1.2;
Double i4 = 1.2;
System.out.println(i3 == i4);// Output false

Now let's look at the problem. Is the output of the following code true or false?

Integer i1 = 40;
Integer i2 = new Integer(40);
System.out.println(i1==i2);

The line of Integer i1=40 will be boxed, which means that this line of code is equivalent to integer i1 = integer valueOf(40) . Therefore, i1 directly uses the objects in the constant pool. Integer i2 = new Integer(40) creates a new object directly.

Therefore, the answer is false. Are you right?

Remember: the values of all integer wrapper class objects are compared using the equals method.

👉 Do you understand automatic packing and unpacking? What is the principle?

What is an automatic disassembly box?
Packing: packing basic types with their corresponding reference types;
Unpacking: convert the package type to the basic data type;
give an example:

Integer i = 10;  //Packing
int n = i;   //Unpacking

The byte codes corresponding to the above two lines of code are:

   L1

    LINENUMBER 8 L1

    ALOAD 0

    BIPUSH 10

    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;

    PUTFIELD AutoBoxTest.i : Ljava/lang/Integer;

   L2

    LINENUMBER 9 L2

    ALOAD 0

    ALOAD 0

    GETFIELD AutoBoxTest.i : Ljava/lang/Integer;

    INVOKEVIRTUAL java/lang/Integer.intValue ()I

    PUTFIELD AutoBoxTest.n : I

    RETURN

From the bytecode, we find that boxing actually calls the valueOf() method of the wrapper class, and unpacking actually calls the xxxValue() method.
So,

  • Integer i = 10 is equivalent to integer I = integer valueOf(10)
  • Int n = I is equivalent to int n = i.intValue();
    Note: if the box is disassembled frequently, it will also seriously affect the performance of the system. We should try our best to avoid unnecessary disassembly and assembly of the box.
private static long sum() {
    // You should use Long instead of Long
    Long sum = 0L;
    for (long i = 0; i <= Integer.MAX_VALUE; i++)
        sum += i;
    return sum;
}

👉 The difference between object-oriented and process oriented

The main difference between the two is that they solve problems in different ways:

  • Process oriented divides the process of solving problems into methods, and solves problems through the implementation of methods.
  • Object oriented will first abstract out the object, and then solve the problem by using the object execution method.

In addition, object-oriented programs are generally easier to maintain, reuse and expand.

👉 Differences between member variables and local variables

  • Syntax form: from the perspective of syntax form, member variables belong to classes, while local variables are variables defined in code blocks or methods or parameters of methods; Member variables can be modified by public,private,static and other modifiers, while local variables cannot be modified by access control modifiers and static; However, both member variables and local variables can be modified by final.
  • Storage method: from the storage method of variables in memory, if the member variable is modified with static, then the member variable belongs to class. If the static modification is not used, the member variable belongs to instance. Objects exist in heap memory and local variables exist in stack memory.
  • Survival time: in terms of the survival time of variables in memory, member variables are a part of objects. They exist with the creation of objects, while local variables are automatically generated with the call of methods and die with the end of the call of methods.
  • Default value: from the perspective of whether the variable has a default value, if the member variable is not assigned an initial value, it will be automatically assigned with the default value of the type (one exception: the member variable modified by final must also be explicitly assigned), while the local variable will not be automatically assigned.

👉 What operator is used to create an object? How are object entities different from object references?

New operator, new creates an object instance (the object instance is in heap memory), and the object reference points to the object instance (the object reference is stored in stack memory).

An object reference can point to 0 or 1 objects (a rope can be tied without a balloon or a balloon); An object can have n references to it (you can tie a balloon with n ropes).

Tags: Java MySQL IDEA Eclipse

Posted by yacaph on Mon, 18 Apr 2022 08:10:12 +0930