[Java SE] 8. Common Java classes

Posted by MorganM on Sat, 25 Dec 2021 22:43:24 +0100

8.1 string related classes

  1. Properties of String:

    1. All string literals (such as "abc") in Java programs are implemented as instances of this class

    2. Is a final class that represents an immutable character sequence and cannot be inherited

    3. String implements Java io. Serializable interface, indicating that the string can be serialized

    4. String implements the comparable < string > interface, indicating that strings can be compared in size

    5. String defines final byte[] value internally; Use and store string data

      public final class String
          implements java.io.Serializable, Comparable<String>, CharSequence,
                     Constable, ConstantDesc {
          @Stable
          private final byte[] value;
      }
      
    6. String represents an immutable character sequence, abbreviated as immutability: it will be recreated as long as it needs to be modified

      1. When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment. Assign a value to a string by literal (different from new). At this time, the string value is declared in the string constant pool (strings with the same content will not be stored in the string constant pool)

        First, judge whether there is "abc" or "hello" in the constant pool. If no constant is created; If there is a direct point

      2. When connecting an existing string, you also need to reassign the memory area assignment, and the original value assignment cannot be used

        String s2 = "abc";
        
        String s3 = s2 + "def";
        System.out.println(s3);//abcdef
        System.out.println(s2);//abc -- s2 will not change
        
      3. When you call the replace() method of String to modify the specified character of String, you also need to reassign the memory area assignment

        String s5 = s2.replace('a','m');
        System.out.println(s2);//abc -- s2 will not change
        System.out.println(s5);//mbc
        
  2. Assignment method of String:

    1. Literal assignment:

      String str = "abc";
      
    2. Creation of String object: constructor of String

      String() 
      //Initialize a newly created String object to represent a null character sequence.
          
      String(char[] value)
      //Assign a new String to represent the character sequence currently contained in the character array parameter.
          
      String(char[] value, int offset, int count) 
      //Assign a new String that contains characters from a sub array of character array parameters. 
          
      String(String original) 
      //Initialize a newly created String object to represent a character sequence with the same parameters; In other words, the newly created String is a copy of the parameter String. 
      String(StringBuffer buffer) 
      //Allocates a new string that contains the sequence of characters currently contained in the string buffer parameter. 
      
    3. Differences between the two methods:

      //By literal definition:
      //At this time, the data abc of s1 and s2 is declared in the string constant pool in the method area
      String s1 = "abc";
      String s2 = "abc";
      
      //Through the new constructor:
      //At this time, the address values stored in s3 and s4 are the space addresses opened up by the data in the heap space
      String s3 = new String("abc");
      String s4 = new String("abc");
      
      System.out.println(s1 == s2);
      System.out.println(s3 == s4);
      

    4. Interview question 1:

      Perdon p1 = new Person("Tom",12);
      Perdon p2 = new Person("Tom",12);
      
      System.out.println(p1.name == p2.name);//true
      
      p1.name = "Jack";
      System.out.println(p2.name);//Tom
      

    5. Interview question 2:

      String s = new String("abc");//How many arrays are created in memory?
      //Two, one is the structure of new in the space, and the other is the data "abc" in the constant pool corresponding to char []
      
  3. String splicing operation:

    1. Conclusion:

      1. The splicing results of constants and constants (literal assignment or final modification) are in the constant pool, and constants with the same content will not exist in the constant pool
      2. As long as one of them is a variable, the result is in the heap
      3. If the result of splicing calls the intern() method, the return value is in the constant pool
  4. Common methods of String:

    1. int length() returns the length of the string

      String s1 = "helloworld";
      System.out.println(s1.length());//10
      
    2. char charAt(int index) returns the character at an index

      System.out.println(s1.charAt(2));//l
      
    3. boolean isEmpty() determines whether it is an empty string

      System.out.println(s1.isEmpty());//false
      
    4. String toLowerCase() String toUpperCase() converts all characters in a string to uppercase and lowercase

      String s2 = s1.toLowerCase();
      String s5 = s1.toUpperCase(Locale.ROOT);
      System.out.println(s2);//helloworld
      System.out.println(s1);//helloworld
      
    5. String trim() returns a copy of a string, ignoring leading and trailing whitespace

      String s3 = "  hello world  ";
      String s4 = s3.trim();
      System.out.println(s4);//hello world
      
    6. boolean equals(Object obj) compares whether the contents of the string are the same

      System.out.println(s1.equals(s4));//false
      
    7. Boolean equalsignorecase (string otherstring) is similar to the equals method, ignoring case

      System.out.println(s1.equalsIgnoreCase(s5));//t
      
    8. String concat(String str) concatenates the specified string to the end of this string. Equivalent to "+"

      String s6 = s3.concat("def");
      System.out.println(s6);//  hello world  def
      
    9. Int CompareTo (string otherstring) compares the size of two strings

      String s7 = "abc";
      String s8 = "abd";
      System.out.println(s7.compareTo(s8));//-1
      
    10. String substring(int beginIndex) returns a new string, which is the last substring of the string intercepted from beginIndex

      String s9 = s2.substring(2);
      System.out.println(s9);//lloworld
      
    11. String substring(int beginIndex, int endIndex) returns a new string, which is a substring intercepted from beginIndex to endIndex (excluding)

      String s10 = s2.substring(2,4);
      System.out.println(s10);//ll
      
    12. boolean endsWith(String suffix) tests whether the string ends with the specified suffix

      System.out.println(s1.endsWith("ld"));//true
      
    13. boolean startsWith(String prefix) tests whether the string starts with the specified prefix

      System.out.println(s1.startsWith("he"));//true
      System.out.println(s1.startsWith("HE"));//false
      
    14. boolean startsWith(String prefix, int toffset) tests whether the substring of this string starting from the specified index starts with the specified prefix

      System.out.println(s1.startsWith("he",0));//true
      
    15. Boolean contains (charsequences) returns true if and only if this string contains the specified char value sequence

    16. int indexOf(String str) returns the index of the specified substring at the first occurrence in this string

    17. int indexOf(String str, int fromIndex) returns the index of the specified substring at the first occurrence in the string, starting from the specified index

    18. int lastIndexOf(String str) returns the index of the last occurrence of the specified substring in this string

    19. int lastIndexOf(String str, int fromIndex) returns the index of the last occurrence of the specified substring in the string, and the reverse search starts from the specified index
      Note: indexOf and lastIndexOf methods return - 1 if they are not found

    20. String replace(char oldChar, char newChar) returns a new string, which is obtained by replacing all oldchars in the string with newChar

    21. String replace(CharSequence target, CharSequence replacement) replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence

    22. String replaceAll(String regex, String replacement) replaces all substrings of this string that match the given regular expression with the given replacement

      String str = "12hello34world5java7891mysql456";
      //Replace the number (d) in the string with "," and remove it if there is "," at the beginning and end of the result
      String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");
      System.out.println(string);
      
    23. String replaceFirst(String regex, String replacement) replaces this string with the given replacement and matches the first substring of the given regular expression

    24. boolean matches(String regex) tells whether the string matches the given regular expression

      String str = "12345";
      //Judge whether all str strings are composed of numbers, that is, 1-n numbers
      boolean matches = str.matches("\\d+");
      System.out.println(matches);
      
      String tel = "0571-4534289";
      //Judge whether this is a fixed line telephone in Hangzhou
      boolean result = tel.matches("0571-\\d{7,8}");
      System.out.println(result);
      
    25. String[] split(String regex) splits the string according to the match of the given regular expression

      String str = "hello|world|java";
      String[] strs = str.split("\\|");   //Cut with "|"
      for (int i = 0; i < strs.length; i++) {
      System.out.println(strs[i]);
      }
      System.out.println();
      
    26. String[] split(String regex, int limit) splits the string according to the matching given regular expression. The maximum number is no more than limit. If it exceeds the limit, all the rest will be placed in the last element

  5. Conversion between String and other structures:

    1. character string → \to → basic data type, wrapper class: call the static method of wrapper class: parseXxx()
    2. Basic data type and packing class → \to → String: call valueOf() overloaded by String
    3. Character array → \to → String: call the constructor of String new String(arr)
    4. character string → \to → character array: call String's toCharArray()
    5. **Byte (binary) array → \to → String: * * call the constructor of String new String(bytes)
    6. character string → \to → byte array: call getBytes() of String
  6. About the use of StringBuffer and StringBuilder

    1. Differences between the three:

      1. String: immutable character sequence; The bottom layer uses char [] storage
      2. StringBuffer: variable character sequence; Thread safety and low efficiency; The bottom layer uses char [] storage
      3. StringBuilder: variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage
    2. Source code analysis:

      String str = new String();
      //Bottom layer: char[] value = new char[0]
      
      String str1 = new String("abc");
      //char[] value = new char[]{'a','b','c'}
      
      StringBuffer sb1 =new StringBuffer();
      //char[] value  = new char[16];
      //The bottom layer creates a char [] with a length of 16
      System.out.println(sb1.length());
      
      sb1.append('a');//value[0] = 'a';
      sb1.append('b');//value[1] = 'b';
      
      StringBuffer sb2 = new StringBuffer("abc");
      //char[] value = new char["abc".length() +16];
      
    3. Capacity expansion:

      If the underlying array of data to be added cannot be placed, the underlying array needs to be expanded. By default, the expansion is twice the original + 2, and the elements in the original array are copied to the new array

    4. Guiding significance:

      Use StringBuffer(int capacity) or StringBuilder(int capacity) in development

    5. Usage: (StringBuffer and StringBuilder are basically the same)

      1. constructor

        1. StringBuffer(): a string buffer with an initial capacity of 16

        2. StringBuffer(int size): constructs a string buffer of the specified capacity

        3. StringBuffer(String str): initializes the content to the specified string content

          //Immutable
          String s = new String("I like learning");
          //variable
          StringBuffer buffer = new StringBuffer("I like learning");
          buffer.append("mathematics");
          
      2. common method

        1. append(xxx): many append() methods are provided for string splicing
        2. delete(int start,int end): deletes the contents of the specified location
        3. replace(int start, int end, String str): replace the [start,end) position with str
        4. insert(int offset, xxx): inserts xxx at the specified position
        5. reverse(): reverses the current character sequence
        6. int indexOf(String str): returns the first occurrence position
        7. String substring(int start,int end): returns a substring in the specified range
        8. int length(): returns the length
        9. char charAt(int n): returns the position of the specified character
        10. Void setcharat (int n, char CH): change the character at the specified position to a new one
    6. Efficiency comparison: StringBuilder > StringBuffer > string

