Two hundred questions about JAVA knowledge (1~30)

java basics

1. What is the difference between JDK and JRE?

1) JDK: the abbreviation of Java Development Kit, java development kit, provides a java development environment and operating environment.
2) JRE: the abbreviation of Java Runtime Environment, java runtime environment, provides the required environment for the operation of java.
3) Specifically, JDK actually includes JRE, as well as javac, a compiler for compiling java source code, as well as many tools for debugging and analyzing java programs. Simply put: if you need to run java programs, you only need to install JRE, if you need to write java programs, you need to install JDK.

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

The effect of the basic type and reference type == is different, as shown below:
• Basic type: compare whether the value is the same;
• Reference type: compare whether the reference is the same;
code example:

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`

Code interpretation : Because x and y point to the same reference, == is also true, and the new String() method rewrites to open up memory space, so the result of == is false, and the comparison of equals is always a value, so The results are all true.
Interpretation of equals :
Equals is essentially ==, but String and Integer rewrite the equals method, turning it into a value comparison. Look at the following code to understand.
First, let’s look at equals comparing an object with the same value by default. The code is as follows:

class Cat {
    
    
    public Cat(String name) {
    
    
        this.name = name;
    }
    private String name;
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
}
Cat c1 = new Cat("jack");
Cat c2 = new Cat("jsck");
System.out.println(c1.equals(c2)); // false

The output is beyond our expectations, it turned out to be false? What is going on, you can see the source code of equals, the source code is as follows:

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

It turns out that equals is essentially ==.
The question is, why do two String objects with the same value return true? code show as below:

String s1 = new String("老王");
String s2 = new String("老王");
System.out.println(s1.equals(s2)); // true

Similarly, when we entered the equals method of String and found the answer, the code is 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;
}

It turns out that String rewrites the equals method of Object, changing reference comparison to value comparison.
Summary : == For basic types is value comparison, for reference types, it is reference comparison; and equals is reference comparison by default, but many classes have renewed the equals method, such as String, Integer, etc. to turn it into Value comparison, so in general, equals compares whether the values ​​are equal.

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

No, the hashCode() of the two objects is the same, and equals() is not necessarily true.
Code example:

String str1 = "通话";
String str2 = "重地";
System.out.println(String.format("str1:%d | str2:%d", str1.hashCode(),str2.hashCode()));
System.out.println(str1.equals(str2));

Execution result:
str1: 1179395 | str2: 1179395
false
code interpretation : Obviously the hashCode() of "call" and "heavy ground" are the same, but equals() is false, because in the hash table, hashCode() is equal to two The hash values ​​of the key-value pairs are equal, but the hash values ​​are equal, and the key-value pairs are not necessarily equal.

4. What is the role of final in java?

• The final modified class is called the final class, which cannot be inherited.
• The final modified method cannot be overridden.
• The final modified variable is called a constant, the constant must be initialized, and the value cannot be modified after initialization.

5. How much is Math.round(-1.5) in java?

Equal to -1, because when taking a value on the number line, the intermediate value (0.5) is rounded to the right, so positive 0.5 is rounded up, and negative 0.5 is directly discarded.

6. Is String a basic data type?

String is not a basic type. There are 8 basic types: byte, boolean, char, short, int, float, long, double, and String is an object.

7. What are the classes of manipulation strings in java? What is the difference between them?

The classes for manipulating strings are : String, StringBuffer, StringBuilder.

The difference between String and StringBuffer and StringBuilder is that String declares immutable objects. Each operation generates a new String object, and then points the pointer to the new String object. StringBuffer and StringBuilder can operate on the basis of the original object. Therefore, it is best not to use String when the content of a string is frequently changed.

The biggest difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe, while StringBuilder is non-thread-safe, but StringBuilder has higher performance than StringBuffer, so StringBuilder is recommended in a single-threaded environment, and StringBuffer is recommended in a multi-threaded environment.

8. Is String str="i" the same as String str=new String("i")?

Not the same , because the memory allocation method is different. String str = "i" way, java virtual machine to be assigned to the constant pool in; and String str = new String ( "i ") will be assigned to the heap memory in.

9. Is String str="i" the same as String str=new String("i")?

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

10. What are the commonly used methods of the String class?

• indexOf(): returns the index of the specified character
• charAt(): returns the character at the specified index.
• replace(): string replacement.
• trim(): Remove blanks at both ends of the string.
• split(): Split a string and return a split string array.
• getBytes(): Returns a byte type array of strings.
• length(): Returns the length of the string.
• toLowerCase(): Convert a string to lowercase letters.
• toUpperCase(): Convert a string to uppercase characters.
• substring(): intercept a string.
• equals(): String comparison.

11. Does an abstract class have to have abstract methods?

No, abstract classes do not have to have abstract methods.
Sample code:

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

In the above code, the abstract class has no abstract methods but can run normally.

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

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

13. Can abstract classes use final modification?

No , the definition of an abstract class is for other classes to inherit. If it is defined as final, the class cannot be inherited. This will cause conflicts with each other. Therefore, final cannot modify the abstract class. As shown in the figure below, the editor will also prompt an error message:
Insert picture description here

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

Implementation : Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement interfaces.
Constructor : Abstract classes can have constructors; interfaces cannot.
Main method : Abstract classes can have a main method, and we can run it; interfaces cannot have a main method.
Number of implementations : A class can implement many interfaces; but can only inherit one abstract class.
Access modifier : The methods in the interface use public modification by default; the methods in the abstract class can be any access modifier.

15. What are the types of IO streams in java?

Divided by function : input stream (input), output stream (output).
Divided by type : byte stream and character stream.
The difference between byte stream and character stream is : byte stream transfers input and output data in bytes according to 8 bits, and character stream transfers input and output data in characters according to 16 bits.

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

BIO : Block IO Synchronous blocking IO, which is the traditional IO we usually use, is characterized by its 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 Channel to achieve multiplexing.
AIO : Asynchronous IO is an upgrade of NIO, also called NIO2, which implements asynchronous non-blocking IO. The operation of asynchronous IO is based on events and callback mechanisms.

17. What are the common methods of Files?

• Files.exists(): Check whether the file path exists.
• Files.createFile(): Create a file.
• Files.createDirectory(): Create a folder.
• Files.delete(): delete a file or directory.
• Files.copy(): Copy files.
• Files.move(): Move files.
• Files.size(): View the number of files.
• Files.read(): Read files.
• Files.write(): write files.

18. What are the java containers?

Catalog of commonly used containers:
Insert picture description here

19. What is the difference between Collection and Collections?

java.util.Collection is a collection interface (a top-level interface of the collection class). It provides common interface methods for basic operations on collection objects. The Collection interface has many concrete implementations in the Java class library. The meaning of the Collection interface is to provide a maximized unified operation mode for various specific collections, and its direct inheritance interfaces are List and Set.
Collections is a tool class/helper class of the collection class, which provides a series of static methods for sorting, searching, and thread-safe operations of the elements in the collection.

20. What is the difference between List, Set and Map?

Insert picture description here

21. What is the difference between HashMap and HashTable?

• HashMap removes the contains method of HashTable, but adds the containsValue() and containsKey() methods.
• HashTable is synchronized, while HashMap is asynchronous, which is more efficient than HashTable.
• HashMap allows empty key values, while HashTable does not.

22. How to decide whether to use HashMap or TreeMap?

For operations such as inserting, deleting, and positioning elements in the Map, HashMap is the best choice. However, if you need to traverse an ordered set of keys, TreeMap is a better choice. Based on the size of your collection, it may be faster to add elements to the HashMap. Change the map to a TreeMap to traverse the ordered keys.

23. Tell me about the implementation principle of HashMap?

HashMap overview : HashMap is an asynchronous implementation of the Map interface based on the hash table. This implementation provides all optional mapping operations and allows the use of null values ​​and null keys. This class does not guarantee the order of the mapping, especially it does not guarantee that the order will last forever.

HashMap data structure : In the java programming language, the most basic structure is two kinds, one is an array , the other is an analog pointer (reference), all data structures can be constructed using these two basic structures, and HashMap is also No exception. HashMap is actually a "linked list hash" data structure, that is, a combination of array and linked list. When we put an element in the HashMap, first recalculate the hash value according to the hashcode of the key, and get the position (subscript) of this element in the array by eliminating the hash value. If the array has already stored other elements at that position, then The element at this position will be stored in the form of a linked list, the newly added will be placed at the head of the chain, and the first added will be placed at the end of the chain. If there is no element at that position in the array, the element will be placed directly at that position of the array.

The implementation of HashMap is optimized in JDK 1.8. When the node data in the linked list exceeds eight, the linked list will be converted to a red-black tree to improve query efficiency, from the original O(n) to O(logn)

24. Tell me about the implementation principle of HashSet?

• The bottom layer of HashSet is implemented by HashMap
• The value of HashSet is stored on the key of
HashMap • The value of HashMap is unified as PRESENT

25. What is the difference between ArrayList and LinkedList?

The underlying data structure of ArrrayList is an array , which supports random access.
The underlying data structure of LinkedList is a two-way circular linked list , which does not support random access.
Using subscripts to access an element, the time complexity of ArrayList is O(1), while LinkedList is O(n).

26. How to realize the conversion between array and List?

• Convert List to Array: call the toArray() method of ArrayList.
• Convert an array to a List: call the asList() method of Arrays.

27. What is the difference between ArrayList and Vector?

Synchronization: Vector is thread-safe, which means that its methods are thread-synchronized, while ArrayList is thread-unsafe. Its methods are not thread-synchronized. If there is only one thread to access the collection, use ArrayList , He does not consider the issue of thread safety, so the efficiency will be higher. If multiple threads access the collection, then use Vector

Data growth : ArrayList and Vector collections have an initial capacity size. When the number of elements exceeds the storage capacity, the storage space of ArrayList and Vector needs to be increased. Each increase is not one but multiple. Vector is Increase the original twice. ArrayList is not explicitly specified, but it can be seen from the source code that ArrayList and Vector can set the initial storage space size by increasing the original 1.5 times. Vector can also set the growth space size, while ArrayList cannot.

28. What is the difference between Array and ArrayList?

• Array can hold basic types and objects, while ArrayList can only hold objects.
• The capacity of Array is fixed, and the capacity of ArrayList is automatically expanded according to demand.
• ArrayList provides methods to add, insert or remove a range of elements, while in Array, only one element value can be obtained or set at a time

29. What is the difference between poll() and remove() in Queue?

Both poll() and remove() remove an element from the queue, but poll() will return null when it fails to get the element, but it will throw an exception when remove() fails.

30. Which collection classes are thread safe?

• Vector: It has one more synchronization mechanism (thread safety) than Arraylist. Because of its low efficiency, it is not recommended to use it now. In web applications, especially the front page, efficiency (page response speed) is often given priority.
• Statck: Stack type, first in, last out.
• HashTable: It is more thread-safe than Hashmap.
• Enumeration: Enumeration, equivalent to iterator.
• All the collection classes under the java.util.concurrent package are ArrayBlockingQueue, ConcurrentHashMap, ConcurrentLinkedQueue, ConcurrentLinkedDeque...

Guess you like

Origin blog.csdn.net/cyb_123/article/details/107523049