Several Java interview questions every day: object-oriented operating mechanism (first day)


Friendly reminder

The questions at the back are very boring. Some dramatic scenes and story characters are added to deepen the memory. PS: Click the article directory to jump directly to the specified location of the article.

Act 1,

Scene 1) In front of the downstairs gate of a building

[Guard A, Guard B, interviewer Lao Wang, passers-by, etc.]

Guard A: Who is coming? Give your name.

Lao Wang: Lao Wang next door came for an interview

Guard B: There are many people interviewing for Java now. If everyone is accepted, I’m afraid the president will blame us. Please talk about 1. The cross-platform principle of Java
. If you answer the right questions, go in for the interview.

Lao Wang: This company is quite interesting. The doorman became the interviewer.Java's cross-platform implementation is the role of the JVM (Java Virtual Machine). Once a Java bytecode is compiled, it does not need to be recompiled when it is switched to a different platform. The premise is that the corresponding platform is installed on these platforms. JVM, JVM is not cross-platform.

Guard A: I also have a question. 2. Let’s talk about Java’s garbage collection mechanism
. By the way, I’ll buy a popsicle, and Lao B will bring one for you.

Lao Wang: Bring me a Zhongxue Gao and I will tell you about the garbage collection mechanism;
The garbage collector usually runs as a separate low-level thread to clear and recycle objects in the memory heap that have died or have not been used for a long time. Programmers cannot call the garbage collector in real time to clean an object or all objects. Perform garbage collection. The garbage collector cannot reclaim memory immediately. It can manually execute System.gc() to notify the GC to run. However, the Java language specification does not guarantee that the GC will be executed. The recycling mechanism includes:
① Generational copy garbage collection.
Objects with different life cycles can be collected in different ways. Those with longer life cycles such as Session objects, threads, and Socket connections in Http requests. Those with a relatively short life cycle such as String objects. Generational recycling places objects with different life cycles in different generations, including the young generation, the old generation, and the persistent generation. Therefore, the garbage collection areas and times are also different.
② Mark garbage collection
Using the mark clear algorithm, when the memory is exhausted, the program will be suspended and garbage collection will begin. The program will continue to execute when all unreferenced objects have been cleaned up. The mark-and-sweep algorithm consists of two phases:
the marking phase, where all accessible objects are marked.
During the collection phase, the garbage collection algorithm scans the heap and reclaims all unmarked objects.
③Incremental garbage collection
solves the long pause problem of mark clearing. The incremental collector divides the stack into multiple domains and collects garbage from only one domain at a time. This causes minor application disruption.

Guard B: Actually, I don’t know if what you said is right, but it’s a bit too much for you to read it on your mobile phone. I put my phone away and ask you a simple question. 3.The principle mechanism of JVM loading class files?

Lao Wang: I don’t know

Guard B: If I tell you to put away your phone, you won’t know, right? Let me tell you.The compiled Java source program is not an executable program, but one or more class files. The JVM will ensure that this class is loaded, connected (verified, prepared and parsed) and initialized.
①Class loading: The class loader and its subclasses find and load the classes in the class file at runtime, and read the data in the .class file into the memory.
② Connection phase: After loading is completed, enter the connection phase, including three steps: verification, preparation (allocating memory for static variables and setting default initial values) and parsing (replacing symbolic references with direct references).
③Finally, the JVM initializes the class, including: if the class has a parent class, initialize the parent class first, and there are initialization statements in the class, then execute these initialization statements in sequence.

Guard B: After I finish speaking, do you agree or disagree?

Lao Wang: I agree. You have always asked me, and I will also ask you this: 4. Brother Janitor, how much do you know about Java memory?

Guard B: Normally I don’t show off my knowledge easily, but since you asked the question sincerely, I will show it off:
①Java memory is divided into heap and stack. A thread in Java will have a corresponding thread stack. The Main function is the starting point of the stack and the starting point of the program, which is the entry point for program execution.
② The stack is the unit of runtime, which stores basic data types and references to objects in the heap, as well as information related to the current program (local variables, program running status, methods, method return values), etc., while the heap is the unit of storage, which stores object information. Such as object properties.
③The stack solves the running problem of the program, that is, how the program is executed (running logic), or how to process data. The heap solves the problem of data storage, that is, how and where to put the data.
④The separation of the heap and the stack allows the content in the heap to be shared by multiple stacks, providing an effective data interaction method and saving space.
⑤ Since the stack can only grow upward, it will limit the stack's ability to store content, and the objects in the heap can grow dynamically as needed. Therefore, the splitting of the stack and the heap makes dynamic growth possible. Only records in the corresponding stack are required. An address in the heap will do.

