[Java] summary of basic interview questions!

Keywords: Java C# leetcode Interview

1. Why do you have to override the hashcode method when you override the equals method?

equals() and hashCode() are both built-in methods in the Object class. The native equals() uses = = to compare the memory addresses of the two objects. hashCode is a native method. Different objects get different hashcodes.

A subclass of Object, such as String. The equals() method is overridden to treat objects with the same content as the same thing. So why rewrite hashCode()? Because when we use HashMap or HashSet, we call the hashCode () method of the Object, that is, we want two objects with the same content to be regarded as one thing. The native hashCode () will get two different hashCode values, and there will be two elements with the same content in the map or set, which is not what we want. So we need to rewrite the hashCode () method so that all objects with equals as true are regarded as the same thing. Therefore, when rewriting equals, you also need to rewrite hashCode.

2. What are the advantages of object orientation?

Easy maintenance, high quality, high efficiency and easy expansion

Three characteristics of encapsulation inheritance polymorphism

  • Encapsulation: encapsulate objective things into abstract classes; Class can operate its own data and methods on trusted classes or objects to hide information from untrusted ones.
  • Inheritance: you can extend the functions of an existing class without rewriting it.
  • Polymorphism: allows a reference of a parent type to point to an object of a subclass type.

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

Interface? Multiple interfaces can be implemented by implementing a subclass through implements

Abstract class? Inheriting a subclass through extensions can only inherit one abstract class

The methods of an interface can only be abstract methods, and the methods of an abstract class can be abstract methods or ordinary methods. The variables in the interface are modified by public static final by default and need to be assigned initial values. The methods of the interface can only be modified by public, and the variables and methods of abstract classes can be modified by four modifiers.

4. When a subclass inherits the parent class, the method modifier can only be large and the exception thrown can only be small?

The subclass inherits from the parent class, and the modifier of the overridden method can only be greater than or equal to that of the parent class. For example, for the public method of the parent class and the private method of the subclass, when polymorphism is used, the parent class can be compiled, and it is found that the modifier of the subclass method is small at runtime, resulting in contradiction;

The subclass inherits from the parent class, and the exception range thrown by the overridden method can only be less than or equal to the parent class. Otherwise, the exception thrown cannot be resolved by the parent class.

5. What is the difference between int and Integer?

Int basic data type and Integer are classes under the java.lang package. They are encapsulated classes of int. the automatic boxing / unpacking mechanism enables them to convert to each other.

·Integer variable can only be used after instantiation; int variables are not required;

·Integer is actually a reference to an object, pointing to the integer object of new; int is the data value stored directly;

·The default value of Integer is null; The default value of int is 0.

·Integer objects generated through new exist in the heap, and non new generated data are stored in the constant pool;

int a = 100;
int b = 100;
sout(a==b);//true?  The base type compares values
Integer a = new Integer(100);
int b = 100;
sout(a==b);//true?  When integer is compared with int, it is automatically unpacked into int, which is equivalent to the comparison of int and int
Integer a = new Integer(100);
Integer b = 100;
sout(a==b);//false?  One object is in the heap and the other is in the constant pool. Integer compares the address
Integer a = new Integer(100);
Integer b = new Integer(100);
sout(a==b);//false?  Two different objects

6. What is the difference between memory leak and memory overflow?

Memory leak refers to that the program cannot release the applied memory space after applying for memory. The harm of a memory leak can be ignored, but the consequences of memory leak accumulation are very serious. No matter how much memory is, it will be occupied sooner or later.

Out of memory overflow means that the program does not have enough memory space for its use when applying for memory, and out of memory occurs; For example, if you apply for an integer, but save it with a long to save the number, that is, memory overflow.

7. Concept, classification and use of anomalies?

Exception mechanism refers to how the program handles errors. Specifically, the exception mechanism provides a safe channel for program exit. When an error occurs, the process of program execution changes, and the control of the program is transferred to the exception handler.

