4.9K Star Android interview tips Translated an excellent interview question by Mindorks, today brings the answers to 52 questions in the Core Java section. The quality of the topic is relatively high, covering the basic knowledge of Java, object-oriented, collections, basic data types, concurrency, Java memory model, GC, exceptions and so on. In the process of sorting out the answers, I found that I could not remember some knowledge points too clearly, and I sorted out the answers while recalling and learning. All 52 questions that can be verified by code have been verified by me to ensure the accuracy of the answers.

This is a long article, and you can get the Core Java 52 PDF at the end of the article.

Let’s go ahead and ask questions!

Core Java

object-oriented

1. What is OOP?

I don’t think I’ve ever been asked this question, but my first words were “Everything is an object”. Of course, the answer is very open, just explain your understanding of object orientation. Here’s a summary of the answer from Wikipedia:

Object-oriented programming is a programming paradigm with the concept of Object, as well as an abstract approach to program development.

It may contain data, attributes, code, and methods. An object is an instance of a class. It regards the object as the basic unit of the program and encapsulates the program and data to improve the reuse, flexibility and extensibility of the software.

The program in the object can access and frequently modify the data associated with the object. In object-oriented programming, computer programs are designed as objects related to each other.

OOP generally has the following characteristics:

  • Classes and objects

Classes define the abstract characteristics of a thing. The definition of a class contains the form of the data and the operations on the data. For example, the dog class would contain all the basic dog traits, that is, traits or behaviors that are common to all dogs, such as its gestation, coat color, and ability to bark. An object is an instance of a class.

  • encapsulation

Encapsulation refers to OOP that hides the execution steps and implementation details of a method, restricts access to members of that particular class only to objects of that particular class, and usually exposes interfaces for invocation. Everyone knows how to access it, but doesn’t have to worry about its internal implementation details.

For example, the dog class has the bark () method, which defines exactly how the dog should bark. However, the caller does not know exactly how it barks.

  • inheritance

Inheritance means that, in some cases, a class has subclasses. Subclasses are more specific than the original class (called a parent class). For example, the dog category might have its subcategories sheepdog and Chihuahua.

Subclasses inherit the attributes and behavior of their parent class, and may also contain their own. This means that programmers only need to write the same code once.

  • polymorphism

A Polymorphism is the generation by inheritance of different, related classes whose objects respond differently to the same message. For example, dogs and chickens both have the bark () method, but when the dog bark () is called, the dog barks; Call the crow of the chicken () and the chicken will crow.

In addition to inheritance, interface implementation, method overloading in the same class is also a manifestation of polymorphism.

2. What is the difference between abstract classes and interfaces?

  • Abstract classes can have default method implementations. The interface was not implemented with methods prior to jdk1.8, but can be used after 1.8defaultKeyword definition method implementation
  • Abstract classes can have constructors, but interfaces cannot
  • Use a subclassextendsKeyword to inherit an abstract class. If a subclass is not abstract, it needs to provide implementations of all methods declared in the abstract class. Subclasses use keywordsimplementsTo implement the interface. It needs to provide implementations of all declared methods in the interface
  • Abstract methods can havepublicprotecteddefaultThese modifiers, interface methods default topublic, you can default
  • Fields of an abstract class can use any modifier. The default field in the interface ispublic final
  • Single inheritance multiple implementations
  • An abstract class:is-aIs a continuation of the relationship. Interface:like-aWhat reflects is a kind of function extension relation

3. What is the difference between Iterator and Enumeration?

  • Function interfaces Different Enumeration has only two function interfaces. With Enumeration, we can only read the data of the collection, not modify it.

    Iterator has three function interfaces. In addition to reading data from collections, the Iterator can also delete data.Copy the code
  • Iterator supports fail-fast, but Enumeration does not. Enumeration is an interface added to JDK 1.0. Some of the functions that use it include the Vector and Hashtable classes, which were added in JDK 1.0 and whose purpose is to provide a traversal interface. Enumeration does not support synchronization itself, but it does support synchronization in Vector and Hashtable implementations.

    Iterator was added in JDK 1.2 to provide a traversal interface for collections like HashMap and ArrayList. Iterator supports fail-fast: When multiple threads operate on the contents of the same collection, fail-fast events can be generated. So Enumeration is faster than Iterator.Copy the code

