At present, there are two problems with the interview questions on the market. First, the questions are too old and have not been updated for a long time, and they are still in the state before 2010. In recent years, the JDK has been updated and released quickly, the usage of Java has changed a lot, and the Java technology stack has added many new frameworks, such as Spring Boot, Spring Cloud, etc., but there are few similar interview questions.

Compared to these questions, my 208 interview questions have the following advantages:

  1. Extracting the most classic interview questions from each Java module;
  2. The answers were accurate and I had proofread each question carefully.
  3. Close to the real enterprise interview, the topic is practical and effective;
  4. Difficult topic, I added code analysis and principle analysis.

Combined with the above characteristics, it can be seen that FOR the “Java most common 200+ interview questions” this article, I spent a lot of effort, only one purpose to provide a best and most complete set of Java interview questions on the market.

Here are the questions and answers to the first part of the “Java Basics” module.

Java based

1. What is the difference between JDK and JRE?

  • JDK: Short for Java Development Kit, the Java Development Kit provides the Java Development environment and runtime environment.
  • JRE: Short for Java Runtime Environment. It provides the required Environment for Running Java.

Specifically, the JDK actually contains the JRE, as well as the compiler javac that compiles Java source code, as well as many tools for debugging and analyzing Java programs. Simply put: if you need to run Java programs, just install the JRE, and if you need to write Java programs, install the JDK.

2. What is the difference between == and equals?

= = interpretation

The effect is different for the base type and the reference type ==, as shown below:

  • Basic type: compares whether the values are the same;
  • Reference type: Compares whether references are the same;

Code examples:

String x = "string";
String y = "string";
String z = new String("string");
System.out.println(x==y); // true
System.out.println(x==z); // false
System.out.println(x.equals(y)); // true
System.out.println(x.equals(z)); // true
Copy the code

Since x and y refer to the same reference, == is also true, while the new String() method overwrites the memory space, so == is false, and equals always compares values, so it is true.

Equals reading

Equals is essentially equal to ==, except that String and Integer and others have overridden the equals method to make it a value comparison. Take a look at the code below.

First, equals compares an object with the same value by default, as follows:

class Cat {
    public Cat(String name) {
        this.name = name;
    }

    private String name;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Cat c1 = new Cat("Wang lei");
Cat c2 = new Cat("Wang lei");
System.out.println(c1.equals(c2)); // false
Copy the code

The output is false to our surprise. Equals equals equals equals equals equals equals equals equals equals equals equals equals equals

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

Equals is essentially equal to ==.

Why do two strings with the same value return true? The code is as follows:

String s1 = new String("Wang");
String s2 = new String("Wang");
System.out.println(s1.equals(s2)); // true
Copy the code

Similarly, when we go to String equals, we find the answer as follows:

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;
}
Copy the code

String overrides Object’s equals method, changing reference comparison to value comparison.

Summary: == is a value comparison for primitive types and a reference comparison for reference types; Equals by default is a reference comparison, but many classes have redone equals (String, Integer, etc.) as a value comparison, so in general equals compares whether or not values are equal.

3. If two objects have the same hashCode(), equals() must also be true, right?

HashCode () is the same for both objects and equals() is not necessarily true.

Code examples:

String str1 = "Call";
String str2 = "Important";
System.out.println(String.format("| str2 str1: % d: % d",  str1.hashCode(),str2.hashCode()));
System.out.println(str1.equals(str2));
Copy the code

Results of execution:

Str1:1179395 | str2:1179395

false

HashCode () is the same as hashCode(), but equals() is false, because in a hash table hashCode() equals the hash values of two key-value pairs. However, the hash values are equal, which does not necessarily result in the key-value pairs being equal.

4. What does final do in Java?

  • Classes that are final are called final classes and cannot be inherited.
  • Final methods cannot be overridden.
  • A final variable is called a constant, which must be initialized, after which its value cannot be changed.

5. How much is math.round (-1.5) in Java?

Is equal to -1, because the median value (0.5) is rounded to the right on the number line, so plus 0.5 is rounded up, and minus 0.5 is discarded.

6. Is String a basic data type?

Strings are not part of the base type. There are eight basic types: byte, Boolean, char, short, int, float, long, and double. Strings are objects.

