Want to see the commonly used written test questions in JAVA? Let you take a look at these 22 classics today!

Insert picture description here

1. Which of the following are methods of the Thread class ()

A start() B run() C exit() D getPriority()

Answer: ABD

Analysis: Look at the Java API docs: http://docs.oracle.com/javase/7/docs/api/, exit() is a method of the System class, such as System.exit(0).

2. The following statement about java.lang.Exception class is correct ()

A inherited from Throwable B Serialable CD I don’t remember, it’s not correct anyway

Answer: A

Analysis: The base classes of Java exceptions are java.lang.Throwable, java.lang.Error and java.lang.Exception inherit Throwable, RuntimeException and other Exception inherit Exception, and specific RuntimeException inherit RuntimeException.
Extension: the difference between error and exception (Error vs Exception)

  1. java.lang.Error: A subclass of Throwable, used to mark serious errors. Reasonable applications should not try/catch such errors. The vast majority of errors are abnormal and should not have occurred at all.
    java.lang.Exception: A subclass of Throwable, used to indicate a reasonable program to catch conditions. That is, it is only a program running condition, not a serious error, and user programs are encouraged to catch it.

  2. Error and RuntimeException and their subclasses are unchecked exceptions, while all other Exception classes are checked exceptions.
    checked exceptions: usually thrown from a program that can be restored , And it is best to be able to use the program to recover from such anomalies. Such as FileNotFoundException, ParseException, etc. The checked exception occurs in the compilation stage, try...catch (or throws) must be used otherwise the compilation fails.
    Unchecked exceptions: usually exceptions that shouldn't have occurred if everything is normal, but they do occur. Occurs in the runtime, with uncertainty, mainly due to the logic problems of the program. Such as ArrayIndexOutOfBoundException, ClassCastException, etc. From the perspective of the language itself, programs should not catch such exceptions. Although it can catch and recover from exceptions such as RuntimeException, terminal programmers are not encouraged to do so, because it is completely unnecessary. Because this type of error is itself a bug and should be fixed, the program should stop executing immediately when such an error occurs. Therefore, in the face of Errors and unchecked exceptions, the program should be automatically terminated. Programmers should not do things such as try/catch, but should find out the reason and modify the code logic.

RuntimeException: The RuntimeException system includes incorrect type conversion, array out-of-bounds access, and attempt to access a null pointer, etc.

The principle of handling RuntimeException is: if RuntimeException occurs, it must be the programmer's error. For example, you can avoid array out-of-bounds access exceptions by checking array subscripts and array boundaries. Other (IOException, etc.) checked exceptions are generally external errors, such as trying to read data from the end of the file, etc. This is not an error in the program itself, but an external error in the application environment.

3. The running result of the following program is ()

String str1 = “hello”;
String str2 = “he” + new String(“llo”);
System.err.println(str1 == str2);
答案:false

Analysis: Because the llo in str2 is a newly applied memory block, and == judges the address of the object instead of the value, so it is different. If it is String str2 = str1, then it is true.

4. Which of the following statements are correct ()

A. The constructor in the class cannot be omitted

B. The constructor must have the same name as the class, but the method cannot have the same name as the class

C. Constructor is executed when an object is new

D. A class can only define one constructor

Answer: C

Analysis: There may be misunderstandings here. In fact, ordinary class methods can have the same name as the class name. The only difference from the construction method is that the construction method does not return a value.

5. I don't remember the specific options, but the knowledge used is as follows:

String []a = new String[10];

Then: a[0]~a[9] = null

a.length = 10

If it is int []a = new int[10];

则: a [0] ~ a [9] = 0

a.length = 10

6. The running result of the following program: ()

public static void main(String args[]) {
    
    
 
    Thread t = new Thread() {
    
    
 
        public void run() {
    
    
            pong();
        }
    };
 
    t.run();
    System.out.print("ping");
 
}
 
static void pong() {
    
    
 
    System.out.print("pong");
 
}

A pingpong B pongping C Both pingpong and pongping may not output D

Answer: B

Analysis: The difference between the start() and run() methods in the Thread class is considered here. start() is used to start a thread. When the start method is called, the system will start a new thread, and then call the run() method to perform tasks, and calling run() alone is the same as calling a normal method. The characteristics of threads have been lost. Therefore, you must use start() instead of run() when starting a thread.

