The native keyword

1. Native means native.

Represents local XX in Java

2. Application scope

Can only be used to modify a method.

3. What are the characteristics of the modified method?

The method bodies that it modifies are implemented in non-Java languages, mainly C.

Its method body is not visible at the Java level.

[Other modifiers]nativeReturn value type method name (parameter list);// No method body
Copy the code

Methods implemented in C are compiled into XX.dll and ready to be called.

/ / such as:
// Part of the System class:
public final class System {
    // Modifiers: private static native, private means private, only used by the System class itself
    // static means static. Only static can be called directly from a static code block
    // Native means this method is a native method whose method body is implemented in C rather than Java.
    private static native void registerNatives(a);
    static {// Static code block
        registerNatives(); // a static method of this class is called}... }Copy the code

4. The method invocation implemented in Java language has the process of loading and unloading, allocating memory in the Java virtual machine stack, and the method invocation implemented in C language also has the process of loading and unloading. Allocate memory in the local method stack.

5. How to use native modifications in Java?

(1) Called just like normal Java methods.

(2) If the subclass needs to rewrite the native method, it is also possible.

For example, class Object: the root parent of all classes
public class Object {
    public native int hashCode(a); // It is also a native method. } * /public class TestNative {
    public static void main(String[] args) {
        MyData my = newMyData(); System.out.println(my.hashCode()); }}// This class does not display its declared parent, which is Object by default
class MyData{
    // Override method shortcut key Ctrl + O

    @Override
    public int hashCode(a) {
        return 1234;// This is an arbitrary, syntactic integer}}Copy the code

The final keyword

1, The meaning of the keyword: final

2. Where can it be used?

You can use it to modify: classes, methods, variables

3. What is the difference between the classes it decorates?

Classes decorated with it cannot be inherited, that is, cannot have subclasses, we call “eunuch classes.” For example, the System class, String class, Math class…. These classes are very important; they are the most core types in Java.

4. What is the difference in the way it is decorated?

Methods decorated with it can be inherited and cannot be overridden by subclasses.

For example, the Object class is not final and can be inherited by subclasses. But a method that does not want to be overridden by subclasses is given final alone.

5. What are the differences in the variables modified with it?

The value of the variable it modifies cannot be modified, and is called the final variable, or constant. This variable can be a local variable, a static variable, an instance variable.

If you use a final modified static or instance variable, you must have an explicit initialization statement.

If you use a final modified static or instance variable, there is no set method, only a GET method.

Object the parent class

1, API: Application Program Interface, a set of libraries that can be used.

Java SE API documentation: Documentation of the core class libraries

The Java SE API documentation is available for download on the Oracle website for each JDK release. Are a set of web files (.html), all in English. Many Chinese programmers have translated it (sinicized) (some translation is not very good, need to use the original English document to help understand). And because the web files are not easy to carry and share, so someone combined them with tools. CHM files.

The Object class is one of the classes in the core library.

We can learn about it quickly and easily by: (1) viewing the API documentation (2) viewing the source code of src.zip to learn about it in detail

3. What does an API document look like?

(1) package (2) Classes and interfaces under the package, etc. (3) detailed explanation of a class or interface.

4. The Object class is in the java.lang package

The Object class is the root parent of the class hierarchy.

How to interpret this sentence?

(1) All classes inherit directly or indirectly from the Object class

(2) If a class does not specify its parent, then by default its immediate parent is Object.

(3) Member methods and variables in Object are inherited from subclasses. All objects, including arrays, can call methods in Object.

(4) All Object creation calls the no-parameter construct of Object.

(5) A variable of type Object can receive any type of Object, and this variable forms a polymorphic reference with other types of objects.

(6) Object array, can store any type of objects

Note: A variable of type Object can accept an array Object of a primitive data type,

Variables of type Object[], however, cannot accept an array Object of a primitive data type.

==> Many API overloaded methods need to coexist

​ public static void sort(int[] arr)

​ public static void sort(double[] arr)

Public static void sort(Object[] arr) //Object[] Array parameters cannot accept arguments of type int[]

5. What methods are there in the Object class? 11

ToString method of Object

1. Public String toString () :

Modifier: public, visible anywhere

Without static, you must access it through object

The absence of final means that subclasses can be overridden

There is no Native, you can see its method body implementation in the source code

Return value type: String

Method name: toString, which represents XXX as a string, where XXX represents the information of the object.

2. The return value of the toString method by default

The default toString method returns getClass().getName() + “@” + integer.tohexString (hashCode());

GetClass ().getName() : The name of the runtime type of the current object

Integer.tohexstring (hashCode()) : Represents the hashCode value of an object in hexadecimal format

For example: com. Atguigu. API. Student @ 4554617 c

Com.atguigu.api.student: The name of the runtime type of the object

4554617c: The hexadecimal representation of the object’s hashCode value.

2. If we print a variable that refers to a data type (including an array type), its toString method is automatically called by default.

Because variables referencing data types store the address value of the object, Java cannot expose the memory address. Instead, it replaces the output with the return value of the toString method, which represents the object’s information.

3. The result should be a concise but easy-to-read expression of information. It is recommended that all subclasses override this method.

4. How to rewrite?

Idea has templates, Alt + Insert

Object’s getClass() method

1.public final native Class<? > getClass() : function that returns the runtime type of the object.

Final means that subclasses cannot be overridden. Without static, you must pass “object.” to access the return value type: Class, which is generic for now

Class: is a data type that starts with an uppercase letter, distinguished from the keyword Class. Objects of this data type represent a data type. Java loads all data types into the method area’s memory, and stores each data type information in a Class object.

2 role

Has to do with the reflection of the class.

public class TestGetClass {
    public static void main(String[] args) {
        Object obj = "hello";
        // The compile-time type of obj is Object
        // the runtime type of obj is String
        System.out.println(obj.getClass());//class java.lang.String

        Object arr = new int[5];
// arr[0] = 12; / / error
// New int[5] can only call member methods of the parent class Object, member variables,
        // That is to lose the characteristics of arrays.}}Copy the code

Object method finalize()

1. Protected void Finalize () throws Throwable:

Modifier: protected Visibility ranges are subclasses of this class, this package (including subclasses and non-subclasses), and other packages

In other words, all but the other package’s non-subclasses are accessible.

Throws an exception: Throws Throwable later in the exception section

Function of 2.

Function is used by the garbage collector to do some cleanup of garbage objects before they are reclaimed.

Metaphor: to the garbage object to leave last words or explain things.

In the actual development, it is used for resource objects to do cleaning work such as releasing resources.

For example, after the I/O stream object is used, resources need to be released.

IO streams are used to transfer data with file and other system resources. IO streams are used to read and write files.

Freeing resources is not only a matter of memory reclamation for objects in the JVM, but also a matter of resource freeing at the operating system level.

3. Whether it can be rewritten

Subclasses can be overridden, usually resource classes need to be overridden, IO streams, database connections, network connections, etc. Resource classes need to be overridden, ordinary business classes do not need to be overridden.

4. What is the difference between final, Finalize,finally?

Final: indicates the keyword

Finally: Operation after an exception is thrown

Finalize: This is a method of the Object class called by GC to configure system resources or perform other cleanup.

This method is called only once per object. We can resurrect objects in finalize method.

That is, when a valid reference is made to the garbage object currently ready to be collected in finalize method, the object will be resurrected.

When the object is called garbage again, the Finalize method will not be called.

5. Know the call of Finalize

public class TestFinalize {
    public static void main(String[] args) {
        for (int i=1; i<=10; i++){
            Example e = new Example(); // Each time e is a new variable, the last object created is called garbage
        }

        // Under normal circumstances, GC does not start until memory is tight or the system is idle.
        // We'll let GC do the work.
        System.gc(); // Call GC to work

        // To let you see more objects being recycled, I let the main line sleep for a while. Don't rush to finish, because the JVM shuts down when main ends.
        try {
            Thread.sleep(10000);/ / sleep for 10 seconds
        } catch(InterruptedException e) { e.printStackTrace(); }}}class Example{
    @Override
    protected void finalize(a) throws Throwable {
        System.out.println("Quietly I left, as quietly as I came, without taking a piece of code with me!"); }}Copy the code

Equals () of Object method

1. Public Boolean equals(Object obj) :

Indicates whether some other object (the object passed in arguments) is “equal” to this object (the object calling equals).

Modifier: public visible anywhere

Without static, you must access it through object

The absence of final means that subclasses can be overridden

There is no Native, you can see its method body implementation in the source code

Return value type: Boolean The result can be true or false

Parameter list: (Object obj) Parameter types cannot be changed when subclasses override equals

A parameter of type Object indicates that any type of argument Object can be accepted.

The current object can be compared to equals with any type of object. That is, the type of the object is taken into account when comparing.

2. How does it work

Return (this == obj); return (this == obj); The default equals method also compares two object addresses.

Compares the address of the current object with another specified object.

Equals (p2) p1 is this,p2 is obj

3. Can I rewrite it

Subclasses can choose to override. How do I rewrite it? Idea has template Alt + Insert

4. Rewriting rules

If you override equals manually without a template, there are a few principles to follow:

Reflexive: x.equals(x) must return true

Symmetry: if x.evers (y) returns true, then y.evers (x) must also return true

Transitivity: x.quals (y) returns true, y.quals (z) returns true, and x.quals (z) must also return true

Consistency: x.equals(y) if it returns true, it will return true as long as the x and y objects have not been modified the next time it calls equals. A non-empty object comparing with null must return false

public class TestEquals {
    public static void main(String[] args) {
        Person p1 = new Person("110123199501011234"."Zhang");
        Person p2 = new Person("110123199501011234"."Zhang");
        System.out.println(p1 == p2);//false == compares the memory address of the object
        System.out.println(p1.equals(p2));// Before rewriting: false

        System.out.println(p1.equals(p1));// Compare yourself to yourself, the same memory address, return true
        System.out.println(p1.equals(null));// Return false because p1 is also null, then this code will not execute, NullPointerException
                                                    // p1 must be non-null, and non-null and null must be false
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        String str1 = "hello";
        String str2 = "hello";
        String str3 = new String("hello");
        System.out.println(str1 == str2);//"hello" and "hello" are constant objects, the same memory addressSystem.out.println(str1.equals(str2)); System.out.println(str1 == str3); System.out.println(str1.equals(str3)); }}class Person{
    private String id;
    private String name;

    public Person(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId(a) {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName(a) {
        return name;
    }

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

    @Override
    public String toString(a) {
        return "Person{" +
                "id='" + id + '\' ' +
                ", name='" + name + '\' ' +
                '} ';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;  // Compare memory addresses, return true if the two objects have the same memory address

        if (o == null|| getClass() ! = o.getClass())return false;
        / / | | short circuit or, if on the left is true. On the right.
        //o == null returns false
        //getClass() ! GetClass () on the left represents the runtime type of the current object being retrieved
                                    // The right o.goetclass () gets the runtime type of the argument object
                                    // If the type is not equal, return false

        Person person = (Person) o; // Downcast because the method parameter is Object, upcast occurs when the argument is passed to parameter o
                                // The Person class's equals method is used to compare two Person objects. The parameter (Person p) should be more appropriate
                                // But equals overrides Object, so parameter list complement cannot be changed
                                // We have to go down here because we want to compare objects' properties
                                // If o is treated as Object, the attributes of the Person class cannot be accessed.
        return Objects.equals(id, person.id) &&
                Objects.equals(name, person.name);
            // Use the equals method of the java.util.Objects utility class to compare the ids and names of two Objects
            //&&, which means that id must be the same as name to return true
    }

    @Override
    public int hashCode(a) {
        returnObjects.hash(id, name); }}Copy the code

Object method hashCode()

1.public native int hashCode();

Public: public

Native; The presentation method body is not implemented in the Java language

Int: The return value is of type int and represents an integer

Function: Returns the hash code value of the object. This method is supported to improve the performance of hash tables, such as those provided by java.util.hashtable. HashCode doesn’t do much if the object is not stored in the container of the hash structure.

2. What is returned?

HashCode: is an integer

Number summary: use a number to represent xx details,

For example, id card number, which represents a person’s basic information

In Java, a hashCode value is used to represent information about an object.

Is hashCode a memory address?

Some virtual machines do use memory addresses directly as hashCode values.

But most don’t use memory addresses as hashCode values.

It uses some hash function to evaluate the instance variable of the object to get an int value as a hashCode.

Why hash functions?

Because the goal of the hash function is to get a different output for each different input.

Hopefully, if the object is different, its hashCode value will be different.

But in reality, two different objects might have the same hashCode value.

3. Can I rewrite it

Subclasses can choose to override, idea template and Equals together.

4. Why rewrite with equals()?

Because Java requires:

① If two objects are equal, the hashCode value must be the same

② If two objects have different hashCode values, then they must have different equals (false).

(3) If two objects have the same hashCode, their equals methods may be true,false

The enumeration

1. What is enumeration?

An enumeration is a special class that has a finite number of objects.

In real development, there are requirements:

For example, week, month…….

2. How to implement enumeration?

Jdk1.5 before:

Consider: How to limit the number of objects?

(1) Privatize the constructor;

(2) Inside the enumerated class, create n objects in advance for external use;

(3) The object created should be a member variable (outside of a method in the class). In order to call a member variable without creating an object, you need to set it to a static variable. At the same time, to ensure that the object is not tampered with, final is used.

public static final Week MONDAY = new Week();
Copy the code

After jdk1.5:

To simplify the declaration of enumeration types, the new keyword enum can be used to declare enumerations.

Grammar:

Modifier enum Enum type name {list of constant objects; Other members; }Copy the code

Note:

(1) If there are other members after the constant object list, add them; The end of the

(2) The list of constant objects in the enumeration class must be on the first line

(3) Enumerated types that do not declare constructors also have a default constructor with no arguments

(4) Enumeration constructors must be private anyway, and default to private without declaration

(5) Enumerated types can declare multiple constructors, which are also private

When an object is created by calling a no-argument construct, the () can be omitted

When you create an object by calling the parameter construct, you add the argument list directly after the constant object name. The parameter type and number must correspond.

(6) The enumeration class’s other member variables are not required to be final, but are traditionally declared to be final. In this case, it must be assigned to this parameter or an error will be reported.

(7) Enumeration types declared with enum, by default, inherit an enumeration public parent,java.lang.Enum class, the root parent is still the Object class. This means that an enumerated class declared with enum can no longer inherit from another class.

(8) Because the toString() method of the Object class is overridden in Enum.

ToString returns the name of the constant object, but can be overridden again if necessary.

(9) There are other new methods inherited from the parent Enum class

String name(): Used to return the name of the enumeration constant object;

Int ordinal(): Used to return the index of the enumerated constant object, index subscripts starting at 0;

Enumeration type name [] values: a method that does not exist in the API to get all objects in an enumeration constant.

After jdk1.5, we can write constants of enum type after case of switch.

public enum Month {
    JANUARY(1."Month"),// This is equivalent to calling the parameter constructor to generate an object.
    FEBRUARY(2."February"),
    MARCH(3."March"),
    APRIL(4."April"),
    MAY(5."May"),
    JUNE(6."June"),
    JULY(7."July"),
    AUGUST(8."August"),
    SEPTEMBER(9."September"),
    OCTOBER(10."October"),
    NOVEMBER(11.November),
    DECEMBER(12.December);

    private final int num ;
    private String description;

    public int getNum(a) {
        return num;
    }

    Month(int num, String description) {
        this.num = num;
        this.description = description;
    }
    public static Month getByValue(int value){
        for (int i = 0; i < Month.values().length; i++) {
            if(Month.values()[i].num == value){
                returnMonth.values()[i]; }}return null;
    }


    @Override
    public String toString(a) {
        return num+"- >"+super.toString()+"- >"+description; }}Copy the code

A wrapper class

1. What is packaging

Wrapper class is a concept proposed to solve the problem that Java’s eight basic data types, such as byte,short and void, do not belong to the object oriented category.

Java provides corresponding reference data types for these types

byte –> Byte

short –> Short

int –> Integer

float –> Float

double –> Double

char –> Character

boolean –> Boolean

void –> Void

2. Why packaging?

The eight basic data types and void these types are not object oriented, resulting in many apis designed for objects that do not use these types. Much of Java’s new syntax is designed for object orientation, such as generics, which are also not supported.

To address these compatibility issues, a wrapper class was added

Why didn’t Java start out as a “pure” object-oriented language?

Because Java was invented under the influence of C language,C language has these types, and has advantages :(1) very rich operator (instruction) support; (2) Different platforms have uniform width standards.

3. These wrapper classes are all in the java.lang package

4. Packaging operations: packing and unpacking

Boxing: Wrap the base data type as —-> wrapped objects

Unboxing: Unboxing the object of the wrapper class into a –> primitive data type

Jdk1.5 before:

Only manual packing and unpacking.

After jdk1.5:

Support automatic packing and unpacking.

However, automatic packing and unpacking can only occur between corresponding types, such as int <—->Integer

int b = 1;
Integer obj1 = b;// Automatic boxing

Double obj2 = new Double(1.0);
double d = obj2;// Automatic unpacking
Copy the code

5. The API (part)

(1) Get the maximum and minimum values of each type (wrapper class). MAX_VALUE, wrapper class. MIN_VALUE)

//Integer.MAX_VALUE
//Integer.MIN_VALUE
Copy the code

(2) Get the binary form of a decimal system, the octal form, etc.

ToBinaryString (decimal integer): Converts to binary representation.

ToOctalString (decimal integer): converts to octal

ToHexString: Converts to hexadecimal

(3) Case transformation

Character.touppercase (variable of type char): uppercase

Character.toLowerCase(variable of type char): change toLowerCase

(4) Compare the size of two decimals

Try not to use ‘==’, instead use:

Double.compare(parameter 1, parameter 2); The result is an integer where 0 means equal,1 means the former argument is greater than the latter, and -1 means the former argument is smaller than the latter.

(5) Support conversion between various basic data types and strings (high frequency of use)

Integer.parseint (string) returns an int value

Double. ParseInt (string) returns a Double

Boolean. ParseInt (string) returns Boolean

Long.parseint (string) returns the value of Long

Object name. CharAt (subscript, starting from zero) returns type char

6. Wrap the cache of class objects

Byte -128~127

Short -128~127

Integer -128~127

Long -128~127

Float,Double does not cache objects (decimals, large range of frequently used values, large memory storage)

Boolean:true,flase

Character: 0~127 are exactly the characters in the early ASCII table.

Values in this range are frequently used, and values of wrapped class objects in this range, without actively creating objects using new, point to cached objects in the constant pool.

public class TestCache {
    public static void main(String[] args) {
        int a = 1;
        int b = 1;
        System.out.println(a == b);//true compares data values

        Integer i1 = 1; // The 1 on the right is automatically boxed as an Integer object
        Integer i2 = 1;//i1 and i2 point to the same cache object
        System.out.println(i1 == i2);//true compares address values

        int c = 128;
        int d = 128;
        System.out.println(c == d);//true compares data values

        Integer i3 = 128;
        Integer i4 = 128;
        System.out.println(i3 == i4);//false compares address values

        Integer i5 = new Integer(1);
        Integer i6 = new Integer(1);
        System.out.println(i5 == i6);//false

        Integer i7 = Integer.valueOf(1);
        Integer i8 = Integer.valueOf(1);
        System.out.println(i7 == i8);//true}}Copy the code

7. Supplementary

When the packaging class and basic data type operation, will automatically unpack the basic data type for comparison; If there are two basic data types, an automatic type conversion is performed to compare them to the same data type.

public class TestExam {
    public static void main(String[] args) {
        Integer i = 1000;
        int j = 1000;
        System.out.println(i==j);//true

        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

        Integer m = 1000;
        double n = 1000;
        System.out.println(m == n);//true (1) m autounpack to int (2) int autotype to double

        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        Double d1 = 1.0;
        double d2 = 1.0;
        System.out.println(d1 == d2);//true d1 is automatically unpacked as double}}Copy the code

Wrapper class A special reference data type whose objects are immutable and which can be modified to produce new objects. The same is true of the String class.

public class TestExam2 {
    public static void main(String[] args) {
        int num = 1;
        Integer obj = 1;
        Data data = new Data();
        data.x = 1;

        change(num, obj, data);

        System.out.println("num = " + num);/ / 1
        System.out.println("obj = " + obj);/ / 1
        System.out.println("data.x = " + data.x);/ / 11
    }

    /* Data d is a reference Data type, and its changes to member variables are related to the arguments. Integer B is a reference data type, and Integer is a special reference data type whose objects are immutable objects that can be modified to create new objects. B +=10, which makes b refer to a new object, regardless of the argument obj */
    public static void change(int a , Integer b, Data d ){
        a += 10;
        b += 10;
        d.x += 10; }}class Data{
    int x;
}
Copy the code