Java Common Classes: 7000 + words to help you summarize at once!

  • Overview of Common Classes

  • Internal Class

    • Classification of internal classes:

    • 1. Member internal classes (non-static internal classes)

    • 2. Local Internal Classes

    • 4. Anonymous Internal Class

  • Object class

    • Object class common methods:

    • 1. Equas method

    • 2.hashCode method

    • 3.toString method

    • 4.finzlize method

  • Packaging Class

    • "1. Basic data types and corresponding packaging classes:"

    • "2. Significance of Packaging Classes:"

    • 3. Common methods of packaging classes:

  • Mathematical Classes

  • Time Class

    • Java Common Time Classes:

    • 1.Date date

    • 2.Calendar Calendar

    • 3.SimpleDateFormat Format Time

    • 4. Calculate time difference

  • String Class

    • Common String Class Methods

  • String Builder and String Buffer

  • DecimalFormat

  • summary

Overview of Common Classes

  1. Internal Class

  2. Object class

  3. Packaging Class

  4. Mathematical Classes

  5. Time Class

  6. Character string

  7. String Builder and String Buffer

  8. DecimalFormat

Internal Class

"Concept": Define a complete class within a class.

In general, classes and classes are independent of each other. Internal classes mean to break this independent idea and make one class the internal information of another class, at the same level as member variables and member methods.

"Benefits of internal classes:"

Writing a class outside and inside will ultimately produce the same results. Why should we use an internal class instead?

"Internal classes are a technology that hides details and internal structure, provides better encapsulation, and makes the structure of the program more rational! If there are many classes and they are exposed, the calls between classes will be cumbersome!"

Classification of internal classes:

1. Member internal classes (non-static internal classes)

The reference code is as follows:

package NeiBuLei;
public class OuterClass {
    //Member variables
    private String OuterName;
    //Member Method
    public void display(){
        System.out.println("This is an external class method!");
        System.out.println(OuterName);
    }
    //Internal Class
    public class InnerClass{
        //Member variables
        private String InnerNme;
        //Construction method
        public InnerClass() {
            InnerNme = "Inner Class";
        }
        //Member Method
        public void display(){
            System.out.println("This is an internal class method!");
            System.out.println(InnerNme);
        }
    }
    //Main method
    public static void main(String[] args) {
        OuterClass outerClass = new OuterClass();
        outerClass.display();//This is an external class method! null

        //This class is an internal class and is no longer a stand-alone class, so it cannot be created directly like an external class!
        //InnerClass innerClass = new InnerClass(); Impossible
        OuterClass.InnerClass innerClass = outerClass.new InnerClass();//Same member method/variable just prefixed
        innerClass.display();//This is an internal class method!
    }
}

Output results:

This is an external class method! null This is an internal class method! Inner Class

"Summary: The use of member internal classes (non-static internal classes) is to use internal classes as a member variable/member method of external classes, so objects that depend on external classes must be invoked in accordance with member variable/member methods!"

2. Local Internal Classes

Local internal classes: Basic internal classes can also be defined in a single method body.

package NeiBuLei;
public class OuterClass {
    //Member variables
    private String OuterName;
    //Member Method
    public void display(){
        class InnerClass {
            public void print(){
                System.out.println("This is a local internal class method!");
            }
        }
        InnerClass innerClass = new InnerClass();
        innerClass.print();
    }

    //Main method
    public static void main(String[] args) {
        OuterClass outerClass = new OuterClass();
        outerClass.display();
    }
}
  1. Static Internal Class

The construction of static internal classes does not depend on external class objects, and the static components in a class do not depend on any objects. They can be constructed directly from the Class itself.

package NeiBuLei;
public class OuterClass {
    //Member variables
    private String OuterName;
    //Member Method
    public void display(){
        System.out.println("This is an external class method!");
        System.out.println(OuterName);
    }
    //Static Internal Class
    public static class InnerClass{
        private String InnerName;
        public InnerClass() {
            InnerName = "Inner Class";
        }

