Java learning day014(Object, basic wrapper type, String class, StringBuilder)

Posted by Wolphie on Fri, 14 Jan 2022 16:45:47 +0100

Object class learning

In java, all classes are subclasses of the Object class

The Object class is the parent of all classes

-----Object.java
getClass(); 	// Get bytecode file
hashcode();		// The hashcode value of the object
equals();		// To judge whether two objects are equal, use the address judgment
finalize();		// This method is automatically executed before garbage collection

For example

package om.openlab.da14.object;

public class Test {
    public static void main(String[] args) {
        User u = new User();
        System.out.println(u.getClass()); // class om.openlab.da14.object.User
        System.out.println(u.hashCode()); // 2083562754
    }
}

class User {
}

native keyword

native keyword indicates that the modified method is an original ecological method. The corresponding implementation of the method is not in the current file, but in the file implemented in other languages (such as C and C + +)

✨hashcode()

If two objects are the same object (with the same address), hashcode The value must be the same,
If two objects hashcode Values are the same, not necessarily the same object

OpenJDK: Five are available hashcode Algorithm, one of which directly returns the memory address
 Is the memory address hash Value, this sentence is not wrong, but it is not necessarily accurate

be careful:

If the equals of two objects are equal, hashcode must be equal
If the hashcode s of two objects are equal, equals is not necessarily equal

The difference between final, finally and finalize()

Object Copy

Here you can refer to the blog:
1. How does AVA copy objects
2.java reference copy, object shallow copy, object deep copy
Reference passing:
The object is not copied. It is the same object. What is copied is the stack memory (address)

In java, if a class needs to call the clone of the Object to copy the Object, it must be implemented

In java, if a class wants to implement the clone method, it must implement an interface (clonable)

In java, there is a kind of interface without any code. Label the interface!!!

Shallow copy:

Object Class, provided`clone`The method is shallow copy(object)
When copying an object, only the first level copy of the object is completed. If there are sub objects of the object, then
 Can't copy shell objects

Deep copy:

Recursive copy will separate all objects
1,Let child objects also implement Cloneable Interface. When the parent object is copied, the child object is also copied
2,Deep copy is achieved by serializing and deserializing objects

Reference passing

package om.openlab.da14.copy;
public class Test {
    public static void main(String[] args) {
        User user2 = new User();
        user2.setUsername("first");

        // The address of user2 is passed to user3. The object is not copied, but the stack address is copied
        User user3 = user2;

        System.out.println(user2); // User{username = 'first'}
        System.out.println(user3); // User{username = 'first'}

        user2.setUsername("second");
        System.out.println(user2); // User{username = 'second'}
        System.out.println(user3); // User{username = 'second'}
    }
}

class User {
    private String username;
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                '}';
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

Shallow copy

package om.openlab.da14.copy;
public class User implements  Cloneable{ // Implement clonable interface
    private String username;
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                '}';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
-----
package om.openlab.da14.copy;
public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        User user2 = new User();
        user2.setUsername("first");

        User user4 = (User) user2.clone();

        System.out.println(user2 == user4); // false

        user4.setUsername("second");
        System.out.println(user2); // User{username = 'first'}
        System.out.println(user4); // User{username = 'second'}
    }
}

Basic type packing class

Basic data typePackaging
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCHaracter
booleanBoolean

Overview and use of Integer class

Integer: wraps the value of the original type int in an object

Method nameexplain
public Integer(int value)Create Integer object based on int value (obsolete)
public Integer(String s)Create Integer object based on String value (obsolete)
public static Integer valueOf(int i)Returns an Integer instance representing the specified int value
public static Integer valueOf(String s)Returns an Integer object String that holds the specified value

Conversion between int and String

The most common operation of a primitive type wrapper class is to convert between primitive types and strings

1. Convert int to String
public static String valueOf(inti): returns the String representation of the int parameter. This method is a method in the String class
2. Convert string to int
public static int parseInt(Strings): resolves a string to type int. This method is a method in the Integer class

For example

package om.openlab.da14.packing;
public class InterDemo02 {

    public static void main(String[] args) {
        // int -> String
        int number = 100;
        // Mode 1
        String s1 = number + "";
        System.out.println(s1);

        // Mode 2
        // public static String valueOf(int i)
        String s2 = String.valueOf(number);
        System.out.println(s2);
        System.out.println("--------");

        // String -> int
        String s = "100";
        // Mode 1
        // String -> Integer -> int
        Integer i = Integer.valueOf(s);
        // public int intValue()
        int x = i.intValue();
        System.out.println(x);
        // Mode 2
        // public static int parseInt(String s)
        int y = Integer.parseInt(s);
        System.out.println(y);
    }
}

