SoFunction
Updated on 2025-05-12

Interpretation of internal and common classes in Java

Internal and Common Classes

Internal class

Concept: Define a complete class inside a class

 package .demo01;
 ​
 public class Body {
     private String name;
     class Header{
         //The internal class will also generate a class file. After compilation, it can generate an independent bytecode file.         //Inner class can provide necessary functional components for external class         public void show() {    
             (name);   //Inner class can directly access private members of external class without breaking the encapsulation         }
     }
 }

Member internal class

package .demo02;
 ​
 //External class public class Outer {
     //Instance variable     private String name = "Zhang San";
     private int age = 18;
 ​
     //Inner class Classes of the same level as instance variables and instance methods     class Inner {
         private String address = "Beijing";
         private String phone = "110";
 ​
         private String name =  "Li Si"; 
         
         //private static int scores = 86; Inner class cannot define static members         private static final int scores = 86; //But static constants can be defined         //method         public void show() {
             //Print the properties of the external class             (name);   //The internal class attribute and external class attribute name are the same, and the internal class is preferred             ();    
             (age);    //You can add this to the age to make it clearer and readable             //Print the properties of the internal class             (address);        //Same thing you can add this.             (phone);          //Same thing add this.         }
     }
 }
 package .demo02;
 ​
 public class TestOuter {
     public static void main(String[] args) {
         //The creation of inner class must rely on external class objects // //1. Create an external class object first //        Outer outer = new Outer();
 // //2. Create an inner class object //         inner =  Inner();
 ​
         //Instant in one step          inner = new Outer().new Inner();
 ​
         ();
     }
 }

Static inner class

It does not depend on internal class objects, can be created directly or accessed through class names, and can declare static members.

 package .demo03;
 ​
 //External class public class Outer {
     private String name = "xxx";
     private int age = 18;
 ​
     //Static inner class: same as external class     static class Inner {    //Only internal classes can be modified with static, normal classes cannot be modified with static         private String address = "Shanghai";
         private String phone = "110";
 ​
         // Static members         private static int count = 10000;
 ​
         public void show() {
             //How to call the properties of the external class             //(name); wrong             Outer outer = new Outer();
             ();
             ();
             //Calling properties and methods of static inner class             (address);
             (phone);
             //Calling static properties of static inner class             ();
 ​
         }
     }
 }
package .demo03;
 ​
 public class Test {
     public static void main(String[] args) {
         // Static inner class is equivalent to an outer class         //Create static inner class object directly          inner  =new ();  //No new Outer();         //Calling method         ();
     }
 }

Local internal classes

Defined in external class methods, the scope of action is limited to the current method

package .demo04;
 ​
 public class Outer {
     private String name = "Zhang San";
     private int age = 18;
 ​
     public void show() {
         //Define local variables         final String address = "Shenzhen";    // When a local inner class accesses local variables of the current method of the external class, since it is impossible to guarantee that the declaration period of the variable is the same as itself, the variable modification must be final. ​
         // Local internal class: Note that no access modifier can be added         class Inner {   //It won't disappear in the pile             private String phone = "110";
             private String email = "111@";
 ​
            // private static int count = 0; There cannot be static properties in local internal classes, but static constants can also be             
             public void show2() {
                 //Access the properties of external class, but the show cannot be accessed if it is modified by static                 //Because static and class are loaded together, the external class attribute has not been loaded yet                 (name);   //You can add it. It is highly readable                 (age);
                 //Access internal class attributes                 (phone);  //This can be added.                 (email);  //Same as above                 
                 //Accessing local variable jdk1.7 requires a constant jdk1.8 automatically adds final                 (address);
             }
         }
         
         //Create an internal class object         Inner inner = new Inner();
         inner.show2();
     }
 }
package .demo04;
 ​
 public class Test {
     public static void main(String[] args) {
         Outer outer = new Outer();
 ​
         ();
 ​
     }
 }

Anonymous internal class

  • Local internal classes without class names
  • Must inherit a parent class or implement an interface
  • Advantages: Reduce the amount of code
  • Disadvantages: Poor readability