7. The following are relational databases ()

A. Oracle B MySql C IMS D MongoDB

Answer: AB

Answer: IMS (Information Management System) database is one of the two database types developed by IBM;

One is relational database, a typical representative product: DB2;

The other is the hierarchical database, which represents the product: IMS hierarchical database.

Non-relational databases include MongoDB, memcachedb, Redis, etc.

8. Is the GC thread a daemon thread? ()

the answer is

Analysis: Threads are divided into daemon threads and non-daemon threads (ie user threads).

As long as any non-daemon thread in the current JVM instance does not end, the daemon thread will all work; only when the last non-daemon thread ends, the daemon thread will finish working with the JVM.
The most typical application of daemon threads is GC (garbage collector)

9. Does the volatile keyword guarantee thread safety? ()

Answer: No

Analysis: The volatile keyword is used in multi-thread synchronization to ensure the visibility of reads. The JVM only ensures that the value loaded from the main memory to the thread working memory is the latest read value, not in the cache. But multiple threads

Volatile write operations cannot guarantee thread safety. For example, if thread 1 and thread 2 are performing read and load operations and find that the value of count in the main memory is 5, then this latest value will be loaded. After the heap count of thread 1 is modified, it will be written to the main memory. The count variable in the main memory will become 6; thread 2 has already performed read and load operations, and after the calculation, the variable value of the count in the main memory will also be updated to 6; resulting in two threads being modified with the volatile keyword in time , There will still be concurrency.

10. Which of the following statements is correct ()

A LinkedList inherits from List

B AbstractSet inherits from Set

C HashSet inherits from AbstractSet

D WeakMap inherits from HashMap

Answer: AC

Analysis: The following is a downloaded Java collection type inheritance diagram, at a glance.

11. Is there a number such that i + 1 <i ()

Answer: Exist

Analysis: If i is an int type, then when i is the largest integer that int can represent, i+1 will overflow and become a negative number. At this time, isn't it <i?

Extension: Is there a number that makes i> j || i <= j not true ()

Answer: Exist

Analysis: For example, Double.NaN or Float.NaN, thanks to @BuilderQiu netizens for pointing them out.

12. The data type of 0.6332 is ()

A float B double C Float D Double

Answer: B

Analysis: The default is double type, if it is float type, you need to add f display description, that is, 0.6332f

13. Which of the following stream classes belong to character-oriented input streams ()

A BufferedWriter B FileInputStream C ObjectInputStream D InputStreamReader

Answer: D

Analysis: There are two ways of IO operations in Java: byte-oriented (Byte) and character-oriented (Character).
Byte-oriented operations are operations on binary data in 8-bit units, and no data conversion. These classes are all subclasses of InputStream and OutputStream.
Character-oriented operations are operations on data in units of characters, converting binary data into characters when reading, and converting characters into binary data when writing. These classes are all subclasses of Reader and Writer.

Summary: The suffixes with InputStream (input)/OutputStream (output) are byte streams;

      以Reader(输入)/Writer(输出)为后缀的是字符流。

Extension: Java flow class diagram structure, clear at a glance, to solve most multiple-choice questions:
Insert picture description here
14. Java interface modifier can be ()

A private B protected C final D abstract

Answer: CD

Analysis: The interface is very important, in order to illustrate the situation, here is a little bit windy:

(1) The interface is used to describe all the services provided by the system, so the member constants and methods in the interface must be public (public) to ensure that external users can access them;

(2) The interface only describes what the system can do, but does not specify how to do it, so the methods in the interface are abstract (abstract) methods;

(3) The interface does not involve details related to any specific instance, so the interface has no construction method, cannot be instantiated, no instance variables, only static variables;

(4) The variables in the interface are shared by all implementation classes. Since they are shared, they must be unchanged, because changed things cannot be considered as shared. So the variable is of immutable (final) type, that is, constant.

