Core classes in Java

Welcome to pay attention to my public account [Software Big Bang]
Java learning
basic knowledge that is easy to ignore in
Java Java object-oriented basics
Core classes in
Java Java abstract classes and interfaces
Exceptions in
Java Generics and collections in Java
Java provides corresponding encapsulation classes for its 8 basic data types . Substantially corresponding to the type of wrapper class addition Integerand Characterwriting the exception bit, corresponding to the other basic type of wrapper classes are to be capitalized.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Integer objInt = new Integer(10);
        Character objChar = new Character('y');
        Float objFloat = new Float(89.87);
        byte num = 100;
        Byte objByte = new Byte(num);
        Long objLong = new Long(1000L);
        short num2 = 100;
        Short objShort = new Short(num2);
        Double objDouble = new Double(122.3d);
        boolean flag = false;
        Boolean objBoolean = new Boolean(flag);
    }
}

It can also be constructed by passing in a numeric string .
For example

Integer objInt = new Integer("10");

Equivalent to

Integer objInt = new Integer(10);

If you assign an object to a basic data type, you need to call the xxxValue()method of the encapsulation class.
For example:int num = objInt.intValue();

From after the JDK1.5 , it provides the Java autoboxing (Autoboxing) and auto-unboxing (Auto Unboxing) function, therefore, can be directly assigned between the base class and package type variables.

Boxing refers to the process of converting basic types of data values ​​into corresponding encapsulated objects, that is, encapsulating the data in the stack into objects and storing them in the heap.
Unboxing is the reverse process of boxing. It is the process of converting encapsulated objects into basic data values, that is, storing the data values ​​in the heap into the stack.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Integer objInt = 10;
        int num = objInt;
    }
}

There are two ways to convert a string value to a basic type value:

  • Directly use the construction method of the package class, that is, the Xxx (String s) construction method;
int num = new Integer("100");
  • Call the parseXxx (String s) static method provided by the package class
int num = Integer.parseInt("100");

There are three ways to convert basic types of values ​​into strings :

  • Just use an empty string to concatenate the values
String str = ""+12;
  • Call the tostring() static method provided by the package class
String num = Integer.toString(100);
  • Call the valueof() static method provided by the String class
String num = String.valueOf(100);

About the Object.clone()method
Code example:

//第一个示例
class Student18 implements Cloneable{
    
    
    int rollno;
    String name;

    Student18(int rollno,String name){
    
    
        this.rollno=rollno;
        this.name=name;
    }

    public Object clone()throws CloneNotSupportedException{
    
    
        return super.clone();
    }

    public static void main(String args[]){
    
    
        try{
    
    
            Student18 s1=new Student18(101,"amit");

            Student18 s2=(Student18)s1.clone();

            System.out.println(s1.rollno+" "+s1.name);
            System.out.println(s2.rollno+" "+s2.name);

        }catch(CloneNotSupportedException c){
    
    }

    }
}
//第二个示例(与第一个没有关系)
Person p = new Person(23, "zhang");  
Person p1 = (Person) p.clone();  

System.out.println(p);  
System.out.println(p1);

The clone() method saves the extra processing task of creating an exact copy of the object. If you use the new keyword to do this, it will take a lot of processing time, which is why we use object cloning.

Then in the java language, there are two ways to create objects:

  • 1. Use the new operator to create an object

Detailed steps: allocate memory space, call the constructor, initialize, and the constructor returns

  • 2. Use the clone method to copy an object

Detailed steps: allocate memory space, call the clone()function, fill the fields of the new object with the corresponding fields in the original object, and the clone method returns.

Many friends will have questions about these two lines of code

Person p1 = new Person(1001,"xiaoming");
Person p2 = p1;//复制对象的第一种方式:直接采用地址赋值
Person p3 = (Person) p1.clone();//第二种方式:采用Object的clone()方法

Below is the full version of the above code

public class Person implements Cloneable{
    
    
    private int id;
    private String name;

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

    public static void main(String[] args) throws CloneNotSupportedException {
    
    
        Person p1 = new Person(1001,"xiaoming");
        Person p2 = p1;//复制对象的第一种方式:直接采用地址赋值
        Person p3 = (Person) p1.clone();//第二种方式:采用Object的clone()方法
        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }
}

The output result is as follows:

club.BOOKJava8.Person@5fd0d5ae
club.BOOKJava8.Person@5fd0d5ae
club.BOOKJava8.Person@2d98a335