8.2 date time API before JDK 8

  1. java.lang.System class

    1. The public static long currentTimeMillis() provided by the System class is used to return the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970

    2. long time = System.currentTimeMillis();
      System.out.println(time);//1622513200505 (timestamp)
      
  2. java.util.Date class

    1. Represents a specific moment, accurate to milliseconds

    2. Constructor:

      1. Date(): an object created with a parameterless constructor can get the current local time

      2. Date(long date)

        Date date = new Date(1622513500124L);
        
    3. Common methods:

      1. getTime(): returns this Date object since 00:00:00 GMT, January 1, 1970
        The number of milliseconds represented

        Date date = new Date();
        System.out.println(date.getTime());//1622513500124
        
      2. toString(): convert this Date object to the following String: dow mon ddhh:mm:ss zzz yyyy, where: dow is a day of the week (Sun, Mon, Tue,Wed, Thu, Fri, Sat), and zzz is the time standard

        Date date = new Date();
        System.out.println(date.toString());//Tue Jun 01 10:10:46 CST 2021
        
      3. Many other methods are outdated

    4. java.sql.Date corresponds to a variable of date type in the database

      1. How to instantiate:

        java.sql.Date date = new java.sql.Date(1622513500124L);
        System.out.println(date);//2021-06-01
        
      2. java. util. How to convert a date object to Java sql. Date object

        Date date1 = new Date();
        java.sql.Date date2 = new java.sql.Date(date1.getTime());
        System.out.println(date2);//2021-06-01
        
  3. java.text.SimpleDateFormat class

    1. A concrete class that formats and parses dates in a locale independent manner, allowing

      1. Formatting: dates → \to → specify string
      2. Parsing: strings → \to → date
    2. Formatting: SDF format(date)

      //1. Use the default constructor simpledateformat SDF = new simpledateformat(); Date date = new Date(); System. out. println(date);// Tue Jun 01 10:49:27 CST 2021String format = sdf. format(date); System. out. println(format);// 11:13 am on June 1, 2021 / / 2 Use the constructor with parameters simpledateformat SDF1 = new simpledateformat ("yyyy MM DD HH: mm: SS")// Specify the format Date date1 = new Date();String format1 = sdf1.format(date1);System.out.println(format1);//2021-06-01 12:01:11
      
    3. Parsing: SDF parse( )

      //String str = "2019-08-09";
      //Unrecognized exception: ParseException
      
      String str = "2021/6/1 11 a.m:57";  //To conform to the format
      Date parse = sdf.parse(str);
      System.out.println(parse);
      
  4. java. util. Calendar Class

    1. Abstract base class, which is used to complete the function of mutual operation between date fields

    2. Instantiation:

      1. Method 1: create an object of its subclass (Gregorian calendar)

      2. Method 2: call its static method: getInstance()

        Calendar calendar = Calendar.getInstance();
        
    3. Common methods:

      1. get()

        Calendar calendar = Calendar.getInstance();
        int i = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(i);//1
        int i1 = calendar.get(Calendar.DAY_OF_YEAR);
        System.out.println(i1);//152
        
      2. set()

        calendar.set(Calendar.DAY_OF_MONTH,22);
        int i2 = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(i2);//22
        
      3. add()

        calendar.add(Calendar.DAY_OF_MONTH,3);
        //calendar.add(Calendar.DAY_OF_MONTH,-3);
        int i3 = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(i3);//25
        
      4. getTime() calendar class → \to →Date

        Date time = calendar.getTime();
        System.out.println(time);//Modified Fri Jun 25 12:17:19 CST 2021
        
      5. setTime()Date → \to → Calendar Class

        Date date1 = new Date();
        calendar.setTime(date1);
        int i4 = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(i4);//1: Reset back
        

