Java common classes (entry level)

1. String class:

    1) The three classes String/StringBuffer/StringBuilder are all classes that represent strings.
    2) String: An immutable string, the bottom layer is implemented using final modified char[], and the length cannot be changed.
    3) All methods of StringBuffer are decorated with synchronized, so they are thread-safe, and StringBulider is not thread-safe.
    4) In speed StringBuilder > StringBuffer > String. Therefore, StringBuffer/StringBuilder should be used when dealing with strings with large amounts of data. At the same time, if it is multi-threaded, thread safety should also be considered.

       About immutable strings: The following picture is collected by me on the official website of Power Node. For beginners, it can be understood like this:

    Common operations: These methods are more commonly used but not easy to remember. (In fact, most methods in Java can judge their function according to the method name), only a few methods are listed here. If you want to know more, you can refer to the documentation:

jdk Chinese help documentation

    method type                     method name                                       describe
static String format("%04d-%02d-%02d", year,month, day) Returns a format-controlled string.
String       replace(char old, char new)

Returns a new string obtained by replacing this string with new

All the old appearing in get.

String []      split(String regex, int limit) : Splits this string based on matching the given regular expression.
bolean        startsWith(String prefix): Tests whether this string starts with the specified prefix.
CharSequence  subSequence(int beginIndex, int endIndex) : Returns a new character sequence that is a subsequence of this sequence.
String       substring(int beginIndex) Returns a new string that is a substring of this string.
boolean     contains(CharSequence s)

true if and only if this string contains the specified sequence of char values

Sometimes we can use it to simply determine whether a sequence is a substring of another string.

   The above method mentioned a  CharSequence
    public interface CharSequence: is a readable sequence of char values. This interface provides uniform read-only access to many different kinds of char sequences. If you want to learn more, you can also check the documentation, which is not necessary for beginners.
  

2. Wrapper class: Java provides a corresponding wrapper class for each basic data type

 basic type Packaging class
     byte         Byte
short         Short
int             Integer
long         Long
float         Float
double         Double
char         Character
boolean         Boolean
/*
 static int bitCount(int i)
          返回指定 int 值的二进制补码表示形式的 1 位的数量。
 byte byteValue()
          以 byte 类型返回该 Integer 的值。
 int compareTo(Integer anotherInteger)
          在数字上比较两个 Integer 对象。
 static Integer decode(String nm)
          将 String 解码为 Integer。
 double doubleValue()
          以 double 类型返回该 Integer 的值。
 boolean equals(Object obj)
          比较此对象与指定对象。
 float floatValue()
          以 float 类型返回该 Integer 的值。
 `````

 */
public class IntegerTest {
    public static void main(String[] args) {
        //下面几个字段都是静态常量。
        System.out.println(Integer.MAX_VALUE);//2147483647,即整型表示的有符号最大值
        System.out.println(Integer.MIN_VALUE);//-2147483648,即整型表示的有符合最小值

        //创建一个Integer对象。
        Integer integer = 100;//当然,也可象这样构造一个Integer对象:Integer integer = new Integer(100);
        System.out.println(integer.intValue());//100
    }
}

  

Why provide a wrapper class:

        As we all know, Java is an object-oriented high-level programming language. Object-oriented has many characteristics and attributes, but it is not 100% object-oriented, such as these eight basic data types. Therefore, Java provides their own wrapper classes for these basic data types, so that these basic data types also have some object-oriented features and commonalities.

         For example, the packaging type of int is the Integer class, which inherits Number and of course the Object class. Implements the Comparable interface, the fields are:

                MAX_VALUE: Indicates the maximum value that the int type can represent.
                 MIN_VALUE : Indicates the minimum value that the int type can represent.
                 SIZE : The number of bits used to represent an int value in two's complement form.
                 TYPE : Represents a Class instance of the basic type int.
    There are many more ways. There are no examples here. Other basic types can be compared and understood.

We convert a primitive type to a wrapper type, which is called boxing, and vice versa, unboxing. In Java, boxing and unboxing can be done automatically, so in most cases we do not need to manually create objects of the wrapper class.

3. Java date and time type: In terms of time, no matter which discipline it is from, it will be very difficult if you want to study in depth and pursue quite accurate. As big as the celestial universe, as small as hours, minutes and seconds... There are so many classes about time in java. There are many descriptions and explanations of these time-related classes, interfaces, etc. in the official jdk documentation, and we don't need to go into them.

     1) java.util.Date class: The Date class represents the specified number of milliseconds since the standard base time (called "epoch", that is, January 1, 1970 00:00:00 GMT).


     2) The java.text.SimpleDateFormat class: is a concrete class that formats and parses dates in a locale-dependent manner. It allows formatting (date -> text), parsing (text -> date) and normalization. SimpleDateFormat makes it possible to select any user-defined date-time format pattern. However, it is still recommended to create date-time formatters via getTimeInstance, getDateInstance or getDateTimeInstance in DateFormat.

public class Test01 {

