java development learning: common classes

Posted by oscar2 on Wed, 02 Feb 2022 12:23:45 +0100

Common class

1. Internal class

  • Concept: define a complete class in an internal class

  • characteristic:

    • After compilation, an independent bytecode file can be generated.
    • The inner class can directly access the private members of the outer class without breaking the encapsulation. Variables defined by private can be used internally
    • It can provide necessary internal functional components for external classes.

1.1 member internal class

  • Define a class within the class, which is at the same level as instance variables and instance methods.
  • An instance part of an external class. When creating an internal class object * *, you must rely on the external class object**
    • Outer out = new Outer() ;
    • inner in = out.new Inner() ;
  • When the external class and internal class have the same name attribute, the internal class attribute will be accessed first.
    • Print the properties of the external class. The properties of the internal class have the same name as those of the external class. Use outer this
    • system.out.println(outer.this.name) ;
  • Member inner classes cannot define static members, but can contain static constants final
//1 create an external class object
outer out = new outer();
//2 create internal class objects
inter in = out.new inter();

// One step in place
inter in = new outer().new inter();

in.show();

1.2 static internal class

  • It does not depend on external class objects, can be created directly or accessed through class names, and can declare static members. The internal class plus a containment relationship is the same as the external class;
  • Only static members of external classes can be accessed directly (instance members need to instantiate external class objects);
    • Outer. Inner inner = new Outer. Inner()
    • Outer.Inner.show()

1.3 local internal class

  • Defined in an external class method, the scope of action and the scope of creating an object are limited to the current method.
  • Access local variables of local internal classes, jdk1 7 requirement: variable must be constant final jdk1. 8 add final automatically
  • When a local internal class accesses a local variable in the current method of an external class, the variable must be modified to final because it cannot guarantee that the life cycle of the variable is the same as itself.

1.4 anonymous inner class

  • Local inner class without class name (all features are the same as local inner class).

  • You must inherit a parent class or implement an interface.

  • The syntax combination of defining class, implementing class and creating object can only create one object of this class.

  • Advantages: reduce the amount of code.

  • Disadvantages: poor readability.

//Use anonymous inner class optimization (equivalent to creating a local inner class)
USB usb = new USB() {
    @Override
    public void service() {
        System.out.println("work");
    }
};
usb.service();

2.Object class

  • Superclass and base class, the direct or indirect parent of all classes, are located at the top of the inheritance tree;
  • For any class, if extensions is not written to show that it inherits a class, it inherits the Object class directly by default, otherwise it inherits indirectly;
  • The method defined in 0object class is the method of all objects;
  • The Object type can store any Object.
    • As a parameter, any object can be accepted.
    • As a return value, any object can be returned.

2.1 getclass() method

  • public final Class<> getClass () {}
  • Returns the actual object type stored in the reference
  • Application: it is usually used to judge whether the actual storage object types in two references are consistent.

2.2 hashcode() method

  • public int hashCode() {};
  • Returns the hash code value of the object;
  • Hash value a numeric value of type int calculated using the hash algorithm based on the address or string or number of the object
  • Generally, the same object returns the same hash code;
  • Application: usually used to judge whether objects are consistent.

2.3 tostring() method

  • public String toString() {}

  • Returns the string representation (representation) of the object.

  • This method can be overridden according to program requirements, such as displaying the attribute values of the object.

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