package .demo05;
 ​
 //interface public interface USB {
     //Define a service method     void service();
 }
package .demo05;

public class Mouse implements USB {
    @Override
    public void service() {
        ("The connection is successful, the mouse starts working");

    }
}
package .demo05;

public class Test {
    public static void main(String[] args) {


        //Create interface type variable        //USB usb = new Mouse();
        //();

        //Local internal class    class Fan implements USB {


        @Override
        public void service() {
            ("The connection is successful, the fan starts working");
        }
    }
        USB usb = new Fan();
        ();

    }
}

This is using local inner classes. Local internal classes are only used once, and can be optimized with anonymous internal classes->

 package .demo05;
 ​
 public class Test {
     public static void main(String[] args) {
 ​
         //Create an object using an anonymous inner class (equivalent to creating a local inner class)         // USB usb = new USB(); error - the interface cannot be instantiated         USB usb = new USB() {
             @Override
             public void service() {
                 ("The connection is successful, the fan starts working");
             }
         };
         ();
 ​
         //Use anonymous internal class optimization ​
     }
 }

Commonly used categories

Object class

Under the package

Superclass, all objects inherit the method of this class

getClass() method

Return class type

Application: Determine whether the actual storage object types in the two references are consistent

 package .demo06;
 ​
 public class Student {
     private String name;
     private int age;
     
     public Student(String name, int age) {
          = name;
          = age;
     }
 ​
     public String getName() {
         return name;
     }
 ​
     public void setName(String name) {
          = name;
     }
 ​
     public int getAge() {
         return age;
     }
 ​
     public void setAge(int age) {
          = age;
     }
 }
package .demo06;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
        //Judge whether s1 and s2 are of the same type        Class class1 = ();
        Class class2 = ();

        if (class1 == class2) {
            ("s1 is the same class");
        } else {
            ("s1 is not the same class");
        }
    }
}
hashCode() method

Return to the int type

Hash value according toThe address of the objectorStringornumberThe value of type int calculated using hash algorithm

Generally, the same object returns the same hash code

The code of the above lesson is as an example

package .demo06;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
        
        //hashCode method        (());	//Open the first space        (());	//Open the second space        Student s3 = s1;
        (());	//Give it the first space		//1, 3 are equal, 1, 2 are different    }
}
toString() method

Return value type String

This method can be rewrite according to program requirements

package .demo06;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
        
        //
        (());	
        (());
    }
}

What you get is @+hexadecimal hash value

If you want to see the specific attribute, you need to rewrite toString

package .demo06;

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
         = name;
         = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
         = age;
    }
	//Shortcut key alt+ins    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}
equals() method

Return to Boolean type

package .demo06;

public class Test {
    public static void main(String[] args) {
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 22);
        
        //Method: Determine whether the two objects are equal or not        ("-----------------------------------");
        ((s2));

        Student s4 = new Student("Xiao Ming",17);
        Student s5 = new Student("Xiao Ming", 17);
        ((s5));  //Although the properties of the two are the same, a memory space is opened up separately false
    }
}

To make the attributes the same return true, you must rewrite equals

 @Override
     public boolean equals(Object obj) {
         //1. Determine whether two objects are the same reference         if (this == obj) {
             return true;
         }
         //2. Determine whether obj is null         if (obj == null) {
             return false;
         }
         //3. Determine whether it is the same type //        if(() == ()) {
 //            return true;
 //        }
         if (obj instanceof Student) {    //Instanceof determines whether the object is of some type             //4.Captive type conversion             Student s = (Student) obj;
             //5. Compare attributes             if ((()) &&  == ()) {
                 return true;
             }
         }
         return false;
     }
finalize() method

In general, programmers will not call this method

  • When the object is determined to be a garbage object, the JVM automatically calls this method to mark the garbage object and enter the recycling queue
  • Garbage object: When there is no valid reference to point to this object, it is a garbage object
  • Garbage collection: GC destroys garbage objects and frees up data storage space
  • Automatic recycling mechanism: JVM runs out of memory, freeing up data storage space
  • Manual recycling mechanism: use (), notify the JVM to perform garbage collection