4. Do you agree that portfolio takes precedence over inheritance?

Inheritance is powerful, but problematic, because it violates the principle of encapsulation. Inheritance is appropriate only if there is a subtype relationship between a subclass and a superclass. Even so, inheritance can cause fragility if the subclass and superclass are in different packages and the superclass is not designed for inheritance. To avoid this vulnerability, you can replace inheritance with composition and forwarding mechanisms, especially if there are appropriate interfaces to implement wrapped classes. Wrapper classes are not only more robust than subclasses, they are also more powerful. (That is, decorator mode).

See Effective Java’s 18 composition priorities over Inheritance

5. What is the difference between method overloading and method overwriting?

Methods with the same name but different parameter types in the same class are called method overloading. Overloaded methods are identified at compile time. For each method call, the Java compiler selects overloaded methods based on the declared type of the argument passed in (note the distinction from the actual type).

If a subclass defines a method with the same name as a nonprivate method in the parent class, and the two methods have different parameter types, then both methods in the subclass also constitute an overload. On the other hand, if the method parameters are of the same type, this is the time to distinguish between static methods. If the method is static, the method in the subclass hides the method in the parent class. If the method is not static, the subclass overrides the method of the parent class,

The distinction between overloaded methods is made at compile time, and overloading is also known as static binding, or compile-time polymorphism. Rewriting is called dynamic binding.

6. Which access modifiers do you know? What do they do separately?

The level of access Access control modifier The similar With the package A subclass Different package
public public Square root Square root Square root Square root
The protected protected Square root Square root Square root
The default There are no access control modifiers Square root Square root
private private Square root

7. Can one interface implement another?

Yes, but instead of implements, extends. An interface can inherit from one or more interfaces.

8. What is polymorphism? What is inheritance?

There are compile-time polymorphism (static binding) and runtime polymorphism (dynamic binding) in Java. Method overloading is a form of compile-time polymorphism. Method overwriting is a form of runtime polymorphism.

Another important example of polymorphism is when a parent class references a subclass instance. In fact, polymorphism can be seen in any object that satisfies the IS-A relationship. For example, Cat is a subclass of Animal, so Cat is Animal, which satisfies the IS-A relationship.

Inheritance means that, in some cases, a class has “subclasses.” Subclasses are more specific than the original class (called a parent class). For example, the “dog” class might have subclasses of “sheepdog” and “Chihuahua.” Subclasses inherit the attributes and behavior of their parent class, and may also contain their own. This means that programmers only need to write the same code once.

9. Multiple inheritance of classes and interfaces in Java

In Java, a class cannot inherit from more than one class, but an interface can inherit from more than one interface.

10. What are design patterns?

Design patterns are not expanded here. I recommend a Github project called Java-Design-Patterns. There will be an opportunity to write a separate design pattern later.

Collections and generics

11. Arrays vs ArrayLists

Arrays is a utility class that provides static methods for manipulating, sorting, and finding Arrays.

ArrayList is a dynamic array queue that implements the Collection and List interfaces and provides methods for adding, deleting, and retrieving data.

12. HashSet vs TreeSet

HashSet and TreeSet are implementation classes based on the Set interface. TreeSet is the implementation class of SortedSet subinterface of Set.

A HashSet, implemented based on a hash table, does not guarantee the iteration order of the set, and in particular, it does not guarantee that the order is constant. Null values are allowed. Synchronization is not supported.

TreeSet is implemented based on a binary tree, and its elements are sorted automatically, either in natural order or by the provided comparator, so elements in TreeSet need to implement the Comparable interface. Null values are not allowed.

13. HashMap vs HashSet