8.3 new date time API in JDK 8

JDK 1.0 includes a Java util. Date class, but most of its methods have been deprecated since JDK 1.1 introduced the calendar class. Calendar is not much better than date. The problems they face are:

  1. Variability: classes like date and time should be immutable
  2. Offset: the year in Date starts from 1900, and the month starts from 0
  3. Formatting: formatting is only useful for Date, not Calendar
  4. In addition, they are not thread safe; Cannot handle leap seconds, etc

Java 8 absorbs the essence of Joda-Time and creates a good API for Java with a new start.

  1. java.time – the base package that contains the value object
  2. java.time.format – format and parse time and date
  1. java. Classes in time:

    1. LocalDate: represents the date in IOS format (yyyy MM DD). It can store birthday, anniversary and other dates
    2. Local time: represents a time, not a date
    3. LocalDateTime: used to represent date and time
  2. method:

    1. now(): a static method that creates an object based on the current time / an object with a specified time zone

      LocalDate localDate = LocalDate.now();
      LocalTime localTime = LocalTime.now();
      LocalDateTime localDateTime = LocalDateTime.now();
      
      System.out.println(localDate);//2021-06-01
      System.out.println(localTime);//12:57:33.350232500
      System.out.println(localDateTime);//2021-06-01T12:57:33.350232500
      
    2. of(): a static method that creates an object based on the specified date / time (regardless of offset)

      LocalDate localDate = LocalDate.of(2021,6,1);
      System.out.println(localDate);//2021-06-01
      
    3. getDayOfMonth() / getDayOfYear() / getDayOfWeek(): the day of the month, year, and week

    4. getMonth(): get the Month and return a Month enumeration value

    5. getMonthValue() / getYear(): obtain the month (1-12) and year

    6. getHour()/getMinute()/getSecond(): get the hour, minute and second corresponding to the current object

    7. withDayOfMonth() / withDayOfYear() / withMonth()/withYear(): modify the month days, year days, month and year to the specified value and return a new object (without considering the offset)

      LocalDateTime localDateTime = LocalDateTime.now();
      LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(22);
      LocalDateTime localDateTime2 = localDateTime1.withHour(4);
      
      //It's not changeable
      System.out.println(localDateTime);//2021-06-01T16:04:28.832504400
      System.out.println(localDateTime1);//2021-06-22T16:04:28.832504400
      System.out.println(localDateTime2);//2021-06-22T04:04:28.832504400
      
    8. plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours(): add days, weeks, months, years and hours to the current object

    9. Minusmonths() / minusweeks() / minusdays() / minusyears() / minuhours(): subtract months, weeks, days, years and hours from the current object

  3. instant class

    1. An instantaneous point on a timeline

    2. method:

      1. now(): a static method that returns the object of the Instant class of the default UTC Greenwich time zone

      2. Ofepochmili (long epoch milli): after the number of static methods, Instant returns the specified milliseconds based on the class object 1970-01-01 00:00:00

      3. At offset (zoneoffset offset): create an offset datetime in combination with an immediate offset

      4. Toepochmili(): returns the number of milliseconds from 1970-01-01 00:00:00 to the current time, which is the timestamp

        //instantiation 
        Instant instant = Instant.now();
        System.out.println(instant);//Greenwich mean time
        
        //Adjust offset
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);
        
        //Calculate the timestamp of instant
        long l = instant.toEpochMilli();
        System.out.println(l);
        
        //Find instant instance with timestamp
        Instant instant1 = Instant.ofEpochMilli(1622535397734L);
        System.out.println(instant1);
        
  4. java.time.format.DateTimeFormatter class

    1. This class provides three formatting methods

      1. Predefined standard formats

        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        
        //Format: date -- > string
        LocalDateTime localDateTime = LocalDateTime.now();
        String format = formatter.format(localDateTime);
        System.out.println(format);//2021-06-01T16:22:10.8436232
        
        //Parsing: String -- > date
        TemporalAccessor parse = formatter.parse("2021-06-01T16:22:10.8436232");
        System.out.println(parse);//{},ISO resolved to 2021-06-01T16:22:10.843623200
        
      2. Localization related formats

      3. ⭐ Custom format

        //format:
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format = timeFormatter.format(LocalDateTime.now());
        System.out.println(format);//2021-06-01 05:14:54
        
        //Resolution:
        TemporalAccessor parse = timeFormatter.parse("2021-06-01 05:14:54");
        System.out.println(parse);
        //{NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=54, HourOfAmPm=5, MinuteOfHour=14, MilliOfSecond=0},ISO resolved to 2021-06-01
        

