Common classes in java. Detailed summary of wrapper class, Math class, String class, Date class, Calendar class and BigDecimal class

Posted by vijay17877 on Tue, 04 Jan 2022 09:52:24 +0100

Several common classes in Java

enumeration

  • Enumeration refers to a type consisting of a fixed set of constants
  • Keywords: enum
  • Enumeration can have methods and properties, but generally not
public enum Ennum {
    L1,L2,L3
}

public class Application {
    public static void main(String[] args) {
        Application application = new Application();
        application.target(Ennum.L2);
        Ennum[] values = Ennum.values();  // Returns an array of objects of enumeration type
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i]+"\t");
        }
    }
    public void target(Ennum a){
        switch (a){
            case L1:
                System.out.println("Enumeration type I");
                break;
            case L2:
                System.out.println("Enumeration type II");
                break;
            case L3:
                System.out.println("Enumeration type III");
                break;
        }
    }
}
result
 Enumeration type II
L1	L2	L3

Packaging

  • The wrapper class converts the basic data type to an object
  • Each basic type is in Java Lang package has a corresponding wrapper class
  • effect
    • A series of practical methods are provided
    • The collection is not allowed to store the basic data type, but can be converted to the packaging type (automatic unpacking and packing after JDK1.5)

Construction method of packaging class

  1. All wrapper classes have construction methods: take the corresponding basic data type as a parameter
  2. All wrapper classes except Character have construction methods: using string as parameter
public class Application {
    public static void main(String[] args) {
        // All wrapper classes have construction methods: take the corresponding basic data type as a parameter
        Integer integer = new Integer(1);
        Boolean aBoolean = new Boolean(true);
        Character a = new Character('A');
        Float aFloat = new Float(5.6F);
        Double aDouble = new Double(8.5);
        System.out.println(integer+"\t"+aBoolean+"\t"+a+"\t"+aFloat+"\t"+aDouble);
        System.out.println(a instanceof Character);
        // All wrapper classes except Character have construction methods: using string as parameter
        Integer integer1 = new Integer("100");
        Boolean aFalse = new Boolean("world");  // The value is false
        Boolean aTrue = new Boolean("true");   // True is returned only when the string is true, and the rest are false
        Float aFloat1 = new Float("8.6F");
        Double aDouble1 = new Double("5.8");
        System.out.println(integer1+"\t"+aFalse+"\t"+aTrue+"\t"+aFloat1+"\t"+aDouble1);
        System.out.println(integer1 instanceof Integer);
    }
}
result
1	true	A	5.6	8.5
true
100	false	true	8.6	5.8
true

be careful:

  1. When the Boolean class constructor parameter is of String type, if the String content is true (regardless of case), the Boolean object represents true; otherwise, it is false
  2. When the parameter of the wrapper class constructor is of type String, the String cannot be null, and the String must be parsed into the data of the current basic data type. Otherwise, the compilation fails, and the runtime NumberFormatException exception occurs

Common methods of packaging

  • Package class to basic data type: xxxvalue(); = = > All types
public class Test {
    public static void main(String[] args) {
        int num = 10;
        int i = new Integer(num).intValue();
        boolean b = new Boolean(true).booleanValue();
        char a = new Character('A').charValue();
        float v = new Float(5.6F).floatValue();
        System.out.println(i+"\t"+b+"\t"+a+"\t"+v);
    }
}
result
10	true	A	5.6
  • Basic data type to string: (1) toString() (2) + ""
public class Test2 {
    public static void main(String[] args) {
        int num = 10;
        String s = Integer.toString(num);
        String s1 = 9+"";
        String s2 = Boolean.toString(false);
        String a = Character.toString('in');
        String s3 = Float.toString(5.6F);
        System.out.println(s+"\t"+s1+"\t"+s2+"\t"+a+"\t"+s3);
    }
}
result
10	9	false	in	5.6
  • String repackaging class: valueof() = = > (except Character)
public class Test3 {
    public static void main(String[] args) {
        String num = "10";
        Integer integer = Integer.valueOf(num);
        Boolean aFalse = Boolean.valueOf("false");
        Float aFloat = Float.valueOf("8.9");
        Double aDouble = Double.valueOf("5.2");
        System.out.println(integer+"\t"+aFalse+"\t"+aFloat+"\t"+aDouble);
    }
}
result
10	false	8.9	5.2
  • The basic data type is a repackaging class. All methods have