(5) Can't define variables in the interface? If the interface can define variables, but the methods in the interface are abstract, the properties cannot be modified by behavior in the interface. Some people will say that it doesn't matter, you can modify the properties of the interface through the behavior of the object that implements the interface. This is of course no problem, but consider such a situation. If there is a static variable a with public access permission in interface A. According to the semantics of Java, we can access the variable a without the object that implements the interface. Through Aa = xxx; we can change the value of the variable a in the interface. Just as this can be done in an abstract class, all objects that implement interface A will automatically have the value of a after the change. That is to say, if a is changed in one place, the value of a in all these objects will follow. changed. What is the difference between this and abstract classes? How to reflect the higher abstraction level of the interface, how to reflect the unified protocol provided by the interface, and what is the abstraction of the interface? Therefore, variables cannot appear in the interface. If there are variables, it conflicts with the unified abstraction provided by the interface. Therefore, the attributes in the interface must be constants, which can only be read but not changed, so as to provide a unified attribute for the objects that implement the interface.

In layman's terms, what you think is to be changed should be placed in your own implementation, not in the interface. The interface is only a higher-level abstraction of the properties and behavior of a class of things. It is closed for modification and open for extension (different implementations). The interface is a manifestation of the principle of opening and closing.

and so:

The method of the interface is public abstract by default;

Variables can not be defined in the interface, that is, only constants can be defined (plus final modification will become constants). Therefore, the properties of the interface are public static final constants by default, and initial values ​​must be assigned.

Note: Final and abstract cannot appear at the same time.

15. Can an object be created without a constructor ()

A yes B no

Answer: A

Analysis: Several ways of creating objects in Java (important):

(1) Use the new statement to create an object. This is the most common way to create an object.
(2) Using reflection means, call the newInstance() instance method of java.lang.Class or java.lang.reflect.Constructor.
(3) Call the clone() method of the object.
(4) Using deserialization means, call the readObject() method of the java.io.ObjectInputStream object.

(1) and (2) will explicitly call the constructor; (3) is a copy of an existing object in memory, so the constructor will not be called; (4) is to restore the object of the class from the file, Nor will the constructor be called.

16. ArrayList list = new ArrayList(20); expand the list several times ()

A 0 B 1 C 2 D 3

Answer: A

Analysis: This is a bit confusing. Everyone knows that the default ArrayList length is 10, so if you want to add 20 elements to the list, you must expand it once (expanded to 1.5 times the original), but the display here indicates how much space is needed , So I allocate so much space for you at once, that is, there is no need to expand.

17. Which of the following are symmetric encryption algorithms ()

A DES B AES C DSA D RSA

Answer: AB

Analysis: Commonly used symmetric encryption algorithms are: DES, 3DES, RC2, RC4, AES

Commonly used asymmetric encryption algorithms are: RSA, DSA, ECC

Encryption algorithm using one-way hash function: MD5, SHA

18. To create a new stream object, which of the following options is wrong? ()

A)new BufferedWriter(new FileWriter(“a.txt”));

B)new BufferedReader(new FileInputStream(“a.dat”));

C)new GZIPOutputStream(new FileOutputStream(“a.zip”));

D)new ObjectInputStream(new FileInputStream(“a.dat”));

Answer: B

Analysis: Do you remember the picture in question 13? Reader can only be instantiated with FileReader.

19. Can the following program run normally ()

public class NULL {

public static void haha(){
    System.out.println("haha");
}
public static void main(String[] args) {
    ((NULL)null).haha();
}

}
Answer: It can run normally

Analysis: The output is haha, because the null value can be coerced to any java class type, and (String)null is also legal. However, after the null coercion is an invalid object, its return value is still null, and the call of the static method is bound to the class name, so it can be output correctly without accessing the object. Conversely, if there is no static modification, you can only use the object to access it. Calling the object with null will definitely report a null pointer error. This is very similar to C++. Thanks to @Florian netizens for answering.

class HelloA {
    
    
 
    public HelloA() {
    
    
        System.out.println("HelloA");
    }
     
    {
    
     System.out.println("I'm A class"); }
     
    static {
    
     System.out.println("static A"); }
 
}
 
public class HelloB extends HelloA {
    
    
    public HelloB() {
    
    
        System.out.println("HelloB");
    }
     
    {
    
     System.out.println("I'm B class"); }
     
    static {
    
     System.out.println("static B"); }
     
    public static void main(String[] args) {
    
     
     new HelloB(); 
   }
 
}

answer:

static A
static B
I’m A class
HelloA
I’m B class
HelloB

Analysis: To be honest, I think this question is very good, examine the static statement block, the construction statement block (that is, the block with only the braces) and the execution order of the constructor.