HashMap HashSet
The Map interface is implemented The Set interface is implemented
Store key-value pairs Store only objects
Call put() to add elements to the map Call the add() method to add elements to the Set
Use the key object to calculate the hashCode value Using member objects to calculate hashCode values, hashCode can be the same for two objects, so equals() is used to determine the equality of the objects, and returns false if the two objects are different
A HashMap is faster than a HashSet because it uses a unique key to get objects A HashSet is slower than a HashMap

14. Stack vs Queue

A queue is a collection type based on a first-in, first-out (FIFO) policy. The queue stores elements in their relative order: make them enter in the same order as they exit. Queues are extremely common in life and programming, like queues, where the first in is always the first out.

A stack is a collection type based on LIFO. When a foreach statement is used to traverse the elements in the stack, the elements are processed in the opposite order to the order in which they are pushed. Just like our mailboxes, the last ones are always seen first.

Explain generics in Java

16. How is the String class implemented? Why is it designed to be immutable?

The String class is implemented using a char array, but changed to a byte array in JDK 9. Benefits of immutable classes:

  • Immutable classes are simpler.
  • Immutable objects are thread-safe in nature; they do not require synchronization. Immutable objects can be freely shared.
  • Not only can immutable objects be shared, but even their internal information can be shared.
  • Immutable objects provide a lot of build for other objects.
  • The only real disadvantage of immutable classes is that you need a separate object for each different value.

Step into JDK String

Objects and primitive types

17. Why is String immutable?

  • StringfinalClass, cannot be extended
  • private final char value[]Immutable,
  • No modifications have been made to the publicvalue[]The method of

See my article why is String immutable?

18. What is string.intern ()? When to use it? Why?

If the current string exists in the constant pool, the current string is returned directly. If the string is not in the constant pool, it is put into the constant pool and then returned.

Put strings that need to be used heavily at run time into the constant pool.

String. Intern ()

19. List eight basic types

Basic types of The size of the The maximum The minimum value A wrapper class Symbol of the VM
boolean Boolean Z
char 16 bits 65536 0 Character C
byte 8 bits 127 – 128. Byte B
short 16 bits 215– 1 2 –15 Short S
int 32 bits 231– 1 231 Integer I
long 64 bits 263– 1 2 –63 Long J
float 32 bits 3.4028235 e f 3.4028235 e + f Float F
double 64 bits 1.7976931348623157 e+308 1.7976931348623157 e+308 Double D

20. The difference between int and Integer

Ints are basic data types and are usually stored directly on the stack, which is more efficient

Integer is the wrapper type, and the new object is stored in the heap, which consumes resources

21. What is automatic packing and unpacking?

The process of converting a basic data type into a wrapper class is called boxing.

The process of converting wrapper classes to primitive data types is called unboxing.

Prior to Java 1.5, boxing was done manually,

Integer i = new Integer(10);
Copy the code

Java 1.5 provides automatic unpacking and automatic packing functions. When unpacking and packing are required, the automatic conversion will be carried out.

Integer i =10;  // Automatic boxing
int b= i;     // Automatic unpacking
Copy the code

The automatic boxing is implemented using integer.valueof (), and the automatic unboxing of Integer is implemented using integer.intValue.

For more information on Java primitives, see my summary article: Getting into the JDK and Talking about primitives

22. Type conversion in Java

Assignment and method call conversion rules: Automatic conversion from low type to high type; A cast is required to go from a high-order type to a low-order type:

  1. Booleans cannot be converted to and from other primitive data types;
  2. byteType can be converted toshortintlongfloatdouble
  3. shortCan be converted tointlongfloatdouble
  4. charCan be converted tointlongfloatdouble
  5. intCan be converted tolongfloatdouble
  6. longCan be converted tofloatdouble
  7. floatCan be converted todouble

Basic types and corresponding packaging classes can be automatically converted, which is the principle of automatic packing and folding.