Automatic packing and unpacking

Packing: convert the basic data type to the corresponding packing type

Unpacking: convert the packaging type to the corresponding basic data type

For example

package om.openlab.da14.packing;
public class IntegerDemo03 {
    public static void main(String[] args) {
        // Packing: convert the basic data type to the corresponding packing type
        Integer i = Integer.valueOf(100);
        Integer ii = 100; // Integer.valueOf(100) automatic packing

        // Unpack and convert the packing type to the corresponding basic data type
        // ii +=200;
//        ii = ii.intValue() + 200; // ii.intValue() this is unpacking
        ii += 200; // Automatic unpacking
        System.out.println(ii);

        Integer iii = null;
       if (iii != null) {
           iii += 300; // Null pointerexception null pointer exception
       }
    }
}

Note: when using the wrapper class type, it is best to judge whether it is null first if you do the operation

Recommendation: as long as it is an object, it must be judged not to be null before use

String class

String class in Java Lang package, so you don't need to import packages when using

The String class represents a String. All String literals (such as "abc") in the Java program are implemented as instances of this class, that is, all double quoted strings in the Java program are objects of the String class

Characteristics of string

Strings are immutable, and their values cannot be changed after creation. Although String values are immutable, they can be shared
String effect is equivalent to character array (char []), but the underlying principle is byte array (byte [])

JDK8 and before are character arrays, and JDK9 and after are byte arrays

String construction method

Method nameexplain
public String( )Create a blank string object that contains nothing
public String(char[] chs)Create a string object based on the contents of the character array
public String(byte[ ] bys)Create a string object based on the contents of the byte array
String s = "abc" ;Create a string object by direct assignment. The content is abc

For example

package om.openlab.da14.packing;
public class StringDemo {
    public static void main(String[] args) {
    
        String s1 = new String();
        System.out.println("s1:"+s1);

        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println("s2:"+s2);

        byte[] bys = {97,98,99};
        String s3 = new String(bys);
        System.out.println("s3:"+s3);

        String s4 = "abc";
        System.out.println("s4:"+s4);
    }
}

string comparison

1.==

Address of the comparison string

2.eaual()

Compare the contents of the string

For example

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);       // false
System.out.println(s1.equals(s2));  // true

String splicing problem:

stay java,Do not loop concatenate strings, because a large number of discarded strings will be generated (which cannot be used) gc Recycle, resident memory)

StringBuilder:Thread unsafe (non thread safe)
StringBuffer: Is thread safe

String constant pool

From blog: Deep understanding of Java String classes

/**
 * The running result is true or false
 */
String s1 = "AB";
String s2 = "AB";
String s3 = new String("AB");
System.out.println(s1 == s2);
System.out.println(s1 == s3);

The strings in java are saved in the string constant pool, and there is only one copy!! A string is a constant

Interview question: where is the string constant pool in java and the JVM?

JDK7 Previously, constant data such as string constant pool was stored in method area( Method Area),Also known as the permanent generation
JDK7 Start to remove the permanent generation and store constant data such as string constant pool in the heap.
JDK8,metadata area (Metaspace),Will 1.6 Other data stored in the method area is moved to the metadata area,
The string constant pool has not been moved back
 implication: java from jdk7,String constant pool stored in heap In, jdk It was previously stored in a permanent generation.

Note: when compiling, the string of the determined result will not create an object, and the values in the constant pool will be directly compared
When compiling, if the result is uncertain, a string object will be created

StringBuilder

StringBuilder is a variable string class. We can regard it as a container. The variable here means that the content in the StringBuilder object is variable

Differences between String and StringBuilder:
String: the content is immutable
StringBuilder: content is mutable

StringBuilder construction method

Method nameexplain
public StringBuilder( )Create a blank variable string object that contains nothing
public StringBuilder(String str)Creates a variable string object based on the contents of the string

For example

package om.openlab.da14.packing;

public class StringBuilderDemo {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:"+sb);
        System.out.println("sb.length():"+sb.length());

        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:"+sb2);
        System.out.println("sb2.length():"+sb2.length());
    }
}

Adding and reversing methods of StringBuilder

Method nameexplain
Public StringBuilder append (any type)Add data and return the object itself
public StringBuilder reverse( )Returns the opposite sequence of characters

StringBuilder and String convert to each other

1. Convert StringBuilder to String
public String toString(): you can convert StringBuilder to String through toString()

2. Convert string to StringBuilder
public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a method

Topics: Java