Java language practice answer 03

1. Which of the following cannot be used to handle thread safety

  • synchronized keyword
  • volatile keyword
  • Lock class
  • transient keyword

Correct answer D answer analysis
Let's take a look at the function of the transient keyword
The variable cannot be serialized
Variables modified by transient cannot be serialized
Cannot be read after deserialization again


class UserInfo implements Serializable {
    private static final long serialVersionUID = 996890129747019948L;
    private static String name;
    private transient String psw; // The password cannot be serialized

    public UserInfo(String name, String psw) { = name;
        this.psw = psw;

    public String toString() {
        return "name=" + name + ", psw=" + psw;
public class Test {
    public static void main(String[] args) {
        UserInfo userInfo = new UserInfo("Zhang San", "123456");
        try {
            //The property set to transient is not serialized
            ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("User cache.txt"));
            //Write content
        } catch (Exception e) {
        try {
            //Change the value of name before deserialization
            //Reread content
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("User cache.txt"));
            UserInfo readUserInfo = (UserInfo) in.readObject();
            //The content of the deserialized read psw is null
        } catch (Exception e) {

2. The argument of volatile keyword is wrong

  • Thread safety can be guaranteed
  • volatile keyword is used in multi-threaded synchronization to ensure the visibility of reading
  • The JVM guarantees that the value loaded from main memory to thread working memory is up to date
  • volatile prevents instruction reordering

Correct answer A answer analysis
First understand the following concepts
Atomicity: an operation cannot be interrupted. Either all operations succeed or all operations fail, such as bank transfer
Order: the order of program execution is in the order of code
Visibility: when multiple threads access the same variable, one thread modifies the value of the variable, and other threads can immediately see the modified value
Instruction rearrangement: This is a compiler optimization. It does not guarantee that the execution order of each statement in the program is consistent with that in the code, but it will ensure that the final execution result of the program is consistent with that of the code. When the instruction rearrangement is considered, the data dependency is considered. Statement 2 depends on the value of statement 1, and statement 1 will be executed before statement 2

What does the volatile operation do

Instruction rearrangement optimization is prohibited
It ensures the visibility when different threads operate on this variable, that is, when a thread modifies a variable value, the new value is immediately visible to other threads
Atomicity is not guaranteed (leading to thread insecurity)

Although the incremental operation (x + +) looks like a single operation, in fact, it is a combined operation composed of read modify write operation sequence, which must be executed in an atomic way. volatile cannot provide the necessary atomic characteristics and can not guarantee that it will not be disturbed by other threads during the operation
To achieve the correct operation, you need to keep the value of x unchanged during the operation, which cannot be achieved by volatile variables

Volatile is used to limit that variables can only be read from the cache (working memory) to ensure that the values are consistent for all threads, but it cannot be said that volatile can ensure thread safety
synchronized ensures atomicity and visibility

3. Which of the following is not a java class loading process

  • Generate Java Lang.class object
  • Assign default values to int type object member variables
  • Execute static block code
  • Class method parsing

Correct answer B answer analysis
Wrong. It's not an object member variable, it's a class member variable
Object member variables are initialized by constructors
This also involves the content of JVM, which is described too much here

4. What is the correct description of anonymous inner class? ( )

  • Anonymous inner classes can inherit a base class and cannot implement an interface
  • Anonymous inner classes cannot define constructors
  • Anonymous inner classes cannot be used for arguments
  • None of the above is true

Correct answer B answer analysis
Since the constructor name must be the same as the class name, and the anonymous class has no class name, the anonymous class cannot have a constructor
Then look at what anonymous inner classes are

In the process of using anonymous inner classes, we need to pay attention to the following points:
 1,When using anonymous internal classes, we must inherit a class or implement an interface, but we can't have both. At the same time, we can only inherit a class or implement an interface.
 2,Constructors cannot be defined in anonymous inner classes.

 3,There cannot be any static member variables or static methods in an anonymous inner class.

 4,Anonymous inner classes are local inner classes, so all restrictions on local inner classes also apply to anonymous inner classes.

 5,An anonymous inner class cannot be abstract. It must implement all abstract methods of the inherited class or the implemented interface.
The creation format of anonymous inner class is: new parent class constructor (parameter list) | implementation interface () {/ / class body implementation of anonymous inner class}
public class HelloWorldAnonymousClasses {
     * HelloWorld interface with two methods
    interface HelloWorld {
        public void greet();
        public void greetSomeone(String someone);

    public void sayHello() {

        // 1. The local class EnglishGreeting implements the HelloWorld interface
        class EnglishGreeting implements HelloWorld {
            String name = "world";
            public void greet() {
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hello " + name);

        HelloWorld englishGreeting = new EnglishGreeting();

        // 2. Anonymous classes implement the HelloWorld interface
        HelloWorld frenchGreeting = new HelloWorld() {
            String name = "tout le monde";
            public void greet() {
                greetSomeone("tout le monde");
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Salut " + name);

        // 3. Anonymous classes implement the HelloWorld interface
        HelloWorld spanishGreeting = new HelloWorld() {
            String name = "mundo";
            public void greet() {
            public void greetSomeone(String someone) {
                name = someone;
                System.out.println("Hola, " + name);


    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses();

5. The correct description of the following codes is
 class StaticStuff{
     static int x=10;
     static { 
     public static void main(String args[ ]){
         System.out.println("x=" + x);
     static { x/=3;}
  • Lines 3 and 9 cannot be compiled because the method name and return type are missing
  • Line 9 cannot be compiled because there can only be one static initializer
  • The compilation passed, and the execution result is: x=5
  • The compilation passed, and the execution result is: x=3

Correct answer C answer analysis
First of all, this question is a rare multiple-choice question with only one correct choice
First review the loading order of Java initialization
Parent static member variable parent static code block subclass static member subclass static code block
Parent class non static member parent class non static code block parent class constructor
Subclass non static member subclass non static code block subclass construction method

6. In the Java language, which of the following statements is the correct statement to create an array? ( )

float f[][] = new float[6][6];
float []f[] = new float[6][6];
float f[][] = new float[][6];
float [][]f = new float[6][6];
float [][]f = new float[6][];

Correct answer ABDE easy to choose wrong answer ABCD analysis
It's easy to mix with C language
C language is the second dimension and must be given
Java is the first dimension and must be given

7. The result of running the following Java program is

public class Tester{
public static void main(String[] args){
   Integer var1=new Integer(1);
   Integer var2=var1;
public static void doSomething(Integer integer){
    integer=new Integer(2);
  • 1true
  • 2true
  • 1false
  • 2false

Correct answer A answer analysis
Look at the code below

class SimInt{
    int value;
    public SimInt(int value){
public class Main{
    public static void change1(SimInt si){
        si=new SimInt(3);//Re pointing to the new object, the original object is not affected
    public static void change2(SimInt si){
        si.value=3;//By referring to the internal members of the operation object, the original object is changed
    public static void main(String args[]) {
	SimInt si1=new SimInt(1);
        System.out.println(si1.value);//Output 1
        System.out.println(si1.value);//Output 1
       System.out.println(si1.value);//Output 3

8. The following statement is correct

  • Calling the sleep() method of Thread will release the lock, and calling the wait() method will not release the lock
  • When a thread calls the yield method, it can make the thread with the same priority get the processor
  • In Java, high priority runnable threads will preempt the resources of low priority threads
  • In java, a thread can call the yield method to run a thread with a lower priority than itself

Correct answer BC answer analysis
yield() returns the currently running thread to the runnable state, allowing other threads with the same priority to get the chance to run. Therefore, the purpose of using yield() is to enable proper rotation between threads with the same priority.
However, in practice, there is no guarantee that yield() will achieve the purpose of concession, because the concession thread may be selected again by the thread scheduler

I still remember Mr. Ma said that the yiled method belongs to the behavior of high moral integrity. I won't go to this pit. Those at the same level with me go to the bathroom first
The high priority is your county magistrate. The county magistrate needs to go to the bathroom. Sorry, you have to come out. The county magistrate goes first. After the county magistrate goes to the bathroom, the CPU is allocated to you, and then you can continue to go to the bathroom

9. The following description of JAVA exception class is correct ()

  • Inheritance structure of Exception: the base classes are Throwable,Error and Exception. Implement Throwable, RuntimeException, IOException and other inherited exceptions
  • Non RuntimeException is usually an external Error (regardless of Error), which can be caught by the try{}catch statement block in the current class
  • The error class system describes the internal errors and resource exhaustion in the Java running system. Error does not need to be caught
  • The RuntimeException system includes incorrect type conversion, array out of bounds access, trying to access null pointers, etc., which must be caught by the try{}catch statement block

    Correct answer ABC answer analysis

Explain the options one by one

A. There is nothing to say about the base class. Although both Error and Exception implement Throwable, these three are indeed base classes. If I rewrite the second half of the sentence and feel that there is a problem with its text description, I should understand it. Implement Throwable, RuntimeException, IOException and other inherited exceptions
B. Note that Error is not considered in parentheses. This means that all Exception classes under Exception can be caught, except that RuntimeException is basically an external Error, and IOException is a typical one
C. Correct, very simple, slightly explained
D. You can not throw it. Only external errors need to be thrown. Exceptions in java are allowed to be thrown. Remember to use the throw keyword

10. There are several common relationships between classes

  • "USES-A" relationship
  • "HAS-A" relationship
  • "IS-A" relationship
  • "INHERIT-A" relationship

Correct answer ABC answer analysis
USES-A: dependency relationship. Class A will use class B. this relationship is accidental and temporary. However, changes in category B will affect category A
This is reflected in the code: the parameters in class A methods include class B
Association relationship: Class A will use class B, which is a strong dependency and is long-term, not accidental. In the code, the member variables of class a contain class B
HAS-A: aggregation relationship, ownership relationship, is a special case of association relationship, which is the relationship between whole and part. For example, the relationship between a flock of birds and birds is an aggregation relationship. Each part of a flock of birds is a bird, such as the generic type of a set of member variables
IS-A: indicates inheritance. Parent and child classes
LIKE-A: A link-a B, A implements the B interface

Keywords: Java Back-end

Added by Gregghawes on Tue, 01 Mar 2022 09:18:21 +0200