    public static void main(String[] args) throws ParseException {
        //创建一个Date对象,该对象表示当前时间。输出格式:Fri Dec 10 15:20:46 CST 2021
        Date date = new Date();
        System.out.println(date);//Sun Jan 09 13:57:24 CST 2022

        // 将日期对象 date 转成给定格式的字符串:“yyyy年MM月dd日 HH:mm:ss SSS”。
        // 这里的yyyy、MM、dd等符号是 SimpleDateFormat类里面设定好的,并且只能识别这样的符号。还有其他符号可以查看
        // SimpleDateFormat 类的api文档。
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss SSS");
        System.out.println(sdf.format(date));  // 2022年01月09日 13:57:24 053

        //将给定字符串转成Date对象。
        String text = "2035-10-10 00:15:12";
        //注意: 格式串一定要完全匹配日期字符串
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = sdf.parse(text);
        System.out.println( date );//  Wed Oct 10 00:15:12 CST 2035

        //获取当前日历。该对象是以当前时间设置的一个日历
        Calendar calendar1 = Calendar.getInstance();
        //  使用set()来设置一个日历。
        calendar1.set(2200,6,6);
        int year = calendar1.get(Calendar.YEAR);
        int month = calendar1.get(Calendar.MONTH);
        int day = calendar1.get(Calendar.DAY_OF_MONTH);
        
        System.out.println( year+"-"+month+"-"+day);   //  2200-6-6
    }
}


     3) java.util.Calendar class: The class is an abstract class that provides some methods for the conversion between a specific instant and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc. next week's date) provides some methods. An instant can be expressed as a millisecond value, which is an offset from an epoch (ie, 00:00:00.000 GMT, January 1, 1970, Gregorian calendar). This class also provides additional fields and methods for implementing a specific calendar system outside the scope of the package. These fields and methods are defined as protected. Like other locale-sensitive classes, Calendar provides a class method getInstance to obtain a generic object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:
                           Calendar rightNow = Calendar.getInstance(); The
        Calendar object is capable of generating all the calendars needed to implement date-time formatting for a particular language and calendar style Field value, for example, Japanese-Gregorian, Japanese-traditional.
        Calendar defines the range of values ​​returned by certain calendar fields, and what those values ​​mean. For example, for all calendars, the value for the first month of the calendar system is MONTH == JANUARY.
        For beginners like me, it is enough to use the Calendar class to create a calendar, and then operate on the information of the year, month, day, and week.

/*
    在Calendar中有以下属性:
    YEAR 指示年。 MONTH 指示月份。
    DAY_OF_MONTH 指示一个月中的某天。
    DAY_OF_WEEK 指示一个星期中的某天。
    DAY_OF_YEAR 指示当前年中的天数。
    DAY_OF_WEEK_IN_MONTH 指示当前月中的第几个星期。
    HOUR指示当天中的某小时 MINUTE 指示当前小时中的某分钟
    SECOND 指示当前分钟中的某秒
    注意:
        月份是0~11;在西方人们认为星期日是一个星期的起始,所以1~7分别表示星期天到星期六。
    常用方法有get(),set();我们可以借助蓝桥杯往年的一道题目来理解一下:
        世界末日问题:曾有邪教称1999年12月31日是世界末日。当然该谣言已经不攻自破。还有人称
    今后的某个世纪末的12月31日,如果是星期一则会…有趣的是,任何一个世纪末的年份的12月31日都
    不可能是星期一!!于是,“谣言制造商”又修改为星期日…  1999年的12月31日是星期五,请问:未来
    哪一个离我们最近的一个世纪末年(即xx99年)的12月31日正好是星期天(即星期日)?
 */
public class Test02 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        for (int year = 1999; year < 10000; year+=100) {
            calendar.set(year,11,31);//前面说过,月份是从0开始的,所以将 month 设置为11
            if (calendar.get(Calendar.DAY_OF_WEEK)==1){
                System.out.println(year);         //year = 2299
                break;
            }
        }
    }
}

    4. The java.lang.Math class: defines some methods related to mathematical functions.

      1)java.text.DecimalFormat类:

      2) BigInteger/BigDecimal classes: When performing scientific/financial calculations, these two classes are used if the precision is relatively high;

      3) java.util.Random class: used to generate random numbers

public class Test03 {
    public static void main(String[] args) {
        //1) Math.random() 产生[0,1)之间 随机小数
        for(int i = 0 ;  i<10 ; i++){
            System.out.println( Math.random() );
        }

        //2)
        System.out.println( Math.sqrt(100)); 	//平方根
        System.out.println( Math.cbrt(100));	//立方根
        System.out.println( Math.pow(3, 4));	//3的4次方

        //3)
        System.out.println( Math.ceil( 5.6 ));  		//返回大于等于指定数的最小整数   6.0
        System.out.println( Math.floor( 5.6 ));			//返回小于等于指定数的最大整数   5.0

        //4) 两个常量
        System.out.println( Math.PI);
        System.out.println( Math.E);
    }
}


    
 

Guess you like

Origin blog.csdn.net/weixin_52575498/article/details/122392144