        //Member Method
        public void display(){
            System.out.println("This is a static internal class method!");
            System.out.println(InnerName);
        }
    }

    //Main method
    public static void main(String[] args) {
        OuterClass outerClass = new OuterClass();
        outerClass.display();
        //The construction of static internal classes is independent of external classes and can be constructed directly from the class itself!
        InnerClass innerClass = new InnerClass();
        innerClass.display();
    }
}

Output results:

This is an external class method! null This is a static internal class method! Inner Class

4. Anonymous Internal Class

Anonymous inner class: An inner class without a name.

Anonymous Internal Class "Implementation of Primary Applications and Interfaces!"

Interface:

package NeiBuLei;
public interface MyInterface {
    public void test();
}

Implementation class:

package NeiBuLei;
public class MyImplement implements MyInterface{
    @Override
    public void test() {
        System.out.println("test");
    }
}

Use of anonymous internal classes:

package NeiBuLei;
public class MyImplement implements MyInterface{
    @Override
    public void test() {
        System.out.println("test");
    }
}

"Benefits of anonymous internal classes:"

After we have defined the interface, "its implementation class does not need to create a separate file to write its implementation". We can write the operation of this implementation class to the place we call it. It is more concise and convenient to write.

"Disadvantages of anonymous internal classes:"

Coupling is too high!

Object class

Disadvantages of anonymous internal classes

Object class common methods:

1. Equas method

"==comparison with equals [Interview Question]+ jdk View Source"

==is a comparison operator

  1. ==: You can judge not only the basic type but also the reference type.

  2. ==: If the basic type is judged, the value is equal.

//==: If the basic type is judged, the value is equal
int x1 = 10;
int x2 = 10;
double x3 = 10.0;
System.out.println(x1 == x2);//true
System.out.println(x1 == x3);//true
  1. ==: If you are judging the Reference Type, you are judging whether the addresses are equal, that is, whether they are the same object.

package Equals;
public class Test01 {
    public static void main(String[] args) {
        //==: If you are determining the type of reference, you are determining whether the addresses are equal, that is, whether they are the same object.
        A a = new A();
        A b = a;
        A c = b;
        System.out.println(a==c);// ? true
        System.out.println(b==c);// true
        B obj = a;
        System.out.println(obj==c);// true
    }
}

class B{}
class A extends B{}

picture

  1. The equals method is a method in the Object class,'only reference types can be determined'.

idea view Jdk source: mouse cursor on the method to view, enter ctrl + b directly

View all methods of a class: ctrl + F12

  1. The default judgment is whether the addresses are equal, "Subclasses (Object classes are the parent of all classes) often override this method to determine if the contents are equal."

/*
Object Class equals() method source code

//Default judgement of whether addresses are the same
    public boolean equals(Object obj) {
        return (this == obj);
    }
    
Subclasses often override this method to determine if content is equal. The equals() method source code in the String class (overrides the parent equals() method)
  
    public boolean equals(Object anObject) {
        if (this == anObject) { // If it's the same object (same address)
            return true; // Return true
        }
        if (anObject instanceof String) { // Type of judgment
            String anotherString = (String)anObject; // Downward transition
            int n = value.length;
            if (n == anotherString.value.length) { // If the lengths are the same
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) { // Compare each character
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true; // Returns true if both strings are identical in each character
            }
        }
        return false;
    }
 */

Take an example

picture

[Small Practice]

Write out the output:

package Equals;
public class EqualsTest01 {
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.name = "tom";
        Person p2 = new Person();
        p2.name = "tom";
        System.out.println(p1 == p2);//Reference Type - Determine if the same object (address)
        System.out.println(p1.name.equals(p2.name));//p.name is a String type and overrides the equals() method to determine if the content is the same
        System.out.println(p1.equals(p2));//p1,p2 belongs to the Person class, which does not override the equals() method (inherit the parent equals() method, that is, determine the address)