Object initialization sequence: (1) After the class is loaded, execute the statement modified by static from top to bottom (from parent class to subclass); (2) After the static statement is executed, execute the main method; (3) If a statement new its own object, the construction code block and constructor (the two can be said to be bound together) will be executed from top to bottom.

Let's slightly modify the above code to explain the situation more clearly:

class HelloA {
    
    
 
    public HelloA() {
    
    
        System.out.println("HelloA");
    }
     
    {
    
     System.out.println("I'm A class"); }
     
    static {
    
     System.out.println("static A"); }
 
}
 
public class HelloB extends HelloA {
    
    
    public HelloB() {
    
    
        System.out.println("HelloB");
    }
     
    {
    
     System.out.println("I'm B class"); }
     
    static {
    
     System.out.println("static B"); }
     
    public static void main(String[] args) {
    
    
 
        System.out.println("-------main start-------");
        new HelloB();
        new HelloB();
        System.out.println("-------main end-------");
    }
}

The output at this time is:

static A
static B
-------main start-------
I’m A class
HelloA
I’m B class
HelloB
I’m A class
HelloA
I’m B class
HelloB
-------main end-------

20. The getCustomerInfo() method is as follows. Three types of exceptions can be caught in try. If an IOException occurs during the operation of the method, what results will be output ()

public void getCustomerInfo() {
    
    
 
    try {
    
    
 
        // do something that may cause an Exception
 
    } catch (java.io.FileNotFoundException ex) {
    
    
 
        System.out.print("FileNotFoundException!");
 
    } catch (java.io.IOException ex) {
    
    
 
        System.out.print("IOException!");
 
    } catch (java.lang.Exception ex) {
    
    
 
        System.out.print("Exception!");
 
    }
 
}

A IOException!

BIOException!Exception!

CFileNotFoundException!IOException!

DFileNotFoundException!IOException!Exception!

Answer: A

Analysis: Examine the execution order of multiple catch statement blocks. When multiple catch statements are used, the catch statement blocks are in order. The exception types are matched in sequence from the front catch statement block, so that if the parent exception is before the child exception type, the parent exception type will be matched first, and the child exception type will not get a chance to match, that is, the child exception type The catch statement block in which it is located will be an unreachable statement. Therefore, the parent exception class, Exception boss, is generally placed at the end of the catch statement block.

21. The running result of the following code is: ()

import java.io.*;
import java.util.*;
 
public class foo{
    
    
 
    public static void main (String[] args){
    
    
 
        String s;
 
        System.out.println("s=" + s);
 
    }
}

The A code is compiled, and output "s="

The B code is compiled and output "s=null"

C Because String s is not initialized, the code cannot be compiled

The D code is compiled, but a NullPointException is caught.
Answer: C

Analysis: At first I thought it would output null or something, but after running it found that all basic types or objects defined in Java must be initialized to output values.

  1. System.out.println("5" + 2); The output result should be ().

A 52 B7 C2 D5

Answer: A

Analysis: There is nothing to say, Java will automatically convert 2 to a string.

22. Point out the result of the following program operation ()

public class Example {
    
    
 
    String str = new String("good");
 
    char[] ch = {
    
     'a', 'b', 'c' };
 
    public static void main(String args[]) {
    
    
 
        Example ex = new Example();
 
        ex.change(ex.str, ex.ch);
 
        System.out.print(ex.str + " and ");
 
        System.out.print(ex.ch);
 
    }
 
    public void change(String str, char ch[]) {
    
    
 
        str = "test ok";
 
        ch[0] = 'g';
 
    }
}

A、 good and abc

B、 good and gbc

C、 test ok and abc

D, test ok and gbc
Answer: B

End of sentence

These are some very, very basic questions, which I wrote down from memory after I recently participated in the written test of major IT companies. After sorting out, they are dedicated to the students who participated in the recruitment of major IT campuses like me. They are pure Java basic skills, veterans. There is no need to come in, so as not to laugh at us children who have not left school, but IT companies like to test these basic things. I spent a lot of time sorting out, and I learned a lot during the sorting process. Please take every question seriously~~~
This is the end of this sharing about JAVA questions. If you are not satisfied with reading it, I will also organize my collection. More than 20 years of interview knowledge points organized by companies, and various Java core knowledge points are shared with you for free. If you want information, please click here to sign qf.
Insert picture description here

Guess you like

Origin blog.csdn.net/SpringBoot_/article/details/108858301
Recommended