Java Interview Summary (a)--interview Frequently asked the keyword summary

Source: Internet
Author: User
Tags volatile

Key words:

    • Final Finalize finally
    • Throws and throw
    • The role of the static keyword
    • Abstract and interface
    • Super and this
    • Synchronize and volatile
1. Final Finalize finally comparison

(1) different properties

    • Final is the key word;
    • Finalize () as the method;
    • Finally is the chunk flag, which is used in a try statement;

(2) different functions

    • Final: The keyword used to identify the constant, and the final identified keyword is stored in a constant pool (where the concrete usage of the final constant is described below); the value of the final definition is immutable, the method is not writable, and the class is not inheritable .
      • Define variables: Once initialized (in the declaration or constructor), it cannot be changed. For a base type whose value is immutable, the reference type is not variable; (string is the final one)
      • Definition method: 1) Using the method of final definition, does not allow overwrite, think its function satisfies the requirement does not need to expand, 2) allows the compiler to convert all calls to this method into an inline (inline mechanism), that is, you can copy this method directly at the call, rather than make a routine method call (save breakpoint, pressure stack) to increase efficiency. But if too much, will cause code expansion, but will affect efficiency, use with caution.
      • Defining a class: Cannot be inherited, which means that the class is a leaf class in an inheritance tree, and that a class member is either final or not.

    • Finalize (): The method is defined in object to be invoked by the JVM when the object "disappears" for garbage collection of objects, similar to a destructor in C + +, which frees up resources used by objects (such as i/0 operations) when the user is customized;
    • finally{}: Used to identify code blocks, with try{} to complement the exception handling model, whether the code in the try or not finished (in this case, there is an exception), the code block of the program must be done, not alone, in a try...catch ... There is at most one finally in the finally statement block, which is typically used to maintain the internal state of the object and clean up non-memory resources.

2. Throws and throw comparison

(1) different use location

    • The throw is inside the method body and can be used as a separate statement;
    • Throws is located behind the parameter list of the method head and cannot be used alone;

(2) different contents

    • Throw throws a specific exception object, and can only be one;
    • Throws declaration throws the exception class, you can declare more than one;

(3) different functions

    • Throw is used to throw an exception in the program, and once the execution instructions are thrown, the exception is handled by the inner statement of the method body;
    • Throws is used to declare an exception class that may be thrown within the method, and if an exception is thrown, it is handled by the caller of the method and thrown on the layer;

Summary: When a function is called, if you need to throw an exception to the upper layer, you must explicitly declare (throws Exception1, Exception2) The exception type at the head of the function, and if you only need to handle the exception inside the method body, you can handle the exception yourself inside the method body , Thorw throws a specific exception instance (catch (Exception1 e) {...} ).

3. The role of the static keyword

The static keyword can be used to modify properties, methods, and blocks of code in order to relate the object to a class-related, that is, the non-static members are object-dependent, owned by a single object, and the member of the static modifier is a class member that can be called directly through the class name and owned by all objects.

The static modified member variables and member methods are customarily referred to as static variables and static methods, which can be accessed directly through the class name, and Access syntax is:

    • Class name. static method Name (parameter list ...)
    • Class name. Static variable Name

(1) Static modifier attribute (class variable, static variable)

    • A variable that is modified by static, called a static variable or a class variable, can be accessed directly through the class name; A variable that is not modified by static is called an instance variable.
    • A static variable is shared by all objects of this class, and instance variables belong to only a single object.
    • Static variables have only one copy in memory, are created and initialized when the class is loaded , and the JVM allocates only one memory (saving memory). The class loading process occurs only once, so the static variable is only created once, the instance variable is initialized when the object is created , there are multiple copies in memory , and each object is created with one memory, and each instance variable has no effect (flexibility).

As a result, static variables are typically used when you need to implement the following two functions:

1). When sharing values between objects, 2). Easy access to variables

(2) Static modification method (static method)

    • Static modified method, called the method, can be directly accessed by the class name, for all objects of this class share;
    • Static methods cannot access non-static members of this class (including instance variables and methods, because non-static is associated with a particular object and cannot be shared entirely), but non-static methods can access static members (ofcourse, static members, All-class sharing);
    • The This and Super keyword cannot appear in a static method (because this is a pointer to the current object, super (). Member name calls the parent class member);
    • Because the static method is independent of any instance, the static method must be implemented, not abstract;
    • When a subclass overrides a static method of a parent class, it can only still be overwritten as a static method (a day static lifetime static), but there is no polymorphism.

The reason why the main method must be static in Java:

Objects cannot be created while the class is loading, and static methods can be called without objects, so the program can be run through the main method portal when the class is loaded.

(3) Static modifier code block (initialization block, static code block)

Format: static{...}

A static block of code is also called a code block, which is an independent block of static blocks in a class that is separate from a class member, can have more than one position, it is not in any method body, and the JVM executes these static blocks of code when the class is loaded, and if there are multiple static blocks of code, The JVM executes them sequentially in the order in which they appear in the class, and each code block is executed only once.

Initialization summary (static variable, instance variable, execute constructor by declaration initialization)