@Override
     protected void finalize() throws Throwable {
         ( +"The object was recycled");
     } //rightfinalizeRewrite the method
 package .demo06;
 ​
 public class Test2 {
     public static void main(String[] args) {
         Student s1 = new Student("aaa", 20);
         new Student("bbb", 20);
 ​
         //Recycle garbage         ();
         ("Recycling garbage"); //aaa is normal, bbb is recycled     }
 }

Packaging

Reference data type corresponding to basic data

Basic data types Packaging
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
Type conversion and boxing
  • The objects in the stack are taken into the stack: Packing
  • Take the objects in the pile into the stack: unbox
package .demo07;

public class Test {
    public static void main(String[] args) {
        //Type conversion: Packing: The process of converting basic types to reference types        int num1 = 18;  //Basic Type Stack        //Create an object using the Integer class. Both of the following methods are OK        Integer integer1 = new Integer(num1);
        Integer integer2 = (num1);
        ("Boxing");
        (integer1);
        (integer2);


        //Type conversion: Unboxing: Convert the reference type to the basic type        Integer integer3 = new Integer(100);
        int num2 = ();
        ("Unboxing");
        (num2);

        //After JDK1.5, automatic packing and unboxing are provided.        int age = 18;
        //Automatic packing        Integer integer4 =age;
        ("Autoboxing");
        (integer4);
        //Automatic unboxing        int age2 =  integer4;
        ("Automatic unboxing");
        (age2);


    }
}

Basic type conversion

package .demo07;

public class Test {
    public static void main(String[] args) {
        
        //Convert basic type into string        int n1 = 15;
        //1. Use + sign        String s1 = n1 + "";
        //2. Use the toString() method in Integer        String s2 = (n1);
        String s3 = (n1,16);    //ToString overload method, convert it to the specified division        (s1);
        (s2);
        (s3);

        //Convert string to basic type        String str = "150";
        //use();        int n2 = (str);
        (n2);

        //Convert the boolean string into the basic type, "true"-->true, as long as this string is either true or false        String str2 = "true";
        boolean b1 = (str2);
        (b1);

    }
}
Integer Buffer

Java pre-created 256 commonly used integer wrapper type objects Integer

Let's deepen our understanding of this sentence from a program

package .demo07;


public class Test2 {
    public static void main(String[] args) {
        //Interview questions        Integer integer1 = new Integer(100);
        Integer integer2 = new Integer(100);
        (integer1 == integer2);   //Reference type opens up two different spaces in heap memory false
        Integer integer3 = 100; //Automatic boxing, that is, Integer integer3 = (100) The same applies to the following        Integer integer4 = (100); //Automatic packing        (integer3 == integer4);
        //Integer3 and integer4 are both reference types, is the answer false?  The result is true
        Integer integer5 = 200;
        Integer integer6 = 200;
        (integer5 == integer6);
        //These three lines are almost no different from the above three lines. The result is the opposite. It is false    }
}

Automatic boxing is used ()

The problem lies in this method, ctrl+mouse to see valueOf() source code

public static Integer valueOf(int i) {
        if (i >=  && i <= )
            return [i + (-)];
        return new Integer(i);
    }

low= -128,high = 127;

		Integer integer3 = 100; 
        Integer integer4 = 100; 
        (integer3 == integer4);	//true

100 at -128~127 Return cache[] array

The array has 256 positions in the buffer. The value 100 is given to integer3 and integer4. The addresses of both are the same, so the return true

		Integer integer5 = 200;
        Integer integer6 = 200;
        (integer5 == integer6);	//false

200 is not in -128~127 return new Integer(i); Like Integer1,2, open up new space in heap memory

String class

String Overview
  • Strings are constants that do not disappear after creation
  • String literals are stored in string pools and can be shared
package .demo07;

public class Test3 {
    public static void main(String[] args) {
        String name = "hello";  //"hello" is stored in a constant pool        (());    //If hashcode is x        name = "zhangsan";    // When assigning "zhangsan" to name When assigning a value to a string, the data is not modified on the original string, but a piece of space is reopened.        String name2 = "zhangsan";

        (());    //hashcode is y "zhangsan" string constants can be shared        (());   //hashcode is y        
    }
}
Common methods of String
  • public int length(): Returns the string length
  • public char charAt(int index): Get characters based on subscript
  • public boolean contains(String str): Determine whether the current string contains str
package .demo07;

public class Test3 {
    public static void main(String[] args) {
        //Use of string method        //length(); returns the length of the string        //charAt(int index); Returns the character at a certain position        //contains(String str); determine whether it is a substring?
        String content = "java is the best programming language in the world";
        (());   //15
        ((0));  //The first character        ((()-1)); //The last character        (("java"));
        (("php"));


    }
}
  • public char[] toCharArray(): Convert strings to arrays
  • public int indexOf(String str): Find the first subscript that appears in str, exists, returns the subscript, does not exist, returns -1
  • public int lastIndexOf(String str): Find the last subscript of the string in the current string
package .demo07;

import ;

public class Test3 {
    public static void main(String[] args) {
        
        //Use of string method        //toCharArray(); returns the array corresponding to the string        //indexOf(); Returns the location where the substring appears        //lastIndexOf(); Returns the last occurrence of the string		String content = "java is the best java programming language in the world, java is really delicious";

        (());
        ((())); //Output this array as a string        (("java"));    //0
        (("java", 4)); //Look for the second java, start with the angle mark of 4, but the final result is still with the first character as 0        (("java"));    // Find the last java

    }
}
  • public String trim(): Remove the spaces before and after the string
  • public String toUpperCase(): Convert lowercase to uppercase
  • public String toLowerCase(): Convert uppercase to lowercase
  • public boolean endsWith(String str): Determine whether the string ends with str
  • public boolean startsWith(String str): Determine whether the string starts with str
package .demo07;

import ;

public class Test3 {
    public static void main(String[] args) {
      
        //Use of string method        //trim(); Remove the spaces before and after the string        //toUpperCase(); Convert lowercase to uppercase        //toLowerCase(); convert uppercase to lowercase        //endsWith(str); determine whether it ends with str, startsWith(str); determine whether it starts with str
        String content2 = " hello   World   ";
        (());
        (());
        (());
        String fileName = "";
        ((".java"));
        (("hello"));

    }
}
  • public String replace(char oldChar, char newChar): Replace the old string with the new string
  • public String split[] split(String str): Split according to str
package .demo07;

import ;

public class Test3 {
    public static void main(String[] args) {
        
        //Use of string method        //replace(char old, char new);Replace the old string with the new string        //split(); splits the string        (("java", "php"));
        String say = "java is the best programming language";
        String[] arr = (" ");
        (); //6, split into 6 strings        for (String s : arr) {
            (s);
        }
        String say1 = "java is the best programming language,java xiang";
       //You want to remove the string space and commas to split        String[] arr1 = ("[ ,]");
        for (String s : arr1) {
            (s);
        }
        String say2 = "java is the best      programming language,java xiang";
        //You can also remove multiple spaces if you want        String[] arr2 = ("[ ,]+");
        for (String s : arr2) {
            (s);
        }
        ("--------------------------");
        //Supplement two methods equals; compareTo();        String s1 = "hello";
        String s2 = "Hello";
        ((s2));  //false
        ((s2));    //Ignore case true
        String s3 = "abc";  //a is 97        String s4 = "xyz";  //x is 120        ((s4));   //The ASCII code value of the first character of two strings is subtracted -23, the first one is the same, the next one is reduced and so on
        String s5 = "abc";
        String s6 = "abcxyz";
        ((s6));   //S5 is just in front of s6, so the length is -3    }
}
Case Study
package .demo07;

//Case demonstration//It is known that String str = "this is a text";/*
 * Get the words in str separately
 * Replace text in str with practice
 * Insert an easy in front of the text
 * Change the first letter of each word to capitalize

 * */
public class Test4 {
    public static void main(String[] args) {
        String str = "this is a text";
        //Get the words in str separately        String[] arr = (" ");
        for(String str1 : arr) {
            (str1);
        }

        //Replace text in str with practice       String s1 = ("text", "practice");

        //Insert an easy in front of the text        String s2 = ("text", "easy text");

        //Change the first letter of each word to capitalizefor(int i = 0; i &lt; ; i++) {
    char first = arr[i].charAt(0);
    char upperFirst = (first);
    String s3 = upperFirst+arr[i].substring(1);


}

    }

}

StringBuffer and StringBuilder

  • StringBuffer: Variable long string, slow running efficiency, thread-safe For multi-threading
  • StringBuilder: Variable long string, fast running efficiency, unsafe threads for single thread

Higher efficiency than String, more memory saving than String

The StringBuffer and StringBuilder methods are common, and the common methods are as follows

package .demo08;

public class Demo01 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        //(); additional        ("Java World No. 1");
        (());
        ("Java is so fragrant");
        (());
        //(); Add to        (0,"I'm in the front");
        (());
        //();
        (0, 4, "Hello");  //The head and the tail are still left        (());
        //(); delete        (0, 6);
        (());
        //(); flip        ();
        (());
        //Clear        (0, ());
        (());

    }
}
package .demo08;