2.4 equals() method

  • public boolean equals (Object obj){};

  • The default implementation is (this == obj). Compare whether the addresses of the two objects are the same;

  • You can overwrite and compare whether the contents of the two objects are the same.

    public boolean equals(Object obj) {
        //1 judge whether two objects are the same reference
        if(this == obj){
            return true;
        }
        //2 judge whether obj is null
        if(obj == null){
            return false;
        }
        //
        if (obj instanceof student){
            //4 cast type
            student s = (student)obj;
            if (this.name.equals(s.getName())&&this.age==s.getAge()){
                return true;
            }
    
        }
        return super.equals(obj);
    

2.5 finalize() method

  • When the object is determined to be a garbage object, the JVM will automatically call this method to mark the garbage object and enter the collection queue.
  • Garbage object: garbage object when there is no valid reference to this object.
  • Garbage collection: GC destroys garbage objects to free up data storage space.
  • Automatic recycling mechanism: the JVM runs out of memory and recycles all garbage objects at one time.
  • Manual recycling mechanism: use system gc(); Notify the JVM to perform garbage collection.
@Override
protected void finalize() throws Throwable {
    System.out.println(this.name + "The object was recycled");
}

3. Packaging

  • Reference data type corresponding to basic data type
  • 0bject can unify all data, and the default value of wrapper class is null

3.1 type conversion, packing and unpacking

  • Boxing: converting basic types to reference types
  • Unpacking: convert reference type to basic type
  • Eight packaging classes provide conversion methods between different types:
    • Six common methods provided in the Number parent class.
    • parseXXX() static method.
    • valueOf() static method.
  • Note: ensure type compatibility, otherwise NumberFormatException exception will be thrown.
//1 convert basic type to string
int n1 = 100;
//1.1 use + sign
String s1 = n1+" ";
//1.2 use toString() method in Integer
String s2 = Integer.toString(n1);
System.out.println(s1);
System.out.println(s2);

//2 convert string to basic type
String str = "150";
//Use integer parseXXX();
int n2 = Integer.parseInt(str);
System.out.println(n2);

//Convert boolean string to basic type. "True" ----- > true not "true" ----- > false
String str2 = "ccb";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);

Integer buffer

  • Java creates 256 commonly used integer wrapper type objects in advance.
  • In practical application, the created objects are reused.

4.String class

  • String is a constant and cannot be changed after creation.

  • String literals are stored in the string pool and can be shared.

  • String s = “Hello”; Generate an object and store it in the string pool.

  • String s = new String(“Hello”);// Two objects are generated, one in heap and one in pool.

    String name = "hello";//"hello" constants are stored in the string pool
    name = "zhangsan";//"Zhang San" is assigned to the name variable. When assigning a value to a string, it does not modify the data, but opens up an area in the string pool for storage
    String name2 = "zhangsan";//It already exists in the character pool. name2 can be referenced directly
    
    //Another way to create a demo string. new String(); Create the form of the object
    String str = new String("JAVA");
    String str2 = new String("JAVA");
    System.out.println(str == str2);//The comparison is the address
    System.out.println(str.equals(str2));//The comparison is data
    