8.4 Java comparator

In Java, the sorting of object arrays is often involved, so it involves the comparison between objects

  1. There are two ways to sort objects in Java:

    1. Natural sorting: Java Lang. comparable, once specified, once and for all
    2. Custom sorting: Java util. Comparator, a temporary given comparison rule
  2. Natural sorting: Java lang.Comparable

    1. For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo() method, and give a way to compare the sizes of two objects

      String[] arr = new String[]{"AA","BB","EE","DD"};
      Arrays.sort(arr);//From small to large
      System.out.println(Arrays.toString(arr));//[AA, BB, DD, EE]
      
    2. Rule to override compareTo() method:

      1. If the current object this is greater than the formal parameter object obj, a positive integer is returned
      2. If the current object this is less than the formal parameter object obj, a negative integer is returned
      3. Returns zero if the current object this is equal to the parameter object obj
    3. For custom classes, if sorting is required, you can let the custom class implement the Comparable interface and override the compareTo() method

      public class Goods implements Comparable{//⭐ Implementation interface
          private String name;
          private int price;
      
         	/*get,set,Constructor, toString*/
      
          //⭐ Indicates the sort method
          @Override
          public int compareTo(Object o) {
          if(o instanceof Goods){
              Goods goods = (Goods) o;
              if(this.price > goods.price){
                  return 1;
              }else if(this.price < goods.price){
                  return -1;
              }else {
                  //If the price is the same, compare the name and nest a compareTo()
                  //name is a String type, and has been rewritten
                  //Return - negative implementation from high to low
                  return -this.name.compareTo(goods.name);
              }
          }
          throw new RuntimeException("The data type passed in is inconsistent");
      }
      
      public class Test {
          public static void main(String[] args) throws ParseException {
              Goods[] goods = new Goods[4];
              goods[0]=new Goods("lenovo",34);
              goods[1]=new Goods("huawei",22);
              goods[2]=new Goods("xiaomi",3);
              goods[3]=new Goods("dell",56);
      
              Arrays.sort(goods);
              System.out.println(Arrays.toString(goods));
              //[Goods{name='xiaomi', price=3}, Goods{name='huawei', price=22}, Goods{name='lenovo', price=34}, Goods{name='dell', price=56}]
          }
      }
      
  3. Custom sorting: Java util. Comparator

    1. When the element type does not implement Java Lang. comparable interface, and it is not convenient to modify the code, or it implements Java The collation of the lang. comparable interface is not suitable for the current operation, so you can consider using the Comparator object to sort

    2. Rules for overriding compare(Object o1,Object o2) method:

      1. If the method returns a positive integer, o1 is greater than o2
      2. If 0 is returned, it indicates equality
      3. Returns a negative integer indicating that o1 is less than o2
    3. public class StringTest {
          public static void main(String[] args) throws ParseException {
              Goods[] goods = new Goods[4];
              goods[0]=new Goods("lenovo",34);
              goods[1]=new Goods("huawei",22);
              goods[2]=new Goods("xiaomi",3);
              goods[3]=new Goods("dell",56);
      				
              //⭐ When sorting, temporarily give a sorting method
              //The anonymous class implements the interface Comparator and overrides compare()
              Arrays.sort(goods, new Comparator<Goods>() {
                  @Override
                  public int compare(Goods o1, Goods o2) {
                      if(o1.getPrice() > o2.getPrice()){
                          return 1;
                      }if(o1.getPrice() < o2.getPrice()){
                          return -1;
                      }else{
                          return o1.getName().compareTo(o2.getName());
                      }
                  }
              });
              System.out.println(Arrays.toString(goods));
          }
      }
      

8.5 System class

  1. Represents the system. Many system level attributes and control methods are placed inside this class. This class is located in Java Lang package

  2. Because the constructor of this class is private, the object of this class cannot be created, that is, the class cannot be instantiated. Its internal member variables and member methods are static, so they can also be called conveniently

  3. Member variables: the System class contains three member variables: in, out and err, which represent standard input stream (keyboard input), standard output stream (display) and standard error output stream (display) respectively

  4. Member method:

    1. native long currentTimeMillis(): the function of this method is to return the current computer time. The expression format of time is the milliseconds difference between the current computer time and GMT time (Greenwich mean time) at 0:0:0:0 on January 1, 1970.

    2. void exit(int status): this method is used to exit the program. The value of status is 0 for normal exit, and non-zero for normal exit
      Abnormal exit. Using this method, the exit function of the program can be realized in the graphical interface programming.

    3. void gc(): this method is used to request the system for garbage collection. Whether the system recycles immediately depends on the implementation of the garbage collection algorithm in the system and the execution of the system

    4. String getProperty(String key): this method is used to obtain the value corresponding to the property named key in the system. The common attribute names and functions in the system are shown in the following table:

      String javaVersion = System.getProperty("java.version");
      System.out.println("java of version:" + javaVersion);
      String javaHome = System.getProperty("java.home");
      System.out.println("java of home:" + javaHome);
      String osName = System.getProperty("os.name");
      System.out.println("os of name:" + osName);
      String osVersion = System.getProperty("os.version");
      System.out.println("os of version:" + osVersion);
      String userName = System.getProperty("user.name");
      System.out.println("user of name:" + userName);
      String userHome = System.getProperty("user.home");
      System.out.println("user of home:" + userHome);
      String userDir = System.getProperty("user.dir");
      System.out.println("user of dir:" + userDir);
      

8.6 Math class

  1. java.lang.Math provides a series of static methods for scientific calculation. The parameter and return value types of the method are generally double

  2. abs absolute value
    acos,asin,atan,cos,sin,tan trigonometric function
    sqrt square root
    pow(double a,doble b) a of b pow 
    log Natural logarithm
    exp e Bottom index
    max(double a,double b)
    min(double a,double b)
    random() Return 0.0 To 1.0 Random number of
    long round(double a) double Type data a Convert to long Type (rounded)
    toDegrees(double angrad) Radian ->angle
    toRadians(double angdeg) Angle ->radian
    

8.2 BigInteger and BigDecimal

  1. BigInteger

    1. As the wrapper class of int, the Integer class can store the maximum Integer value of 2 31 − 1 2^{31}-1 231 − 1, the Long class is also limited, and the maximum is 2 63 − 1 2^{63}-1 263−1
    2. BigInteger can represent an immutable integer of any precision
    3. Constructor: BigInteger(String val): constructs BigInteger objects based on strings
  2. BigDecimal

    1. In business calculation, the digital accuracy is required to be relatively high, so Java is used math. BigDecimal class
    2. constructor
      1. public BigDecimal(double val)
      2. public BigDecimal(String val)
    3. common method
      1. public BigDecimal add(BigDecimal augend)
      2. public BigDecimal subtract(BigDecimal subtrahend)
      3. public BigDecimal multiply(BigDecimal multiplicand)
      4. public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
  3. Example:

    BigInteger bi = new BigInteger("12433241123");
    BigDecimal bd = new BigDecimal("12435.351");
    BigDecimal bd2 = new BigDecimal("11");
    //A large number
    System.out.println(bi);
    //bd divided by bd2, default
    System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
    //Divide bd by bd2 and keep 15 decimal places
    System.out.println(bd.divide(bd2, 15, BigDecimal.ROUND_HALF_UP))
    

Topics: JavaSE