Java basic knowledge interview questions, one is enough, click on it, and then collect it

The interview questions in the article are carefully selected from the vast Internet. If there are errors, please correct me!

1 Introduction

Students who have participated in social recruitment know that when entering a company to interview for development positions, after filling in personal information, they will generally ask to do a written test first, and then the company will determine whether to continue the interview based on the answer to the written test If the answer is not good, some companies may directly say "The technical manager or director is busy, you should go back and wait for the notice." Some companies may continue the interview to learn about your project experience and so on.

At least in the first 5 years of work or even longer, the interview will not skip the written test (except for some companies). I can't remember how many companies I interviewed and how many interview questions I have done. As a result, I sometimes go shopping now, and I always feel familiar in many places. I feel that I have come to face-to-face interviews many years ago. I once laughed at myself, and at one time I doubted what I was relying on to persist in Shanghai. So interview questions are still for job hunting. very important.

There are many articles explaining the keywords of "Java Interview Questions" on the Internet. Why should I summarize it myself? The main reasons are as follows:

  • There are too many articles, but I don’t know which one to read (as in a book, too much information equals no information)
  • The accuracy of the article is not high (I have repeatedly found that the description is incorrect or the code cannot run)
  • Can deepen one's own understanding and memory
  • Once and for all, you don’t need to screen slowly from the Internet next time, just see what you organize

2. Outline

This article mainly organizes the interview questions of Java basic knowledge, mainly including the following points:

  • 2.1 The difference between Integer and int
  • 2.2 The difference between == and equals
  • 2.3 The difference between String, StringBuilder, StringBuffer
  • 2.4 Boxing and unboxing

Next, explain one by one.

3. The difference between Integer and int

3.1 Differentiation of basic concepts:

  1. Integer is a wrapper class of int (reference type), int is a basic data type (value type) of java.
  2. Integer variables must be instantiated before they can be used, while int variables are not required.
  3. Integer is actually a reference to an object. When an Integer is new, a pointer is actually generated to point to this object; and int is to store the data value directly.
  4. The default value of Integer is null, and the default value of int is 0.

3.2 Several commonly used comparison scenarios for Integer and int:

1) Compare two new Integer() variables and always return false

Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.println(i == j); // false

Two Integer variables generated by new generate two objects with different memory addresses

2) Compare the Integer variable generated by non-new with the variable generated by new Integer(), and always return false

Integer i = new Integer(100);
Integer j = 100;
System.out.println(i == j); // false

The non-new generated Integer variable points to the object in the Java constant pool, and the variable generated by new Integer() points to the newly created object in the heap. The addresses of the two in memory are different.

3) Comparison of two non-new generated Integer variables. If the values ​​of the two variables are between -128 and 127, the comparison result is true. If the values ​​of the two variables are not in this range, the comparison result is false.

Integer i = 100;
Integer j = 100;
System.out.println(i == j); //true

Integer i1 = 128;
Integer j1 = 128;
System.out.println(i1 == j1); //false

Why is this so, let's analyze the reasons:

Integer i = 100; will be translated into Integer i = Integer.valueOf(100); when compiling, and the source code of the valueOf method of the Integer class in Java is as follows:

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 final Integer cache[];

     static {
          // high value may be configured by property
          int h = 127;
          String integerCacheHighPropValue =
              sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
          if (integerCacheHighPropValue != null) {
              try {
                  int i = parseInt(integerCacheHighPropValue);
                  i = Math.max(i, 127);
                  // Maximum array size is Integer.MAX_VALUE
                  h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
              } catch( NumberFormatException nfe) {
                  // If the property cannot be parsed into an int, ignore it.
              }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
    }

    private IntegerCache() {}
}

We can see from the source code

Java will cache the numbers between -128 and 127.
So when Integer i = 100, 100 will be cached, and when Integer j = 100 is written next time, it will be taken directly from the cache and will not be new.

4) When comparing Integer and int variables, as long as the values ​​of the two variables are equal, the result is true

Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true

Because when the packaging class Integer is compared with the basic data type int, Java will automatically unpack it as int, and then compare it, which actually becomes a comparison of two int variables

4. The difference between == and equals

4.1 Differentiation of basic concepts

1) For ==, the comparison is whether the values ​​are equal

如果作用于基本数据类型的变量,则直接比较其存储的 “值”是否相等;

If it acts on a variable of reference type, the comparison is whether the addresses of the pointed objects are equal.

In fact, == compares whether it is a basic data type or a variable of a reference data type, the comparison is all values, but the value stored in a reference type variable is the address of the object

2) For the equals method, compare whether it is the same object

The equals method cannot be applied to variables of basic data types, and equals inherits the Object class;

If the equals method is not rewritten, the comparison is the address of the object pointed to by the variable of the reference type;

If classes such as String and Date rewrite the equals method, the comparison is the content of the pointed object.

3) The equals() method exists in the Object class, because the Object class is the direct or indirect parent class of all classes, that is to say, the equals() method in all classes inherits from the Object class, and there is no overriding equals( In the class of the) method, calling the equals() method has the same effect as using ==, and it is also the address value for comparison. However, most of all classes provided by Java have rewritten the equals() method. The latter equals() method generally compares the values ​​of two objects, such as the String class.
Source of equals() method of Object class:

public boolean equals(Object obj) {
     return (this == obj);
}

String class equals() method source code:

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;
}

4.2 Example

Example 1:

int x = 10;
int y = 10;
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(x == y); // true
System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true

Example 2:

String str3 = "abc";
String str4 = "abc";
System.out.println(str3 == str4); // true

The reason why str3 and str4 want to wait is that the constant pool in memory is used. When the object is created in str3, if there is no constant pool, an object "abc" is created in the constant pool. When it is created for the second time, it is It is used directly, so the objects created twice are actually the same object, and their address values ​​are equal.

Example 3:
First define the Student class

package com.zwwhnly.springbootdemo;

public class Student {
    private int age;

    public Student(int age) {
        this.age = age;
    }
}

Then create two Student instances to compare:

Student student1 = new Student(23);
Student student2 = new Student(23);

System.out.println(student1.equals(student2)); // false

At this time, the equals method calls the equals() method of the base Object class, which is == comparison, so it returns false.

Then we rewrite the equals() method, as long as two students are of the same age, they are considered to be the same student:

package com.zwwhnly.springbootdemo;

public class Student {
    private int age;

    public Student(int age) {
        this.age = age;
    }

    public boolean equals(Object obj) {
        Student student = (Student) obj;
        return this.age == student.age;
    }
}

At this time, compare the two instances just now and return true:

Student student1 = new Student(23);
Student student2 = new Student(23);

System.out.println(student1.equals(student2)); // true

5. The difference between String, StringBuilder, StringBuffer

5.1 Difference explanation

1) Running
speed The order of running speed is: StringBuilder> StringBuffer> String
String The slowest reason:
String is a string constant, and StringBuilder and StringBuffer are both string variables, that is, once the String object is created, the object cannot be changed , But the objects of the latter two are variables and can be changed.

2) Thread safety
In terms of thread safety, StringBuilder is thread-unsafe, while StringBuffer is thread-safe (many methods carry the synchronized keyword).

3) Use scenario
String: Suitable for a small number of string operations.
StringBuilder: Suitable for a large number of operations in the character buffer under a single thread.
StringBuffer: Suitable for a large number of operations in the character buffer under multithreading.

5.2 Example

Taking 10,000 times of string splicing as an example, let's see the time required for each of the three:

String str = "";
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
    str = str + i;
}
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
System.out.println("String消耗时间:" + time);

StringBuilder builder = new StringBuilder("");
startTime = System.currentTimeMillis();
for (int j = 0; j < 10000; j++) {
    builder.append(j);
}
endTime = System.currentTimeMillis();
time = endTime - startTime;
System.out.println("StringBuilder消耗时间:" + time);

StringBuffer buffer = new StringBuffer("");
startTime = System.currentTimeMillis();
for (int k = 0; k < 10000; k++) {
    buffer.append(k);
}
endTime = System.currentTimeMillis();
time = endTime - startTime;
System.out.println("StringBuffer消耗时间:" + time);

operation result:

String消耗时间:258 StringBuilder消耗时间:0 StringBuffer消耗时间:1

Also verified the StringBuilder> StringBuffer> String mentioned above.
#6. Boxing and unboxing

6.1 What is boxing? What is unboxing?

  • Packing: Automatically convert basic data types to wrapper types.
  • Unboxing: Automatically convert the wrapper type to the basic data type.
Integer i = 10; // 装箱
int j = i; // 拆箱

6.2 How is packing and unpacking achieved?

The boxing process is implemented by calling the valueOf method of the wrapper, and the unboxing process is implemented by calling the xxxValue method of the wrapper instance. (Xxx represents the corresponding basic data type).

How to prove this conclusion, we create a new class Main, add the following code in the main method:

package com.zwwhnly.springbootdemo;

public class Main {
    public static void main(String[] args) {
        Integer i = 100;        
        int j = i;
    }
}

Then open the cmd window, switch to the path where the Main class is located, and execute the command: javac Main.java, you will find that the directory will generate a Main.class file, open it with IDEA, you will find the compiled code is as follows:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.zwwhnly.springbootdemo;

public class Main {
    public Main() {
    }

    public static void main(String[] var0) {
        Integer var1 = Integer.valueOf(100);
        int var2 = var1.intValue();
    }
}

6.3 Example

Example 1:

Double i1 = 100.0;
Double i2 = 100.0;
Double i3 = 200.0;
Double i4 = 200.0;

System.out.println(i1==i2);
System.out.println(i3==i4);

Output result:

false

false

Why do all return false? Let's look at the Double.valueOf() method and we will know:

private final double value;

public Double(double value) {
   this.value = value;
}

public static Double valueOf(double d) {
   return new Double(d);
}

Example 2:

Boolean i1 = false;
Boolean i2 = false;
Boolean i3 = true;
Boolean i4 = true;

System.out.println(i1==i2);
System.out.println(i3==i4);

Output result:

true

true

Why do they all return true? Let's look at the Boolean.valueOf() method, and we will know:

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);

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

More selected interview questions:

The Java back-end advanced interview questions necessary for the 2020 interview are summarized as a review guide on Github. The content is detailed, with pictures and texts. Friends who need to learn can star!
GitHub address: https://github.com/abel-max/Java-Study-Note/tree/master

Guess you like

Origin blog.csdn.net/doubututou/article/details/109162302