7. What are the classes for manipulating strings in Java? What’s the difference between them?

Classes that operate on strings are: String, StringBuffer, StringBuilder.

The difference between String and StringBuffer and StringBuilder is that String declares an immutable object. Each operation generates a new String and then points to a new String. StringBuffer and StringBuilder can operate on existing objects, so it’s best not to use strings if you’re constantly changing the contents of strings.

The big difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe and StringBuilder is non-thread-safe, but StringBuilder performs better than StringBuffer, So StringBuilder is recommended for single-threaded environments and StringBuffer is recommended for multi-threaded environments.

Is String STR =” I “the same as String STR =new String(” I “)?

No, because memory is allocated differently. String STR =” I “, which the Java virtual machine allocates to the constant pool; String STR =new String(” I “) will be allocated to the heap.

9. How to reverse a string?

Use the Reverse () method of StringBuilder or stringBuffer.

Sample code:

// StringBuffer reverse
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("abcdefg");
System.out.println(stringBuffer.reverse()); // gfedcba
// StringBuilder reverse
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("abcdefg");
System.out.println(stringBuilder.reverse()); // gfedcba
Copy the code

What are the common methods of the String class?

  • IndexOf () : returns the indexOf the specified character.
  • CharAt () : Returns the character at the specified index.
  • Replace () : string replacement.
  • Trim () : Removes whitespace at both ends of a string.
  • Split () : Split string, returns a split array of strings.
  • GetBytes () : Returns a byte array of strings.
  • Length () : Returns the length of the string.
  • ToLowerCase () : converts the string toLowerCase.
  • ToUpperCase () : converts a string toUpperCase characters.
  • Substring () : intercepts a string.
  • Equals () : String comparison.

11. Must abstract classes have abstract methods?

No, abstract classes don’t have to have abstract methods.

Sample code:

abstract class Cat {
    public static void sayHi(a) {
        System.out.println("hi~"); }}Copy the code

In the code above, the abstract class does not have abstract methods but works perfectly fine.

12. What are the differences between ordinary classes and abstract classes?

  • Ordinary classes cannot contain abstract methods. Abstract classes can contain abstract methods.
  • Abstract classes cannot be instantiated directly; ordinary classes can be instantiated directly.

13. Can abstract classes use final?

If an abstract class is defined as final, the class cannot be inherited. This conflicts with each other. Therefore, final cannot modify an abstract class, as shown in the following figure.

What is the difference between an interface and an abstract class?

  • Implementation: Subclasses of abstract classes inherit using extends; Interfaces must be implemented using IMPLEMENTS.
  • Constructors: Abstract classes can have constructors; No interface exists.
  • Main method: Abstract classes can have main methods and we can run them; An interface cannot have a main method.
  • Number of implementations: A class can implement many interfaces; But only one abstract class can be inherited.
  • Access modifiers: Methods in an interface use the public modifier by default; Methods in abstract classes can be arbitrary access modifiers.

15. How many IO streams are there in Java?

According to functions, it can be divided into: input and output.

By type: byte stream and character stream.

The difference between a byte stream and a character stream is that a byte stream transmits input and output data in bytes in 8 bits, while a character stream transmits input and output data in characters in 16 bits.

16. What is the difference between BIO, NIO and AIO?

  • BIO: Block IO Synchronous blocking IO is the traditional IO that we usually use. It is characterized by simple mode and convenient use, and low concurrent processing capability.
  • NIO: New IO synchronous non-blocking IO is an upgrade of traditional IO. The client and server communicate through channels, realizing multiplexing.
  • AIO: Asynchronous IO is an upgrade of NIO, also known as NIO2, which implements Asynchronous non-blocking I/O operations based on events and callbacks.

17. What are the common methods of Files?

  • Files.exists() : checks whether a file path exists.
  • Files.createfile () : Creates a file.
  • Files.createdirectory () : Creates a folder.
  • Files.delete() : Deletes a file or directory.
  • Files.copy() : copies Files.
  • Files.move() : moves a file.
  • Files.size() : Displays the number of Files.
  • Files.read() : Reads Files.
  • Files.write() : writes Files.

Scan the QR code below to get all the answers

Related articles recommended:

Java most common 200+ interview questions