Guard A: You are back.

Guard B: It’s me who’s back, not you. Can I eat popsicles during working hours? Lao Wang, please tell me 5. Why not put basic types in the heap?

Guard A: Quick answer:Because the space occupied by basic types is generally 1 to 8 bytes, there will be no dynamic growth - the length is fixed, so storing it on the stack is enough. There is no point in storing it in the heap.

Guard B: Did I ask you? It’s conspicuous. Lao Wang answers 6. Is parameter passing in Java by value? Or pass a reference?

Guard A: Quick answer:Object transfer is by reference value (the address value of the reference is transferred), and basic data type transfer is by value.

Lao Wang: Can I go in? Overeating is bad for my appetite, and being interviewed by the doorman without restraint will only make me miss the interview time. ——By the way, give me the popsicle.

Doorman A/B: Do you want cake? If you want to go in, just go in.

Scene 2) In the elevator

[Lao Wang, cleaning company owner, cleaning aunt]

Boss: You have done a good job in cleaning the company. But various other matters still require you to come to the office alone to discuss and work out alone. I know you have little experience in this area, so let me ask you a question first: 7. What is your understanding of object-oriented thinking?

Cleaning aunt: If you want to be fired, just say it, why bother with this? Unfortunately, I memorized the interview questions yesterday:Object-oriented programming, referred to as OOP technology, uses many code modules. Each module only provides specific functions. They are independent of each other, which can increase the chance of code reuse and is more conducive to software development, maintenance and upgrades. In addition, the three core features of OOP: inheritance, encapsulation, and polymorphism enable the design of a highly cohesive and low-coupling system structure based on object-oriented programming, making the system more flexible, easier to expand, and lower in cost. Therefore, this programming idea is currently the most commonly used software design idea.

Boss: It seems you still have some skills: 8. Let’s talk about the three major characteristics of object-oriented

Lao Wang: Let me answer first:
① Encapsulation
Encapsulation is to encapsulate the code describing the properties and behavior of an object in a "module", that is, a class. The properties are defined with variables and the behavior is defined with methods. Methods can directly access the properties of the same object.
②Inheritance
Inheritance is a mechanism for subclasses to share parent class data and methods. This is a relationship between classes that improves the reusability and scalability of software. When defining or implementing a class, you can do it on the basis of an existing class. You can use the content defined by the existing class as your own content, and you can add new content or modify the original method to use it. Which is more suitable for special needs, this is inheritance.
③Polymorphism
Polymorphism refers to the multiple running states of the same object at different times in the program. It means that the parent class reference points to the child class object. When calling the method, the implementation of the child class will be called instead of the implementation of the parent class. Different subclasses inherit the same parent class. When we use parent class reference variables to call methods in these different subclass objects, we call it polymorphism.
In order to make polymorphism run, there is an inheritance or implementation relationship.
The object of the subclass can be assigned to the parent class/interface, and parameters can be passed in polymorphic form, which enhances the flexibility of parameter types.
Advantages and Disadvantages of Polymorphism:
Advantages: The existence of polymorphism improves the scalability and later maintainability of the program
Disadvantages: Although it can be used in advance, it can only access the functions already in the parent class, and the functions of the later subclasses are run. Functional content. Unique functionality defined in a subclass cannot be used in advance.
Polymorphic application scenario: When the interface has been determined, but the same interface requires different implementations in different environments. Such as: factory mode

Boss: Who are you? I’m still rushing to answer, but it looks like I answered well. Come and work in the cleaning company.

Lao Wang: Talking wildly.

Cleaning aunt: Boss, I want to resign to interview for Java.

Scene 3) In the corridor

[Cleaning aunt, Lao Wang]

Cleaning aunt: "The evening rain sprinkles on the river sky to cleanse the autumn. The frost and wind are getting colder and colder, and the Guanhe River is desolate, and the remaining light shines on the building. The red and green trees in this place are declining, and everything is in bloom. Only the water of the Yangtze River flows eastward in silence. I can't bear it. Climbing high and looking far away, looking at the dimness of my hometown, I can't bear to think about it. I sigh at the traces of the past years, why I have been so miserable. I miss the beautiful lady, look up at the makeup building, I miss it a few times, and I know the boat is back in the sky. Fighting to know me, leaning on the railing, I am concentrating. "Sorrow." Please ask: 9. How many ways are there to output this poem in reverse order?