Throwable can be divided into Exception exception and Error error.
  1. Error is an error that the program cannot handle, indicating a more serious problem in running the application. Such as VirtualMachineError, OutOfMemoryError, etc.

  2. An Exception is an Exception that the program itself can handle. The Exception class has an important subclass RuntimeException, which refers to runtime exceptions, such as NullPointerException (null pointer Exception), indexoutofboundsexception (subscript out of bounds Exception), etc. these exceptions are not checked, and the program can choose to capture and handle them or not. Even if it is not captured with a try catch statement and thrown without a throw clause declaration, it will be compiled.

Non runtime exceptions are also called compilation exceptions. They are exceptions other than RuntimeException. They all belong to Exception class and its subclasses. From the perspective of program syntax, it is an Exception that must be handled. If it is not handled, the program cannot be compiled. Such as IOException, SQLException, and user-defined Exception exceptions. Generally, exceptions are not checked by users.

Exception throw: any Java code can throw exceptions, such as code written by itself, code from Java development environment package, or Java runtime system. Anyone can throw an exception through Java's throw statement. Any exception thrown from a method must use the throws clause.

Exception capture: exception capture is realized by try catch statement or try catch finally statement.

8. Concept, classification and basic method of IO flow?

IO, i.e. in and out, i.e. input and output, refers to data transfer between applications and external devices. Common external devices include files, pipes and network connections.

Stream is an abstract concept. It refers to a series of data (characters or bytes). It is a channel that sends information in a first in first out manner.

There are three main types of IO streams:

  1. According to the direction of data flow: input flow and output flow
  2. By processing data unit: byte stream, character stream
  3. By function: node flow, processing flow



Basic method:

  1. Main methods of byte input stream InputStream:
read() : Read a data byte from this input stream.
read(byte[] b) : The maximum number of entries from this input stream b.length Bytes of data are read into a byte Array.
read(byte[] b, int off, int len) : The maximum number of entries from this input stream len Bytes of data are read into a byte Array.
close(): Close this input stream and release all system resources associated with the stream.
  1. Main methods of byte output stream OutputStream:
write(byte[] b) : take b.length Bytes from specified byte The array is written to the output stream of this file.
write(byte[] b, int off, int len) : Will specify byte Offset from array off Beginning len Bytes are written to this file output stream.
write(int b) : Writes the specified byte to this file output stream.
close() : Close this input stream and release all system resources associated with the stream.
  1. Main methods of character input stream Reader:
read(): Read a single character.
read(char[] cbuf) : Reads characters into an array.
read(char[] cbuf, int off, int len) :  Reads characters into a part of an array.
read(CharBuffer target) : An attempt was made to read a character into the specified character buffer.
flush() : Flush the buffer of the stream.
close() : Close this stream, but refresh it first.
  1. Main methods of character output stream Writer:
write(char[] cbuf) : Write character array.
write(char[] cbuf, int off, int len) : Writes a part of a character array.
write(int c) : Write a single character.
write(String str) : Write string.
write(String str, int off, int len) : Writes a part of a string.
flush() : Flush the buffer of the stream.
close() : Close this stream, but refresh it first.

Read and write of byte stream

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOTest01 {
    public String read(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int length;

        while((length=fis.read(b))!=-1){
            sb.append(new String(b,0,length));
        }
        return sb.toString();
    }
    public void write(File file) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        String s="Eat grapes without spitting grape skin";
        fos.write(s.getBytes());
        fos.flush();
        fos.close();
    }
}

Read and write of character stream (common)

import java.io.*;

public class IOTest {
    public String read(File file) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
        char[] c = new char[1024];
        StringBuilder sb = new StringBuilder();
        int length;

        while((length=isr.read(c))!=-1){
            sb.append(c,0,length);
        }

        isr.close();
        return sb.toString();
    }

    public void write(File file) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
        String s="Eat grapes without spitting grape skin";
        osw.write(s);
        osw.flush();;
        osw.close();
    }
}

Posted by wisewood on Mon, 13 Sep 2021 14:20:26 -0700