public class Test4 {
    public static void main(String[] args) {
        Integer integer = Integer.valueOf(10);
        Boolean aFalse = Boolean.valueOf(false);
        Float aFloat = Float.valueOf(8.9F);
        Double aDouble = Double.valueOf(5.2);
        String str = String.valueOf("Hello");
        System.out.println(integer+"\t"+aFalse+"\t"+aFloat+"\t"+aDouble+"\t"+str);
    }
}
result
10	false	8.9	5.2	Hello
  • String to basic data type: except Character
public class Test5 {
    public static void main(String[] args) {
        int i = Integer.parseInt("89");
        boolean world = Boolean.parseBoolean("world");
        boolean aTrue = Boolean.parseBoolean("true");
        float v = Float.parseFloat("8.6");
        System.out.println(i+"\t"+world+"\t"+aTrue+"\t"+v);
    }
}
result
89	false	true	8.6
  • boxing and unboxing
    • Boxing: an object whose basic type is converted to a wrapper class
    • Unpacking: the value of the packing class object converted to the basic type

Math class

  • abs(int a): absolute value
  • ceil(double d): round up
  • floor(double d): round down
  • max(int a,int b): maximum
  • Pow (double a, double b): b power of a
  • random(): random number [0.0,1.0]
  • round(float f): round
  • sqrt(double d): arithmetic square root
public class Test6 {
    public static void main(String[] args) {
        int abs = Math.abs(-8);
        double ceil = Math.ceil(-5.6);
        double ceil1 = Math.ceil(8.2);
        double floor = Math.floor(8.4);
        double max = Math.max(5.6, 2.8);
        int pow = (int) Math.pow(2, 3);
        int random = (int) (Math.random()*10);   // Generate a random number between 0 and 9
        long round = Math.round(5.5);
        int sqrt = (int) Math.sqrt(9);
        System.out.println(abs+"\t"+ceil+"\t"+ceil1+"\t"+floor+"\t"+max+"\t"+pow+"\t"+random+"\t"+round+"\t"+sqrt);
    }
}
result
8	-5.0	9.0	8.0	5.6	8	4	6	3

String class

  • Storing strings using String objects
  • length() method
    • Determines the length of a string and returns the number of characters in the string
  • equals() method
    • Check that the characters that make up the contents of the string are exactly the same
public class Test7 {
    public static void main(String[] args) {
        String s1 = "Hello World!";
        String s2 = new String();
        String s3 = new String("Hello World.");
        System.out.println(s1+"\t"+s2+"\t"+s3);
        System.out.println(s3.length());
        System.out.println(s1.equals("Hello"));
    }
}
result
Hello World!		Hello World.
12
false

Note: the difference between "= =" and equals()

  1. When comparing basic data types

    Only "= =" can be used, and the value is compared

  2. When comparing reference data types

    "= =" compares the memory address of the reference object;

    Equals is divided into two cases, if the class does not override the equals () method. When comparing two objects of this class through equals(), it is equivalent to comparing the memory addresses of the two objects through "= ="; If the class overrides the equals () method. Then the comparison is whether the contents of the two objects are equal (generally rewritten); Returns true if their contents are equal (that is, the two objects are considered equal).

  • Other methods of string comparison
    • equals(Object obj): compares whether two strings are equal
    • Equalsinnorecase (object obj): ignore case and compare whether two strings are equal
    • contains(String str): whether to include the specified string
    • startsWith(String str): whether to start with the specified string
    • endWith(String str): whether to end with the specified string
    • isEmpty(): is it empty
    • matches(String regex): determines whether the string matches the given regular expression.
public class Test7 {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "hello";
        System.out.println(s1.equals(s2));
        System.out.println(s1.toLowerCase().equals(s2.toLowerCase()));
        System.out.println(s1.toUpperCase().equals(s2.toUpperCase()));
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}
result
false
true
true
true
  • String connection
    • Method 1: use "+"
    • Method 2: use the concat() method of the String class
public class Test8 {
    public static void main(String[] args) {
        String s1 = "Hello World!";
        String s2 = "Hello world";
        System.out.println(s1+s2);
        System.out.println(s1.concat(s2));
    }
}
result
Hello World!Hello world
Hello World!Hello world