1) When using a class for the first time, the JVM finds the appropriate class file and loads It (Java will only load the corresponding class file incrementally if necessary)

The storage space is first allocated for all static variables and initialized to the default values (global variables), followed by the order of the initialization actions specified when the static variable is declared, and the order in which the statements in the static initialization block appear in the class definition. These static initialization actions are performed only once when the class file of the class to which they belong is loaded.

2) After the class file has been loaded, if you need to create an object of the class, initialize the following action

The JVM allocates enough storage space for all instance variables and initializes them to default values (local variables), and then the initialization action that specifies the initial value when declaring an instance variable, and the statements in the instance initialization block are executed sequentially in the order in which they appear in the class, and then the corresponding constructor method is called.

4. Abstract and interface contrast

Stract class and interface are two mechanisms that support abstract class definitions. It is the existence of these two mechanisms that gives Java a powerful object-oriented capability. There is a great similarity between the abstract class and the interface in support of the definition of the abstraction classes, the difference:

Abstract class Interface
Instantiation of No No
Class Abstract classes can generally be used only as base classes for other classes. A class can have only one heavy inheritance relationship. A class can implement multiple interface
Data members Can have a private, default is the friendly type, its value can be redefined in the subclass, can also be re-assigned, can be non-abstract Not private, default is public static final type, and must be assigned the initial value, the implementation class can not be redefined, cannot change its values.
Method members Can be private, can have non-abstract methods, must implement Not private, default is Public,abstract type
Design concept Represents a "is-a" relationship Represents a "like-a" relationship
Realize Need to inherit, to use extends Need to implement, with implements

Abstract class:

(1) can only be used as a base class for other classes and cannot be instantiated (new);

(2) It is not necessary for a member of an abstract class not to be abstract. (You can have abstract members, or you can have no abstract members)

(3) Abstract classes cannot be final at the same time. The abstract always wants to be inherited, and the final class cannot be inherited. Final and abstract cannot exist simultaneously.

(4) A non-abstract class inherits an abstract class and must overwrite all its abstract members . Abstract classes inherit abstract classes and can not overwrite all abstract members.

(5) Abstract class allows to be declared

Interface (interface):

The essence of an interface is a special abstract class that describes all the services that the system provides to the outside.

(1) In the interface, all methods are open and abstract: publicabstract. (both must be inherited)

(2) In an interface, all properties are public, static, constant: Staticfinal, and must be assigned an initial value. (All implementation classes are shared and cannot be changed)

Interfaces are always expected to be accessed, so all members must be public, ensuring access to the outside world. The interface only describes what the system can do, but does not specify how to do it, the implementation of the operation is done by the class, so the method is abstract, must be inherited; the interface does not involve any implementation details, so there is no construction method, the interface cannot be instantiated , no variables, Only static constants (static final) are shared by all implementation classes, and the inheritance of classes can only be inherited, but interfaces may be implemented more than once, separated by ",".

5. Super and this comparison

Super

Super can be understood as a pointer to a parent class object, referring to a parent class closest to itself.

Usage:

    • Super. Member name (variable name or method name ()): explicitly invokes a member of the same name of the parent class, but the member cannot be private (no subclass access is allowed). Because when a child class and parent class have a member of the same name, because the child class has a higher precedence, the corresponding member of the parent class is hidden.
    • Super (parameter list): call the constructor of the parent class, and note that the Super statement must be placed first in the body of the function:

This

This can be understood as a pointer to the current object itself, that is, the object instance that is currently executing this method. is inside the function body.

Usage:

    • This . Member name: reference member variable. Because a function parameter or a local variable in a function has the same name as a member variable, the member variable is masked and the member variable needs to be referenced by using the "this. Member variable" method.
    • This (parameter list); : Call another constructor that is consistent with the parameter table in this class , and note that it should be the first statement in the constructor.

When referencing a constructor:

Super (parameter): Call Parent ClassOne of the constructors (which should be the first statement in the constructor). This (parameter): Call This classThe other form of the constructor (which should be the first statement in the constructor).

This and super are not required to be declared.

6. Synchronize and volatile contrast

(1) Scope of action: volatile can only be used at variable levels; Synchronized can be used at variable, method, and class levels;

(2) The volatile nature is to tell the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory; Synchronized is the lock of the current variable, and other threads are blocked only if the variable is accessible to the front-thread.

(3) volatile does not cause thread blocking, and synchronized can cause thread blocking.

(4)volatile can only synchronize the value of a variable between the thread memory and the main memory, while synchronized synchronizes the values of all variables between the thread memory and the main memory, implemented by locking and releasing the listener.

(5) Volatile tag variables are not optimized by the compiler; Synchronized tagged variables can be optimized by the compiler

(6) Obviously,synchronized is more expensive than volatile in performance.

(7)volatile can only realize the change of the visibility of variables, not guaranteed atomicity, while synchronized can guarantee the change of the variable visibility and atomicity

For detailed synchronize and volatile usage, see the blog: Java Multithreading (ii)-Thread safety, thread synchronization, inter-thread communication (with polygon questions set) Section II, "Two, thread synchronization"

Java Interview Summary (a)--interview Frequently asked the keyword summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.