Conversion between two reference types:

  1. A subclass can be directly converted to a parent class or interface type

  2. Converting a parent class to a subclass casts a type and throws a ClassCastException runtime exception if it is not the object at runtime;

23. Java value passing or reference Passing?

Transmission values.

Pass by value means that a copy of the actual parameter is passed to the function when the function is called, so that the actual parameter is not affected if the parameter is changed.

Pass by reference refers to that the address of the actual parameter is directly passed to the function when the function is called. Then the modification of the parameter in the function will affect the actual parameter.

Java calling methods pass copies of argument references.

Why is there only value passing in Java?

24. What is the difference between object instantiation and initialization?

Initialization is the process of creating new objects and allocating memory. A newly created variable must display an assignment, or it will use the value contained in the previous variable stored on the memory region. To avoid this problem, Java assigns default values to different data types:

  • boolean defaults to false;
  • byte defaults to 0;
  • short defaults to 0;
  • int defaults to 0;
  • long defaults to 0L;
  • char defaults to \u0000;
  • Float defaults to 0.0 f;
  • Double defaults to 0.0 d;
  • object defaults to null.

Instantiation is the process of displaying assignments to already-declared variables.

int j;  // Initialized variable (int defaults to 0 right after)
j = 10; // Instantiated variable
Copy the code

25. What are the differences between local variables, instance variables, and class variables?

Local variables exist only in the method that created them; they are stored in stack memory and cannot be referenced outside the method. Java method execution is not register-dependent, but stack frames, and the execution and termination of each method is accompanied by the loading and unloading of stack frames, as well as the creation and release of local variables.

Instance variables, also known as member variables, are declared in a class and exist depending on the class instance. Variable values may be different among different class instances.

A class variable is a static variable that has only one value in all instances of the class. Changing its value in one place will change the value in all instances of the class.

Java memory model and garbage collector

26. What is garbage collector? How does it work?

Before Java and C++ there was a high wall of dynamic memory allocation and garbage collection. People on the outside wanted to get in and people on the inside wanted to get out.

The garbage collector is mainly used to collect unwanted objects from the heap. Java developers just create and use objects, and the JVM automatically allocates and reclaims memory for you.