public class Demo02 {
    public static void main(String[] args) {
        // Verify that the efficiency of StringBuilder is higher than that of String        long startTime = ();    //Start time        String string = "";
        for (int i = 0; i &lt; 999; i++) {
            string += i;    //Sticking of strings        }
       
        (());
        long endTime = ();
        ("Time to use"+ (endTime - startTime));

    }
}
package .demo08;

public class Demo02 {
    public static void main(String[] args) {
        // Verify that the efficiency of StringBuilder is higher than that of String        long startTime = ();    //Start time        
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i &lt; 999; i++) {
            (i);
        }
        (());
        long endTime = ();
        ("Time to use"+ (endTime - startTime));
    }
}

BigDecimal

  • Location: In the package
  • Function: accurately calculate floating point numbers
  • Creation method: BigDecimal bd = new BigDecimal("1.0");
package .demo08;

import ;

public class Demo03 {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.9;
        (d1 - d2);
        //Output result 0.099999999999...        //In many practical applications, precise calculation is required, while double is an approximate value storage, which requires the help of BigDecimal        double result = (1.4 - 0.5) / 0.9;
        (result);


        //BigDecimal, accurate calculation of large floating point numbers        BigDecimal bd1 = new BigDecimal("1.0"); // Use string        BigDecimal bd2 = new BigDecimal("0.9");
        ((bd2));  //Subtraction        ((bd2));   //addition        ((bd2));  //multiplication
        BigDecimal result1 = new BigDecimal("1.4").subtract(new BigDecimal("0.5")).divide(new BigDecimal("0.9"));
        (result1);