        String s1 = new String("abc");
        String s2 = new String("abc");

        System.out.println(s1.equals(s2));
        System.out.println(s1 == s2);
    }
}

class Person{
    public String name;
}

Output results:

false true false true false

2.hashCode method

picture

Summary: (can be viewed as an address but it is not an address in nature)

  1. Improving the efficiency of containers with hash structure

  2. Two references, if they point to the same object, the hash must be the same

  3. Two references, if they point to different objects, the hash values are different

  4. Hash values are based primarily on address numbers! Hash values cannot be fully equivalent to addresses

  5. hashCode will also be overridden in subsequent collections if needed

package hashCode;
public class HashCode {
    public static void main(String[] args) {
        AA aa = new AA();
        AA aa2 = new AA();
        AA aa3 = aa;
        System.out.println("aa.hashCode()="+ aa.hashCode());
        System.out.println("aa2.hashCode()="+ aa2.hashCode());
        System.out.println("aa3.hashCode()="+ aa3.hashCode());
    }
}

class AA{}

Output results:

aa.hashCode()=460141958 aa2.hashCode()=1163157884 aa3.hashCode()=460141958

3.toString method

toString method

Basic Introduction:

Default return: hexadecimal for full class name + @ +hash value

/*
    Object toString()Source Code
    //(1)getClass().getName() Full class name of class (package name + class name)
    //(2)Integer.toHexString(hashCode()) Converts the hashCode value to a hexadecimal string
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
 */

picture

"Subclasses often override the toString method to return the object's attribute information (shortcut: alt + insert), although we can customize it for ourselves."

picture

When we output an object, the toString() method is called by default

picture

4.finzlize method

picture

finzlize method: When garbage collection determines that there is no longer a reference to this object, the garbage collector calls it on the object.

  1. When an object is recycled, the finzlize method of the object is automatically called. Subclasses can override this method to do some resource-free operations

  2. When an object is recycled: When an object has no reference, the jvm considers it a garbage object, the garbage collection mechanism destroys the object, and the finzlize method is called before destroying the object.

picture

  1. The call to the garbage collection mechanism is determined by the system (i.e. has its own GC algorithm) or can actively trigger the garbage collection mechanism through System.gc().

Note: The finzlize method is rarely used in actual development, but rather for interviews

Packaging Class

"1. Basic data types and corresponding packaging classes:"

byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean

These classes are in the java.lang package

"2. Significance of Packaging Classes:"

  1. Making basic data types object-oriented

  2. "Encapsulates how strings are converted to basic data types (emphasis)"

3. Common methods of packaging classes:

  1. Integer.parseInt()

  2. Long.paseLong()

  3. Double.parseDouble()

[Reference Code]

public class Test {
    public static void main(String[] args) {
        
//Integer i = new Integer(10);// Create wrapper class object
//Integer ii = 10; // Automatic Packaging
//System.out.println(i+10); // In use, int and Integer are virtually identical and can be used with each other
//        System.out.println(ii+10);
//int j = ii; // Automatic unpacking
//        System.out.println(j+100);

        String a = "12";
        String b = "34";
        System.out.println(a+b); // 1234
    //Transition:
        //Unique scheme for string to int
        int c = Integer.parseInt(a);
        int d = Integer.parseInt(b);
        System.out.println(c+d); // 46
        
        //Convert string to double type
        String e = "1.25";
        double f = Double.parseDouble(e);
        System.out.println(f*6); // 7.5

        //Convert to long type
        long l = Long.parseLong("1234567");
        System.out.println(l);
    }
}

Mathematical Classes

Math class methods are static methods and can be directly referenced - Math.

"Common Mathematical Class Methods:"

  1. abs(): Gets the absolute value

  2. max(): Maximum

  3. min(): Find the minimum

  4. pow(): exponentiation

  5. round(): rounding

  6. sqrt(): find the square root