4.1 common methods of string

  • **public int length() 😗* Returns the length of a string.

  • **public char charAt(int index) 😗* Gets characters based on subscripts.

  • public boolean contains(String str): judge whether the current string contains str.

  • public char[] toCharArray(): converts a string into an array.

  • public int indexOf(String str): find the subscript that appears for the first time in str. if it exists, return the subscript; If it does not exist, - 1 is returned

  • public int lastIndexOf(String str): find the index of the last occurrence of the string in the current string.

  • **public String trim() 😗* Remove the spaces before and after the string.

  • public String toUpperCase(): convert lowercase to uppercase.

  • public boolean endWith(String str): judge whether the string ends with str.

  • public String replace(char oldChar, char newChar); Replace old string with new string

  • public String[] split(String str): split according to str.

    String name = "hello";//"hello" constants are stored in the string pool
    name = "zhangsan";//"Zhang San" is assigned to the name variable. When assigning a value to a string, it does not modify the data, but opens up an area in the string pool for storage
    String name2 = "zhangsan";//It already exists in the character pool. name2 can be referenced directly
    
    //Another way to create a demo string. new String(); Create the form of the object
    String str = new String("JAVA");
    String str2 = new String("JAVA");
    System.out.println(str == str2);//The comparison is the address
    System.out.println(str.equals(str2));//The comparison is data
    System.out.println("============================================");
    
    //Use of string method 1
    //1,length(); Returns the length of the string
    //2,charAT(int index); Returns the character of a position
    //3,contains(String str); Determine whether a substring is included
    String content = "java It is the best programming language in the world,java Really fragrant";
    System.out.println(content.length());
    System.out.println(content.charAt(0));
    System.out.println(content.contains("java"));
    System.out.println("============================================");
    //Use of string method 2
    //4.tochararray(); Returns the array corresponding to the string
    //5.indexof(str); Returns the position where the string STR first appears
    //6.lastIndexof(str); Returns the last occurrence of the string str
    System.out.println(Arrays.toString(content.toCharArray()));
    System.out.println(content.indexOf("java"));
    System.out.println(content.lastIndexOf("java"));
    System.out.println("============================================");
    
    //Use of string methods 3
    //7.trim(); Remove the spaces before and after the string
    //8.toUpperCase();// Convert lowercase to uppercase toLowerCase(); Convert uppercase to lowercase
    //9.endwith(str) determines whether it ends with STR, and startwith determines whether it starts with str
    
    String content2 = "   helloworld   ";
    System.out.println(content2.trim());
    System.out.println(content2.toUpperCase());
    
    String file = "hello.java";
    System.out.println(file.endsWith(".java"));
    System.out.println(file.startsWith("hello"));
    System.out.println("============================================");
    
    //10.replace(char old, char new); Replace the old character or string with the new one
    //11.split(); Split string
    
    System.out.println(content.replace("java", "python"));
    String say = "java is the best language,java";
    String[] arr = say.split("[ ,]");
    System.out.println(arr.length);
    for (String s : arr) {
        System.out.println(s);
    }
    System.out.println("============================================");
    
    // Supplement two methods: equals and compare(); Compare size
    String s1 = "h";
    String s2 = "H";
    // ignore case
    System.out.println(s1.equalsIgnoreCase(s2));
    //The first character is compared, and the first is the same as the second
    System.out.println(s1.compareTo(s2));
    String s3 = "hf";
    String s4 = "hfnsdnbsl";
    //Specific length
    System.out.println(s3.compareTo(s4));
    

4.2 variable string

  • StringBuffer: variable length string, jdk1 0, slow running efficiency and thread safety.

  • StringBuilder: variable length string, jdk5 0, which is fast and thread unsafe.

  • //StringBuffer sb = new StringBuffer();
    //same
    StringBuilder sb = new StringBuilder();
    //1 Append(); Add
    sb.append("java");
    System.out.println(sb.toString());
    sb.append(" python");
    System.out.println(sb.toString());
    System.out.println("==========================");
    //2 insert() add
    sb.insert(0, "c++ ");
    System.out.println(sb.toString());
    //3 replace
    sb.replace(0, 5, "go");
    System.out.println(sb.toString());
    //4 delete
    sb.delete(0,3);
    System.out.println(sb.toString());
    //5 empty
    sb.delete(0,sb.length());
    System.out.println(sb.length());
    

5.BigDecimal class

  • introduce:
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1 - d2);
//0.09999999999999998

//Interview questions
double result = (1.4-0.5)/0.9;
System.out.println(result);
//0.9999999999999999
  • Many practical applications require accurate calculation, and double is approximate value storage, which is no longer in line with the requirements, so BIgDecimal is needed.
  • Location: Java In the math package.
  • Function: accurately calculate floating point numbers.
  • Creation method: BigDecimal bd=new BigDecimal("1.0");.
  • method:
    • BigDecimal add(BigDecimal bd)
    • BigDecimal subtract(BigDecimal bd)
    • BigDecimal multiply(BigDecimal bd)
    • BigDecimal divide(BigDecimal bd)
      • Division: divide (BigDecimal BD, int scale, roundingmode)
      • Parameter scal: Specifies the number of decimal places.
      • Parameter mode:
        • Specify the rounding mode of the decimal part, usually in the rounding mode
        • The value is BigDecimal ROUND_ HALF_ UP.