        //Improved the situation        //BigDecimal r = new BigDecimal("10").divide(new BigDecimal("3")); //Exception occurs        BigDecimal r = new BigDecimal("10").divide(new BigDecimal("3"), 2, BigDecimal.ROUND_HALF_UP);   //Retain two decimal places and round it up        (r);


    }

}

Date class

Date represents a specific moment, accurate to milliseconds. Most methods in Date have been replaced by methods in Calendar class

package .demo08;

import ;

public class Demo04 {
    public static void main(String[] args) {

        //1. Create a Date object        //today        Date date1 = new Date();
        (());   //Print the current time and connect with spaces        (()); //Print the current time Use - Connect, it has expired
        //yesterday        Date date2 = new Date(() - 24 * 60 * 60 * 1000);
        (());
        //Method after before       boolean b1= (date2);
        (b1);
        boolean b2= (date2);
        (b2);

        //Compare compareTo();        int d = (date2); //Compare the millisecond values ​​of the two. Subtract the millisecond values. Positive numbers return 1, negative numbers return -1        (d);

        //The comparison number is equals        boolean b3 = (date2);
        (b3);
        
    }
}

Calendar class

package .demo08;

import ;

public class Demo05 {
    public static void main(String[] args) {
        //Create Calendar object        Calendar calendar = (); //Calendar is protected and cannot be directly new        (());    //There are a lot of prints, not the form we want to see        (().toString());  //Convert calendar to date class        (());
        //Get time information        //Get year        int year = (); //You can also write it as 1, which means it is poorly readable        (year);
        //Get month From 0-11, 0 represents January        int month = ();
        (month);
        //Get date        int day = (Calendar.DAY_OF_MONTH);
        (day);
        //Get hours        int hour = (Calendar.HOUR_OF_DAY);  //24-hour system        int hour2 = ();    //12-hour system        (hour);
        (hour2);
        //Get minutes        int minute = ();
        (minute);
        //Get seconds        int second = ();
        (second);

        (year+"Year"+(month+1)+"moon"+day+"day"+hour+":"+minute+":"+second);

        //Modification time        Calendar calendar2 = ();
        (Calendar.DAY_OF_MONTH, 5);    //Modification date        (().toLocaleString());

        //add modification time        (, 1);
        (().toLocaleString());
        (, -1);   //Reduce time        (().toLocaleString());

        //Replenish        int max = (Calendar.DAY_OF_MONTH);  //Get the maximum day of the month        (max);
        int min = (Calendar.DAY_OF_MONTH);  //Get the minimum day of the month        (min);
    }
}