Common string extraction methods

Note: all operations of String do not affect the String itself, but a copy of the String (String is immutable)

  • String splitting

    Splits a string into substrings and returns the result as a string array

public class Test9 {
    public static void main(String[] args) {
        String string = "I love you China,I love you Beijing";
        String[] s = string.split(""); // An empty string indicates that each character is separated
        int count = 0;
        String c = "love";
        for (int i = 0; i < s.length; i++) {
            if (s[i].equals(c)){
                count++;
            }
        }
        System.out.println(c+"The number of occurrences is:"+count+"second");
    }
}
result
 Times of love: 2

StringBuffer class

When the string is frequently modified (such as string connection), the use of StringBuffer class can greatly improve the execution efficiency of the program.

  • StringBuffer declaration
    • StringBuffer str1 = new StringBuffer();
    • StringBuffer str2 = new StringBuffer("aaa");
  • Used buffer string
    • str1.toString(); // Convert to String type
    • str1.append("**"); // Append string
    • str1.insert (1, “**”); // Inserts a string at the specified location
    • deleteCharAt(int index): deletes the element at the specified index
    • String subString(int start): intercept the specified position to the end
    • String subString(int start,int end): intercept the [start,end-1] range

Note: StringBuffer is different from the String class. Its operation changes the String itself, and the operation of String changes the copy.

Extension:

What is the difference between String, StringBuilder and StringBuffer?

String content cannot be changed
The contents of StringBuilder and StringBuffer are variable
StringBuilder is thread unsafe, asynchronous and efficient
StringBuffer is thread safe, synchronous and inefficient

Date class

  • Operation date and time: obtain the current system time and output it in the specified format. In Java util. Date package and Java text. Simpledateformat package.
public class Test9 {
    public static void main(String[] args) {
        //Create date object
        Date date = new Date();
        //Custom date format
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = format.format(date);
        System.out.println(now);

    }
}
result
2022-01-02 22:05:57

Calendar Class

Used to set and get specific parts of date / time data.

public class Test11 {
    public static void main(String[] args) {
        Calendar instance = Calendar.getInstance();
        int i = instance.get(Calendar.YEAR);
        System.out.println(i+"\t"+(instance.get(Calendar.MONTH)+1)+"\t"+instance.get(Calendar.DAY_OF_MONTH));
        System.out.println("Today is the third day of the week"+instance.get(Calendar.DAY_OF_WEEK)+"day");
    }
}
result
2022	1	2
 Today is the first day of the week

BigDecimal class

It is used to solve the problem of precision loss of floating-point operation
1) Construction method

  • BigDecimal(String s): creates a BigDecimal object from characters

2) Member method

  • add(BigDecimal bi):+
  • subtract(BigDecimal bi):-
  • multiply(BigDecimal bi)😗
  • divide(BigDecimal bi)😕
public class Test12 {
    public static void main(String[] args) {
        BigDecimal a = new BigDecimal("1.2");
        BigDecimal b = new BigDecimal("3.6");
        System.out.println("a+b="+a.add(b));
        System.out.println("a-b="+a.subtract(b));
        System.out.println("a*b="+a.multiply(b));
        // The result is rounded to two decimal places
        System.out.println("a/b="+a.divide(b,2,BigDecimal.ROUND_HALF_UP));
    }
}
result
a+b=4.8
a-b=-2.4
a*b=4.32
a/b=0.33

rounding mode

  • ROUND_CEILING / / round to positive infinity
  • ROUND_DOWN / / round to zero
  • ROUND_FLOOR / / round to negative infinity
  • ROUND_HALF_DOWN / / round to the nearest side unless the two sides are equal. If so, round down, for example, 1.55, and keep one decimal place. The result is 1.5
  • ROUND_HALF_EVEN / / round to the nearest side unless both sides are equal. If so, if the reserved digits are odd, use
  • ROUND_HALF_UP, if even, use ROUND_HALF_DOWN
  • ROUND_HALF_UP / / round to the nearest side unless the two sides are equal. If so, round up to 1.55 and keep one decimal place. The result is 1.6, which is what we often call "rounding"
  • ROUND_UNNECESSARY / / the calculation result is accurate, and the rounding mode is not required
  • ROUND_UP / / rounding away from 0

Topics: Java Back-end