The JVM determines whether an object is alive through a reachability analysis algorithm. The basic idea of this algorithm is to search down from a series of objects called GC Roots as the starting point, and the search path is called the Reference Chain. When an object is not connected to GC Roots by any Reference Chain (in terms of graph theory, If the object is unreachable from GC Roots, then the object is not available.

Even in the reachability analysis algorithm, unreachable objects are not necessarily dead. At this time, they are temporarily in the probation stage. In order to truly declare an object dead, at least two marking processes must be experienced.

Read chapter 3 garbage Collector and Memory Allocation Strategies in Understanding the Java Virtual Machine for more details.

27. What is the Java Memory model? What principles does it follow? How is its stack organized?

The Java Virtual Machine specification attempts to define a Java Memory Model (JMM) to screen out the differences of Memory access between different hardware and operating systems, so that Java programs can achieve consistent Memory access effect on various platforms. The JMM is a language-level memory model that ensures consistent memory visibility for programmers across compilers and different processor platforms by disallowing certain types of compiler reordering and processor reordering.

An abstract representation of the JMM memory model is as follows:

In Java, all instance fields, static fields, and array elements are stored in heap memory, which is shared between threads. Local variables, method definition parameters, and exception handler parameters are on the stack, are not shared between threads, do not have memory visibility issues, and are not affected by the memory model.

Communication between Java threads is controlled by the JMM, which determines when one thread’s writes to a shared variable are visible to another thread. The JMM provides Java programmers with memory visibility assurance by controlling the interaction between main memory and local memory for each thread.

Read the Art of Concurrent Programming in Java for more details.

28. What is a memory leak and how does Java handle it?

A memory leak is when objects that are no longer being used are not collected by the GC, that is, objects that are reachable in the reachability analysis, but are actually no longer being used in the program. For example, a long-life object refers to a short-life object, so that the short-life object cannot be reclaimed.

Java should not handle memory leaks, we can do more to prevent them and use reasonable means to detect them, such as Android common LeakCanary, see my previous article LeakCanary source code analysis.

29. What are strong references, soft references, weak references, and virtual references?

After JDK 1.2, Java expanded the concept of references into strong references, soft references, weak references, and virtual references, which gradually decreased in strength.

  • Strong references are common references to program code such as Object obj = new Object(). As long as strong references exist, the GC will never reclaim the referenced Object.

  • Soft references are used to describe objects that are useful but not necessary. Objects associated with soft references are listed in the collection scope for a second collection before the system is about to run out of memory. An out-of-memory exception is thrown if there is not enough memory for this collection. After JDK 1.2, a SoftReference class was provided to implement soft references.

  • Weak references are also used to describe non-essential objects, but they are weaker than soft references, and objects associated with weak references only survive until the next GC occurs. When the GC is running, objects associated only with weak references are reclaimed, regardless of whether the current memory is sufficient. After JDK 1.2, WeakReference classes were provided to implement weak references.

  • Virtual references, also known as ghost references or phantom references, are the weakest type of reference relationship. The existence of a virtual reference does not affect the lifetime of an object, nor can an object instance be obtained through a virtual reference. The only purpose of setting up a virtual reference association for an object is to receive a system notification when the object is collected by GC. After JDK 1.2, the PhantomReference class was provided to implement virtual references.

concurrent

30. What is the role of synchronized?

The keyword synchronized can be used to modify methods or in the form of synchronized blocks. It mainly ensures that multiple threads can only have one thread in a method or synchronized block at the same time. It ensures the visibility and exclusivity of thread access to variables.

  • For normal synchronous methods, the lock is the current instance object
  • For statically synchronized methods, the lock is the Class object of the current Class
  • For synchronized method blocks, the lock is an object configured in Synchonized parentheses

What does ThreadPoolExecutor do?

In Java, threads are used to perform asynchronous tasks. The creation and destruction of Java threads requires some overhead, and if we create a new thread for each task to execute, the creation and destruction of these threads consumes a lot of computing resources. At the same time, creating a new thread for each task to execute is a strategy that can eventually crash an application under heavy load.

For a detailed introduction to thread pools, I recommend an article on Concurrent Programming in Java: The Use of Thread pools

32. What does the keyword volatile do?

Volatile is the lightweight synchronized that ensures the visibility of shared variables in multiprocessor development. Volatile modifies a field (a member variable) by telling the program that any access to that variable must be taken from shared memory, and that changes to it must be flushed back to shared memory synchronously. Volatile ensures visibility to all threads accessing the variable.

However, excessive use of volatile is unnecessary because it reduces the efficiency of program execution.

abnormal

33. How does try{} catch{} finally{} work?

The try code block is used to mark code that needs to be monitored for exceptions

A catch block follows a try block to catch an exception of the specified type that is raised within the try block. In addition to declaring the caught exception type, the catch block defines an exception handler for that exception type. In Java, a try block can be followed by multiple catch blocks to catch different exceptions. The Java virtual machine matches exception handlers from top to bottom. Therefore, the type of exception caught by the preceding catch block cannot override the following, or the compiler will report an error.

A finally block follows a try block and a catch block to declare a piece of code that must run. It is designed to avoid skipping some critical cleanup code, such as closing open system resources.

In the bytecode generated by compilation, each method comes with an exception table. Each entry in the exception table represents an exception handler and is made up of Pointers to from, to, target, and the type of exception caught. The value of these Pointers is the Bytecode index (BCI) used to locate the bytecode.

Where, the FROM and to Pointers indicate the scope monitored by the exception handler, such as the scope covered by the try code block. The target pointer points to the starting position of the exception handler, such as the starting position of the catch block.

Finally code blocks can be complicated to compile. The current version of the Java compiler copies the contents of the finally block and places them in the exit of all normal and exception execution paths of the try-catch block.

This is from geek Time taking apart the Java virtual machine.

34. What is the difference between Checked Exception and un-checked Exception?

In Java, all exceptions are instances of the Throwable class or its subclasses. Throwable has two direct subclasses. One is Error, which covers exceptions that the program should not catch. When an Error occurs, its execution state is beyond recovery and the thread or even the virtual machine needs to be terminated. The second subclass is Exception, which covers exceptions that your program might need to catch and handle.

Exception has a special subclass, RuntimeException, which is a run-time Exception, for a situation where the program cannot continue but can be salvageable.

RuntimeException and Error are types of non-checked exceptions in Java. Other exceptions are checked exceptions. In Java syntax, all check exceptions need to be caught explicitly by the program or annotated with the throws keyword in method declarations. Typically, custom exceptions in a program should be check exceptions to maximize compile-time checking by the Java compiler.

This is from geek Time taking apart the Java virtual machine.

other

35. What is serialization? How to do that?

Serialization is the process of converting an object into a byte stream for persistent storage. It can hold the state and data of an object, making it easy to rebuild the object at a particular moment. In Android, the Serializable, Externalizable (implements Serializable), or Parcelable interfaces are commonly used.

Serializable is the easiest to implement, implementing the interface directly. Externalizable can insert some of its own logic during serialization, and given that it is a relic of earlier Versions of Java, it is largely unused today. The recommended use of Parcelable in Android, which is implemented for Android, is 10 times better than Serializable, which uses reflection. Reflection is not only slow, but also creates a large number of temporary objects, leading to frequent GC.

Example:

/** * Implementing the Serializeable interface is all that is required */
public class User implements Serializable {

    private String name;
    private String email;

        public User(a) {}public String getName(a) {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public String getEmail(a) {
            return email;
        }

        public void setEmail(final String email) {
            this.email = email; }}Copy the code

Parcelable needs more work:

public class User implements Parcelable {

        private String name;
        private String email;

        /** * Interface that must be implemented and provided as a public CREATOR field * that generates instances of your Parcelable class from a Parcel. */
        public static final Creator<User> CREATOR = new Creator<User>() {

            /** * Creates a new USer object from the Parcel. This is the reason why * the constructor that takes a Parcel is needed. * /
            @Override
            public User createFromParcel(Parcel in) {
                return new User(in);
            }

            /**
             * Create a new array of the Parcelable class.
             * @return an array of the Parcelable class,
             * with every entry initialized to null.
             */
            @Override
            public User[] newArray(int size) {
                return newUser[size]; }};public User(a) {}/** * Parcel overloaded constructor required for * Parcelable implementation used in the CREATOR */
        private User(Parcel in) {
            name = in.readString();
            email = in.readString();
        }

        public String getName(a) {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public String getEmail(a) {
            return email;
        }

        public void setEmail(final String email) {
            this.email = email;
        }

        @Override
        public int describeContents(a) {
            return 0;
        }

        /** * This is where the parcel is performed. */
        @Override
        public void writeToParcel(final Parcel parcel, final int i) { parcel.writeString(name); parcel.writeString(email); }}Copy the code

36. The function of keyword TRANSIENT?

Transient is very simple; its purpose is to keep the member variables it modifies from being serialized during serialization.

37. What are anonymous inner classes?

The anonymous inner class is the only class that does not have a constructor. Because it has no constructor, the use of anonymous inner classes is limited, and most of them are used for interface callbacks. Anonymous inner classes are automatically named Outter$1.class by the system at compile time. In general, anonymous inner classes are used to inherit from other classes or implement interfaces. There is no need to add additional methods, just implementations or overrides of inherited methods.

Click events are the most common type of application on Android.

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

For an object, == is always comparing its memory address. Equals () checks to see if the Object overrides equals(). If not, the equals() method of the parent is called, and if not, all the way back up to the Object class. Look at the equals() method in object.java:

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

In Object, equals equals ==, both compare memory addresses. Let’s look at string.equals () instead of comparing memory addresses:

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;
    }
Copy the code

Instead of comparing the memory address, we are comparing its actual value.

39. What does hashCode() and equals() use?

Equals () is used to determine whether two objects are equal or not. If it is rewritten, it will be judged by the logic of the rewrite.

HashCode () is used to calculate the hashCode of an object. The default implementation returns the memory address of the object as a hashCode, ensuring that different objects return different values. In theory, hashCode can also be used to compare objects for equality. HashCode () is mainly used in hash tables, such as HashMap, HashSet, etc.

When we add object to hash table (such as HashSet, HashMap, etc.), we first call hashCode() method to calculate the hashCode of object. Through the hashCode, we can directly locate the position of object in the hash table (generally, the hashCode is complementary to the size of the hash table). If there is no object at the location, you can insert object directly into the location. If there are objects at that location (possibly more than one, via a linked list), then equals() is called to compare whether those objects are equal to the object. If they are, the object does not need to be saved; If not, the object is added to the linked list.

HashCode must be equal to equals(). Otherwise, hashCode equals and equals() does not guarantee equality.

40. Why can’t an abstract method be called from a constructor?

Constructors do not call abstract methods, or, more precisely, overriding methods.

Let’s start with an example:

public abstract class Super {

    Super(){
        overrideMe();
    }

    abstract void overrideMe(a);
}

public class Sub extends Super {

    private final Instant instant;

    public Sub(a) {
        instant = Instant.now();
    }

    @Override
    void overrideMe(a) {
        System.out.println(instant);
    }

    public static void main(String[] args) {
        Sub sub=newSub(); sub.overrideMe(); }}Copy the code

Final print result:

Null T02:2019-04-01 said. 947 zCopy the code

Null is printed the first time because the overrideMe method is called by the Super constructor before the constructor Sub has had a chance to initialize the Instant domain. Notice that the program observes a final field in two different states.

The constructor of the superclass runs before the constructor of the subclass, so methods that override the version in the subclass will be called before the constructor of the subclass runs. If the override version of the method depends on any initialization performed by the subclass constructor, the method will not perform as expected.

41. When do you use the final keyword?

For a final variable, if it is of a primitive data type, its value cannot be changed once initialized; If a variable is a reference type, it cannot be made to point to another object after it is initialized.

In addition, external local variables used in anonymous inner classes can only be final variables.

When a final variable is a basic data type and a String, the compiler uses it as a compile-time constant if its exact value is known at compile time.

The final modifier is also used to emphasize that parameters cannot be changed.

Final decorates a class to indicate that it cannot be inherited.

Analysis of Java final keywords

42. What is the difference between final, finally and Finalize?

Never mind final and finally. Focus on Finalize.

If a Finalize method is overridden ina class, the Finalize method may be triggered when the class object is recycled. Effective Java makes it clear that finalize methods are usually unpredictable, dangerous, and generally unnecessary.

Not only does the JVM not guarantee that Finalize methods will be executed in time, but it does not guarantee that they will be executed at all. So don’t rely on Finalize methods to do things like release resources. Object collection may be delayed, resulting in performance loss.

43. What is the static keyword in Java?

Static is a way to call (method/variable) without creating an object.

  • Static methods are called static methods. Because static methods can be accessed without any object, there is no such thing as this for static methods, because there is no object attached to them. And because of this feature, non-static member variables and non-static member methods of the class cannot be accessed in static methods, because non-static member methods/variables must depend on the specific object to be called.

  • Static variables are also called static variables. The difference between static and non-static variables is that static variables are shared by all objects and have only one copy in memory, which is initialized if and only if the class is first loaded. Non-static variables are owned by the object, initialized when the object is created, and have multiple copies that do not affect each other.

  • Another key use of the static keyword is to form static blocks of code to optimize program performance. Static blocks can be placed anywhere in a class, and there can be more than one static block in a class. When the class is first loaded, each static block is executed in the same order as the static block, and only once when the class is loaded.

Static member variables are initialized in the order defined.

44. Can static methods be overridden?

You can rewrite it, but it’s not polymorphic, it’s not really a rewrite. The static method of a subclass hides the static method of its parent class. There is no relationship between the two methods. The specific method is called depending on which object is called. Only ordinary method calls can be polymorphic.

45. How does a static code block work?

A static code block executes as the class is loaded, and only once.

Static code blocks are compiled and placed in < Clinit >, which is invoked when the JVM first loads the class file, including static variable initialization statements and static block execution.

46. What is reflection?

Reflection is one of the features of Java that allows a running Java program to retrieve information about itself and manipulate the internal properties of a class or object.

Oracle’s official explanation for reflection is:

Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. It also allows programs to suppress default reflective access control.

In short, reflection allows us to obtain information about the members and members of each type of program or assembly at run time. The typical object type in a program is determined at compile time, whereas Java reflection can dynamically create objects and call their properties, and the type of such objects is unknown at compile time. So we can use reflection to create objects directly, even if the type of the object is unknown at compile time.

The core of reflection is that the JVM dynamically loads classes or invokes methods/accesses properties at run time, and it doesn’t need to know who the running object is beforehand (at code writing or compile time).

Java reflection provides the following functions:

Determine the class of any object at run time; Construct an object of any class at runtime; Determine which member variables and methods any class has at run time (you can even call private methods through reflection); Call a method of any object at run time

Deep Java reflection

The smart tip of an IDE is to use reflection.

47. What is dependency injection? How many libraries are there? Have you used it?

Easy to understand Dependency injection (DI) and Inversion of Control (IOC) in Java development

48. How does StringBuilder avoid the assignment problem of immutable Strings?

StringBuilder maintains a variable-length char[] internally to store and concatenate strings, thus avoiding the problem of frequently creating strings because strings are immutable classes.

49. What is the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder are basically the same in use. StringBuffer is thread-safe with the synchronized keyword, whereas StringBuilder has no synchronization. Therefore, using StringBuilder is more efficient when determining the wireless program synchronization problem.

50. Enumeration and an Iterator?

Repeat. Go to problem 3.

51. The difference between fail-fast and fail-safe?

The Fail-fast mechanism, when traversing a collection, throws Concurrent Modification Exceptions when the collection structure is modified. Iterators access internal data directly during traversal, so internal data cannot be repaired during traversal. To ensure that it is not modified, the iterator maintains a flag “mode” inside. The flag “mode” is changed when the collection structure changes (adding, deleting, or modifying), and each time the iterator’s hasNext() and next() methods check whether this “mode” is changed. Concurrent Modification Exception is thrown when Modification is detected.

Fail – safe any changes of collection structure will modify on a replica of the collection, therefore ConcurrentModificationException.

The fail-safe mechanism has two problems:

  1. The collection needs to be copied, resulting in a large number of invalid objects and high overhead

  2. There is no guarantee that the data read is currently in the original data structure

52. What is NIO?

The NIO(New Input/ Output) class was introduced in JDK 1.4, introducing a channel – and buffer-based I/O approach that uses Native libraries to allocate out-of-heap memory directly. It then operates via a DirectByteBuffer object stored in the Java heap as a reference to this memory, avoiding copying data back and forth between the Java heap and Native heap.

NIO is a synchronous non-blocking IO model. Synchronous means that the thread continuously polls for I/O readiness. Non-blocking means that the thread can do other tasks while waiting for the I/O. The core of synchronization is Selector, which polls IO events instead of the thread itself, avoiding blocking and reducing unnecessary thread consumption. The core of non-blocking is the channel and buffer, which can be written to when an IO event is ready to succeed without a thread blocking.

In-depth understanding of Java NIO

End

This article was first published on wechat public number: Bingxin said, focus on Java, Android original knowledge sharing, LeetCode problem solving, welcome to pay attention to!

Wechat search bingxin said, or scan code to follow, reply to Core Java to receive all answers PDF documents.