//BigDecimal, precise operation of large floating-point numbers
BigDecimal bd1 = new BigDecimal("1.0");
BigDecimal bd2 = new BigDecimal("0.9");
//subtraction
BigDecimal s1 = bd1.subtract(bd2);
System.out.println(s1);
//addition
BigDecimal s2 = bd1.add(bd2);
System.out.println(s2);
//multiplication
BigDecimal s3 = bd1.multiply(bd2);
System.out.println(s3);
//Division,
BigDecimal s4 = bd1.divide(bd2,2,BigDecimal.ROUND_HALF_UP);
System.out.println(s4);
//Division, which usually specifies the mode
BigDecimal s5 = new BigDecimal("1.4")
        .subtract(new BigDecimal("0.5"))
        .divide(new BigDecimal("0.9"));
System.out.println(s5);

6.Date

  • Date represents a specific moment, accurate to milliseconds. Most of the methods in the date class have been replaced by those in the Calendar class.
  • Time unit -- > 1 second = 1000 milliseconds -- > 1 millisecond = 1000 microseconds -- > 1 microseconds = 1000 nanoseconds
//Creating Date Objects 
//today
Date date1 = new Date();
System.out.println(date1.toString());
System.out.println(date1.toLocaleString());
//yesterday
Date date2 = new Date(date1.getTime()-(60*60*24*1000));
System.out.println(date2.toLocaleString());
//Usage after before
System.out.println(date1.after(date2));
System.out.println(date1.before(date2));
//compare
System.out.println(date1.compareTo(date2));
System.out.println(date2.compareTo(date1));
System.out.println(date1.equals(date1));

7.Calendar

  • Calendar provides methods to get or set various calendar fields.

  • Construction method

    • protected Calendar(): the object cannot be created directly because the modifier is protected.
  • Other methods

8.SimpleDateFormat class

  • SimpleDateFormat is a concrete class that formats and parses dates in a locale dependent manner.

  • Format (date - > text), parse (text - > date)

  • Common time pattern letters

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ontexlgi-1623223024128) (C: \ users \ 86152 \ appdata \ roaming \ typora \ typora user images \ image-20210609144742860. PNG)]

9.System class

  • The System class is mainly used to obtain the attribute data and other operations of the System, and the construction method is private.
//1 arraycopy: array assignment
//src: source array
//srcPos: where to start copying 0
//dest: target array
//destPose: position of the target array
//Length: the length of the copy
int[] arr = {45,4,53,12,200,69,78};
int[] dest = new int[5];
System.arraycopy(arr,0,dest, 2,3);
for (int i : dest) {
    System.out.println(i);
}
//2 get the current time, milliseconds
System.out.println(System.currentTimeMillis());

//3 System.gc(); Tell the garbage collector to recycle the garbage
student s1 = new student("aaa",19 );
student s2 = new student("bbb",19 );
new student("ccc",19 );

System.gc();
//4 exit the jvm
System.exit(0);
System.out.println("end");

summary

  • Internal class:
    • Define a complete class inside a class.
    • Member inner class, static inner class, local inner class and anonymous inner class.
  • Object class:
    • The direct or indirect parent of all classes, which can store any object.
  • Packaging:
    • The reference data type corresponding to the basic data type enables 0bject to unify all data
  • String class:
    • String is a constant and cannot be changed after creation. The literal value is saved in the string pool and can be shared.
  • BigDecimal
    • Floating point numbers can be calculated accurately.
  • Date
    • A specific time
  • Calendar
    • calendar
  • SimpleDateFormat
    • Format time
  • System
    • System class
      dent s1 = new student("aaa",19 );
      student s2 = new student("bbb",19 );
      new student("ccc",19 );

System.gc();
//4 exit the jvm
System.exit(0);
System.out.println("end");

## summary

- Inner class:
  - Define a complete class inside a class.
  - Member inner class, static inner class, local inner class and anonymous inner class.
- Object class:
  - The direct or indirect parent of all classes, which can store any object.
- Packaging:
  - The reference data type corresponding to the basic data type can make 0 bject Unify all data..
- String class:
  - String is a constant and cannot be changed after creation. The literal value is saved in the string pool and can be shared.
- BigDecimal
  - Floating point numbers can be calculated accurately.
- Date
  - Specific time.
- Calendar
  - calendar
- SimpleDateFormat
  - Format time
- System
  - System class

Topics: Java Back-end