First of all, we can be sure that p1 and p2 are the same object, and their object id is the same. p2 and p3 are not the same object, and their object ids are different.
I use a memory diagram to show it:
First, there is Person p2 = p1;//复制对象的第一种方式:直接采用地址赋值
Insert picture description here
another way. Person p3 = (Person) p1.clone();//第二种方式:采用Object的clone()方法
Insert picture description here
Another thing to note is that the clone()method uses a shallow copy . If you need a deep copy, you need to rewrite the clone method.
You can refer to this article: Portal

About the Object.finalize()method

Java has a garbage collector responsible for recycling memory resources occupied by useless objects. But there are special cases: suppose your object (not using new) acquires a "special" memory area, because the garbage collector only knows to release the memory allocated by new, so it does not know how to release this piece of the object" Special" memory. In order to cope with this situation, Java allows a method named finalize() to be defined in the class. Its working principle "assumes" is this: once the garbage collector is ready to release the storage space occupied by the object, it will first call its finalize() method, and will actually reclaim the memory occupied by the object when the next garbage collection action occurs. . So if you plan to use finalize(), you can do some important cleanup at the time of garbage collection. ——Excerpt from "Java Programming Thoughts"

public class Person implements Cloneable{
    
    
    private int id;
    private String name;

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

    public static void main(String[] args) throws Throwable {
    
    
        Person p1 = new Person(1001,"xiaoming");
        p1.finalize();//调用finalize方法
    }
}

About Object.getClass()Method
About Object.hashCode()Method
About Object.toString()Method : Returns a string containing the class name and a hash code of the form:类名@哈希代码值

public class Person implements Cloneable{
    
    
    private int id;
    private String name;

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

    public static void main(String[] args) throws Throwable {
    
    
        Person p1 = new Person(1001,"xiaoming");
        System.out.println(p1.getClass());
        System.out.println(p1.hashCode());
        System.out.println(p1.toString());
    }
}
class club.BOOKJava8.Person
1607521710
club.BOOKJava8.Person@5fd0d5ae

Can be Object.toString()rewritten

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

Then the output result at this time is:

Person{
    
    id=1001, name='xiaoming'}

The following introduces the string classes in Java :
there are three types, of which the immutable Stringis the StringBulidersum StringBuffer.
First of all,String
there is now. String str1 = "abc";
Insert picture description here
If you continue to write:, String str1 = "def";remember that the string created by String is immutable. Just writing it is actually creating a new string in memory, and the string variable will refer to the newly created string. String address, and the original string still exists in memory and its content remains unchanged until it is destroyed by Java's garbage collection system.
Insert picture description here
Also note: the String str2 = new String("lmn")created character variables are in the heap instead of the constant pool, and the new objects are all in the heap.
Insert picture description here

Interview question: How many objects does String str4 = new String (abc") create?

  1. Look for "abc objects" in the constant pool
  • If yes, return the corresponding reference instance
  • If not, create the corresponding instance object
  1. New in the heap—a String ("abc") object
  2. Assign the object address to str4 to create a reference. Therefore, if there is no "abc" literal in the constant pool, create two objects, otherwise create an object and create a reference

Variant : String str3= new String("A"+"B");How many objects will be created?

  • In the constant pool: "A" "B", "AB": 3
  • In the heap: new String ("AB"): 1
  • Reference: str1:1
  • Total: 5

Next, theStringBuffer
String Buffer created string is variable. It can be operated by append(),, insert()and setCharAt()other methods. The address quoted by the character pass has not changed. To get StringBufferthe final content, you can call the toString()method to convert it into an Stringobject.

public class Test{
    
    
    public static void main(String args[]){
    
    
        StringBuffer sBuffer = new StringBuffer("abc");
        System.out.println(sBuffer);
        sBuffer.append("def");
        System.out.println(sBuffer);
        sBuffer.insert(1, 'i');
        System.out.println(sBuffer);
        sBuffer.setCharAt(1,'o');
        System.out.println(sBuffer);

    }
}
abc
abcdef
aibcdef
aobcdef

ThereStringBuilder
StringBuffer is thread-safe, but StringBuilderdid not achieve thread-safe, so good performance. If you only need to create a variable content string object, does not involve security threads, synchronization aspects of the problem, should give priority to the use of Stringbuilderthe class.

public class Test{
    
    
    public static void main(String args[]){
    
    
        StringBuilder sBulider = new StringBuilder("abc");
        System.out.println(sBulider);
        sBulider.append("def");
        System.out.println(sBulider);
        sBulider.insert(1, 'i');
        System.out.println(sBulider);
        sBulider.setCharAt(1,'o');
        System.out.println(sBulider);
    }
}
abc
abcdef
aibcdef
aobcdef

Guess you like

Origin blog.csdn.net/weixin_44895666/article/details/107214176