Time Class

Java Common Time Classes:

  1. Date Date Class

  2. Calendar Calendar Class

  3. SimpleDateFormat Format Time Class

Date and alendar classes in java. In the util package, the SimpleDateFormat class is in the java.text package

1.Date date

[1] new Date() can get the system time

[2] getTime() takes the long form of time and can be used to calculate the time difference

getTime() - Gets the number stored at the bottom of the computer and returns a number that represents the time in milliseconds of long type.

[Reference Code]

import java.util.Date;
public class Test {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d); //System Time
        //get... () - get the day, month, year...
        System.out.println(d.getYear()+1900); //Calculated since 1900
        System.out.println(d.getMonth()+1); //Month starts at 0
        System.out.println(d.getDate()); //Days
        System.out.println(d.getHours());//Hours

        //getTime() - Gets time in milliseconds and returns long
        System.out.println(d.getTime());
    }
}

2.Calendar Calendar

[1] get() gets a part of time

[2] set() Set Time - > Calculate Time: The system has been set up for us, there is no need to worry about how many days there are in February, the calculation time is very convenient

Note: The Calendar calendar class is abstract, so the new object cannot be removed. Although abstract classes cannot create objects, jdk officially provides an operation on instance objects:

Calendar rightNow = Calendar.getInstance();

We built a Calender object directly from this code

[Reference code]: get() gets a part of the time:

package date;
import java.util.Calendar;
public class TestCalendar {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
//        System.out.println(cal);
        
        /*
 Assume the day:
        2021
        8
        10
         */
  cal.set(Calendar.DATE,cal.get(Calendar.DATE)+31); //Calculate time (in days here)
        
        //Get everything in the object created by Calendar
        System.out.println(cal.get(Calendar.YEAR)); //2021
        System.out.println(cal.get(Calendar.MONTH)+1); //Month: Start from 0. Result: October
        System.out.println(cal.get(Calendar.DATE)); //Day
        System.out.println(cal.get(Calendar.HOUR_OF_DAY));//Hours
        System.out.println(cal.get(Calendar.MINUTE));
        System.out.println(cal.get(Calendar.SECOND));
    }
}

[Reference code]: set() Set time - > Calculate time:

Note: cal.setTime(d); Convert Date to Calendar

package date;
import java.util.Calendar;
import java.util.Date;
public class TestCalendar {
    public static void main(String[] args) {
        Date d = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);//Convert Date to Calendar
        System.out.println(cal);
        System.out.println(cal.get(Calendar.YEAR)); //Year
        System.out.println(cal.get(Calendar.MONTH)+1); //Month: 0-based
        System.out.println(cal.get(Calendar.DATE)); //Day
    }
}

3.SimpleDateFormat Format Time

Date, Calendar can also format time by reference, but it is cumbersome, and the SimpleDateFormat class is a tool class specifically designed to help us format time, which is in the java.text package.

[Time Format]: yyyy-MM-dd HH:mm:ss

The SimpleDateFormat class has two common methods:

[1]format(Date):

format(Date) helps us convert time to a string in the format set when the SimpleDateFormat class defines objects

[Reference Code]

package Simple;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
public class Test {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d); //Thu Aug 12 08:40:08 CST 2021

  //Set the formatting time mode, which we commonly use yyyy-MM-dd HH:mm:ss
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//Time Format
        String s = sdf.format(d); //Formatting time
        System.out.println(s); // 2021-08-12 08:45:09
    }
}

[2]parse(String):

parse(String) helps us convert strings to time

[Reference Code]

package Simple;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Test2 {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a time(yyyy-MM-dd HH:mm:ss): ");
        String s = sc.nextLine();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       Date d =  sdf.parse(s); //Convert string to time
        System.out.println(d);        
        /*
        Please enter a time (yyyy-MM-dd HH:mm:ss):
        2021-08-12 12:25:21
        Thu Aug 12 12:25:21 CST 2021
         */
    }
}