Lao Wang: This topic turns corners too fast. I searched on Baidu and found four methods:
①Use toCharArray() of the String class to output the array in reverse order.

/*
	 * 利用String类的toCharArray(),再倒序输出数组的方法
	 */
	private static void reverseString1(String str) {
    
    
		char[] chr = str.toCharArray();
		for (int i = chr.length-1 ; i >= 0; i--) {
    
    
			System.out.print(chr[i]);
		}
		System.out.println("\t");
	}
	

② Use the subString() method provided by the String class to output the reverse string using recursion.

/*
	 * 利用String类提供的subString()方法,利用递归的办法输出倒序字符串。
	 */
	private static void reverseString2(String str) {
    
    
		if (str.length() == 1)
			System.out.println(str);
		else {
    
    
			String subString1 = str.substring(0, str.length() - 1);
			String subString2 = str.substring(str.length() - 1);
			System.out.print(subString2);
			reverseString2(subString1);
		}
	}

③Define a StringBuffer class and use the reverse() method in the StringBuffer class to directly reverse the string.

/*
	 * string倒序输出 
	 * 定义成一个StringBuffer类,用StringBuffer类中的reverse()方法直接倒序字符串。
	 * 2018-5-18 13:22:10
	 */
	private static void reverseString3(String str) {
    
    
		StringBuffer buffer = new StringBuffer(str);
		System.out.println(buffer.reverse());
	}

④Use the "+" feature of the string concatenation symbol

public class MyTest {
    
    
   public static void main(String[] args) {
    
    

        String s = "对潇潇暮雨洒江天";
        String s2 = "";

        for (int i = s.length() - 1; i >= 0; i--) {
    
    
            s2 += s.charAt(i);
        }
        System.out.println(s2);
    }
    }
}

Cleaning aunt: Do you have a partner? I see that your basic knowledge of Java is very solid. How about introducing 10.Java object initialization sequence ?

Lao Wang: For a second I thought I was going to be single. The Java object initialization sequence is as follows:
① The first is the initialization of this class
, static variables, static initialization blocks, variables, initialization blocks, constructors
② The second is the initialization sequence containing the parent class.
Parent class static variables, parent class static initialization block, subclass static variables, subclass static initialization block, parent class variables, parent class initialization block, parent class constructor, subclass variables, subclass initialization block, subclass constructor.

Lao Wang: Let me ask you a question as courtesy. Java classes all have a common ancestor class, which is Object. What are the methods in 11.Object:

Cleaning aunt: Of course I know:
protected Object clone() Creates and returns a copy of this object.
boolean equals(Object obj) Indicates whether some other object is "equal" to this object.
Class<?> getClass() Returns the runtime class of this Object.
int hashCode() Returns the hash code value of this object.
void notify() Wakes up a single thread waiting on this object's monitor.
void notifyAll() Wakes up all threads waiting on this object monitor.
String toString() Returns the string representation of this object.
void wait() Causes the current thread to wait before other threads call the notify() method or notifyAll() method of this object.

Lao Wang: 12. What is the difference between method overloading and rewriting? Can the Overload method change the type of return value?

Cleaning aunt:
Overload is overloading, and Override is overwriting, that is, rewriting.
①Overload
means that there can be multiple methods with the same name in the same class, but the parameter lists of these methods are different (that is, the number or type of parameters are different). Whether the return value type can be changed, in the definition of overloading, has nothing to do with the type of return value of the method
② Overriding
means that the method in the subclass can have the same name and parameters as a method in the parent class, through the subclass When the instance object created by the class calls this method, it will call the method defined in the subclass. This is equivalent to rewriting the exact same method defined in the parent class. This is also a type of polymorphism in object-oriented programming. Performance. When a subclass overrides a method of the parent class, it can only throw fewer exceptions than the parent class, or it can throw a child exception of the exception thrown by the parent class. The access rights of the subclass method can only be greater than that of the parent class. Can't be smaller.

Cleaning aunt: The true meaning of interviews is: that is, after recognizing the truth of interviews, you still love interviews. After realizing the cruelty of work, he still lived a beautiful life. Good luck.

Guess you like

Origin blog.csdn.net/baomingshu/article/details/132760073