SimpleDateFormat class

Convert dates to specific formats

 package .demo08;
 ​
 import ;
 import ;
 import ;
 ​
 public class Demo06 {
     public static void main(String[] args) throws ParseException {
         //Create SimpleDateFormat object y year M month d day H hour m minute s seconds         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 ​
         //Create a Date         Date date = new Date();
 ​
         //Format Date to convert date into string         ((date));
 ​
         //Analysis Convert string to date         Date date2 = ("2025-5-11 12:00:00");   //The format is the same as the pattern above         (date2);
 ​
     }
 }

System class

Mainly used to fight against the system attribute data and other operations, the construction method is private

 package .demo08;
 ​
 public class Student {
     private String name;
     private int age;
 ​
     public Student(String name, int age) {
          = name;
          = age;
     }
 ​
     public Student() {
 ​
     }
 ​
     public String getName() {
         return name;
     }
 ​
     public void setName(String name) {
          = name;
     }
 ​
     public int getAge() {
         return age;
     }
 ​
     public void setAge(int age) {
          = age;
     }
 ​
     @Override
     public String toString() {
         return "Student{" +
                 "name='" + name + '\'' +
                 ", age=" + age +
                 '}';
     }
 ​
     @Override
     protected void finalize() throws Throwable {
         ("Recycled"+name+" "+age);
     }
 }
 package .demo08;
 ​
 public class Demo07 {
     public static void main(String[] args) {
         //Don't create System object         //arraycopy(); Parameters: src, srcPos (refers to the subscript of src), dest, destPos, length         int[] arr = {1,2,3,4,5,6,7,8,9};
         int[] dest = new int[8];
         (arr,0,dest,0,8);
         for (int i = 0; i &lt; ; i++) {
             (dest[i]);
         }
 ​
         //currentTimeMillis(), gets the current system time and returns the millisecond value. It can be used to calculate the execution time of the code.         (());
 ​
         long start = ();
         for (int i = 0; i &lt; 9999; i++) {
             for (int j = 0; j &lt; 9999; j++) {
                 int result = i+j;
             }
         }
         long end = ();
         ("Time to use"+(end - start));
 ​
 ​
         //(); Recycle garbage ​
         new Student("aaa", 19);
         new Student("bbb", 20);
         Student s3 = new Student("ccc", 21);
 ​
         ();
 ​
         //exit(); Exit jvm         (0);
         ("Program End"); //The previous line of code has ended the program, this line of code will not be executed ​
     }
 }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.