Note: Since the strings entered by the user are not necessarily in the format we want, it may be anything, and it is impossible to convert them to time. You cannot convert a person to time, so there is a great risk that the unhandled (exception: java.text.ParseException) will be required to handle the exception.

4. Calculate time difference

Calculation ideas:

  1. Formatting time

  2. Convert string to long type time first

  3. Calculate millisecond level time difference, take absolute value

  4. Millisecond level time difference to second level

  5. Time difference in seconds to minute level

  6. Minute level time difference converted to xx hours xx minutes

[Reference Code]

package Simple;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDiff {
    public static void main(String[] args) throws ParseException {
        String s1 = "2021-08-12 12:00:00"; //Start time
        String s2 = "2021-08-12 14:35:00"; //End time
        //Formatting time
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        //Convert string to time
        Date d1 = sdf.parse(s1);
        Date d2 = sdf.parse(s2);

        //Calculate time difference: Get time in milliseconds (long type) before making a difference
        long long1 = d1.getTime();
        long long2 = d2.getTime();
        long diffTime = Math.abs(long1 - long2);

        //Seconds level time difference
        long diffSec = diffTime / 1000;

        //Grading time difference
        long diffMin = diffSec / 60;

        //Display xx hours xx minutes
        long displayHours = diffMin / 60; //Hours
        long displayMin = diffMin % 60; //Minute
        System.out.println("You have been studying for:"+displayHours+"hour"+displayMin+"Minute");
    }
}

String Class

Common String Class Methods

"Method Summary:"

"Note: Strings are an immutable type (final class), and almost all string operations return a new string instead of modifying it on its original basis."

[Sample Code]

public class Test {
    public static void main(String[] args) {
        String s = "My name is Li Hua";        
        s.concat("hhh"); //Split on string s, splice hhh
        System.out.println(s);//My name is Li Hua
        //Strings are immutable data types
        //Almost all string operations return a new string
        String s1 = s.concat("hhh"); //Split on string s, splice hhh
        System.out.println(s1);//My name is Li Hua hhh.
        
        String str1 = "Li Hua likes to watch Mr. Luo's video";
        str1.replace("Li Hua","Zhang San");
        System.out.println(str3); //Li Hua likes to watch Teacher Luo's videos without replacing strings with the same str1 or str1

        String str2 = str1.replace("Li Hua","Zhang San");//Almost all string operations return a new string. New strings are joined with new variables
        System.out.println(str2);//Zhang San likes to watch Teacher Luo's video.
   }
}
package String;
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        String s = "My name is Li Hua";
        System.out.println(s.charAt(0)); //Get the character at position 0
        s.concat("hhh");
        System.out.println(s);//My name is Li Hua
        //Strings are immutable data types
        //Almost all string operations return a new string
        String s1 = s.concat("hhh"); //Split on string s, splice hhh
        System.out.println(s1);//My name is Li Hua hhh
        System.out.println(s.contains("Li Hua")); //true
        System.out.println(s.contains("Oxford")); //false
        System.out.println("Invite Li Hua to an English Salon".endsWith("activity"));//true to determine whether to end with xxx
        System.out.println("Invite Li Hua to an English Salon".startsWith("Li Hua"));//false judges whether to start with xxx

        //Is the equals string content the same

        //Enter the verification code when Li Hua accepts the invitation to participate
//        String yanZhengMa = "AAkm";
//
//        Scanner sc = new Scanner(System.in);
//
//System.out.println("Please enter the verification code ("+yanZhengMa+)");
//
//        String userInput = sc.nextLine();
//
//if(yanZhengMa.equalsIgnoreCase("aakm"){// Ignore case to determine if the contents on both sides are the same
//System.out.println("Welcome to the English Salon Event!");
//        }else{
//System.out.println("You are not invited, please sign up on site!");
//        }

//String str = "Li Hua has a good time!";
//System.out.println(str.indexOf("happy");// 5. Calculate where the first occurrence of a given string occurs

        String str2 = "Li Hua did well";
        System.out.println(str2.length()); //6. Calculate the length of the string

        String str3 = "Li Hua likes to watch Mr. Luo's video";
        str3.replace("Li Hua","Zhang San");
        System.out.println(str3); //Li Hua likes to watch Teacher Luo's videos without replacing strings with the same str3 or str3

        String str4 = str3.replace("Li Hua","Zhang San");//Almost all string operations return a new string. New strings are joined with new variables
        System.out.println(str4);//Zhang San likes to watch Mr. Luo's video
        String str5 = "Ha-ha_Ha-ha_Hip-and-Hop_Oh no";
        String[] ss = str5.split("_");//cutting
        System.out.println(ss[0]);//Ha-ha
        System.out.println(ss[1]);//Ha-ha
        System.out.println(ss[2]);//Hip-and-Hop
        System.out.println(ss[3]);//Oh no

        String str6 = "It's a nice day today";
        System.out.println(str6.substring(2,4));//Weather String Interception [] Left Close Right Open, Not Right

        String str7 ="     Ha    Ha      ";
        System.out.println(str7.trim());//Remove spaces on the left and right sides
        int i = 10;
        System.out.println(String.valueOf(i)); //Convert basic data type to string
        System.out.println(i+""); //Wild Road
    }
}

String Builder and String Buffer

"Disadvantages of String Class:"

String is an immutable data type that produces a new string for each stitch, and sooner or later memory will be filled with the stitched strings.

"The difference between String class and StringBuilder and StringBuffer class:"

StringBuilder and StringBuffer:'Variable strings, do not produce new objects, save memory'. StringBuffer and StringBuilder are recommended for large number of string splicing, but they are implemented in almost the same way as String.

"StringBuffer and StringBuilder classes:"

[Similarity]

They are used the same way and can be considered a class

[Difference]

  1. StringBuffer thread-safe, StringBuilder non-thread-safe.

  2. StringBuilder has a speed advantage over StringBuffer. "StringBuilder classes are recommended in most cases, but they must be used when thread security is required."

String splicing method: append() method

StringBuffer and StringBuilder to String class:

StringBuilder sb = new StringBuilder("Cats like fish"); String s = sb.toString();

[Reference Code]

package String;
public class TestStringBuilder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();//An empty string ""
        StringBuilder sb2 = new StringBuilder("Cats like to eat fish");
        System.out.println(sb2);//Cats like fish

        sb2.append(",Dogs like fish, too");
        System.out.println(sb2);//Additionally, cats like fish and dogs like fish

        sb2.insert(1,"Ha ha ha");
        System.out.println(sb2); //Cats like fish and dogs like fish

        //Operation huan'c described above
        //Convert StringBuilder to String
        String s = sb2.toString();
        System.out.println(s); //Cats like fish and dogs like fish
        //All of the above can replace StringBuilder with StringBuffer, and the result is the same
    }
}

DecimalFormat

DecimalFormat: Format decimals, leaving a few decimal places. Associate with formatting time.

Represents a decimal point

0 and # represent digits, reserve a few digits just as 0 or #

[Reference Code]

import java.text.DecimalFormat;
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        double d= 10/3.0;
        System.out.println(d);//3.3333333333333335
        
        //. Represents a decimal point
        //0 and #denote numbers

        //Keep two decimal places formatted
        DecimalFormat df = new DecimalFormat(".00"); //Or. ##
        String s = df.format(d); //Convert d to the format set above
        System.out.println(s);//3.33
   }
}

summary

All these foundations are indispensable to change and to other classes and functions of Java. Keep the foundation in mind and grow more steadily!

Tags: Java Interview Programmer jvm programming language

Posted by bawla on Tue, 06 Sep 2022 22:11:03 +0530