# 1, Digital class

## 1.1 super large floating point

```BigDecimal b1 = new BigDecimal("123456789.987654321"); // Declare a BigDecimal object
BigDecimal b2 = new BigDecimal("987654321.123456789"); // Declare a BigDecimal object
System.out.println("b1: " + b1 +  ", b2:" + b2);
System.out.println("Subtraction operation:" + b2.subtract(b1)); // Subtraction operation
System.out.println("Multiply operation:" + b2.multiply(b1)); // Multiplication operation
//You need to specify the number of bits to prevent infinite loops, or to include them in try catch
System.out.println("Division operation:" + b2.divide(b1,10,BigDecimal.ROUND_HALF_UP)); // The division operation package leaves ten decimal places for rounding

System.out.println("Maximum number:" + b2.max(b1)); // Find the maximum number
System.out.println("Minimum:" + b2.min(b1)); // Find the minimum number

int flag = b1.compareTo(b2);
if (flag == -1)
System.out.println("Comparison operation: b1<b2");
else if (flag == 0)
System.out.println("Comparison operation: b1==b2");
else
System.out.println("Comparison operation: b1>b2");

System.out.println("===================");

//Try to use string assignment
System.out.println(new BigDecimal("2.3"));```

## 1.2 super large integers

```BigInteger b1 = new BigInteger("123456789"); // Declare BigInteger object
BigInteger b2 = new BigInteger("987654321"); // Declare BigInteger object
System.out.println("b1: " + b1 +  ", b2:" + b2);
System.out.println("Subtraction operation:" + b2.subtract(b1)); // Subtraction operation
System.out.println("Multiply operation:" + b2.multiply(b1)); // Multiplication operation
System.out.println("Division operation:" + b2.divide(b1)); // Division Operation
System.out.println("Maximum number:" + b2.max(b1)); // Find the maximum number
System.out.println("Minimum:" + b2.min(b1)); // Find the minimum number
BigInteger result[] = b2.divideAndRemainder(b1); // Division operation of finding remainder
System.out.println("Business is:" + result[0] + "；The remainder is:" + result[1]);
System.out.println("The equivalence is:" + b1.equals(b2));
int flag = b1.compareTo(b2);
if (flag == -1)
System.out.println("Comparison operation: b1<b2");
else if (flag == 0)
System.out.println("Comparison operation: b1==b2");
else
System.out.println("Comparison operation: b1>b2");```

## 1.3 random number:

```import java.util.Random;

public class RandomTest {

public static void main(String[] args)
{
//In the first method, Random numbers in the range of int are generated by Random class
Random rd = new Random();
System.out.println(rd.nextInt());
System.out.println(rd.nextInt(100)); //Random number from 0 to 100
System.out.println(rd.nextLong());
System.out.println(rd.nextDouble());	//Returns a direct number from 0.0 to 1.0
System.out.println("=========================");

//Second, generate a random number in a range, such as a random number between 0 and 10
//Math.random[0,1)
System.out.println(Math.round(Math.random()*10));
System.out.println("=========================");

//New method of JDK 8
rd.ints();  //Returns data in an infinite range of int types
int[] arr = rd.ints(10).toArray();  //Number of generated 10 int range classes.
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("=========================");

arr = rd.ints(5, 10, 100).toArray();//Limit range 10-100
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

System.out.println("=========================");

arr = rd.ints(10).limit(5).toArray();//Indicates to generate 10 qualified return 5
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}

}
```

## 1.4 format output

```public class MathTest {

public static void main(String[] args) {

System.out.println(Math.abs(-5));    //absolute value
System.out.println(Math.max(-5,-8)); //Maximum value
System.out.println(Math.pow(-5,2));  //Exponentiation
System.out.println(Math.round(3.5)); //Rounding
System.out.println(Math.ceil(3.5));  //Rounding up
System.out.println(Math.floor(3.5)); //Rounding down
}

}

//Output:
5
-5
25.0
4
4.0
3.0
```

## 1.5 floating point and double precision

```float f1 = 1.23f;
// Float F2 = 1.23; error, float assignment must have f
double d1 = 4.56d;
double d2 = 4.56;  //double can omit the end d```

# 2, String

## 2.1String

```public class StringTest {

public static void main(String[] args) {
String a = "123;456;789;123 ";
System.out.println(a.charAt(0)); // Return element 0
System.out.println(a.concat(";000")); // Connect a new string and return, a unchanged
System.out.println(a.contains("000")); // Judge whether a includes 000
System.out.println(a.endsWith("000")); // Judge whether a ends in 000
System.out.println(a.equals("000")); // Judge whether it is equal to 000
System.out.println(a.equalsIgnoreCase("000"));// Determine whether it is equal to 000 if case is ignored
System.out.println(a.length()); // Return a length
System.out.println(a.trim()); // Returns a string after removing the space before and after a, a does not change
String[] b = a.split(";"); // Divide a string into arrays according to
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}

System.out.println("===================");

System.out.println(a.substring(2, 5)); // The subscript of intercept a is 2 (the third) to 5 (the sixth) character a is unchanged
System.out.println(a.replace("1", "a"));
System.out.println(a.replaceAll("1", "a")); // The first parameter of replaceAll is a regular expression

System.out.println("===================");

String s1 = "12345?6789";
String s2 = s1.replace("?", "a");
String s3 = s1.replaceAll("[?,8]", "a");
// The [?] here indicates the character question mark, so that it can be replaced normally. Otherwise, there will be a special meaning in the regular and an exception will be reported
System.out.println(s2);
System.out.println(s3);
System.out.println(s1.replaceAll("[\\d]", "a")); //All the numbers in s1 are replaced with a and output, and the value of s1 is unchanged.

}
}

//Output:
1
3
123;456;789;123 ;000
false
false
false
false
16
123;456;789;123
123
456
789
123
===================
3;4
a23;456;789;a23
a23;456;789;a23
===================
12345a6789
12345a67a9
aaaaa?aaaa

```

## 2.2 simple description of regular expression:

?, *, +, \ D \ W are equivalent characters
? equivalent to matching length {0,1}
* equivalent to matching length {0,}
+ is equivalent to matching length {1,}
\ d is equivalent to [0-9]

\D is equivalent to [^ 0-9]
\w is equivalent to [a-za-z_-9]

\W is equivalent to [^ a-za-z_-9].

Example 1:

System.out.println("15088688388".replaceAll("(\\d{3})(\\d{4})","\$1****"));

\\d{3} For 150,\\d{4 } 8868.\$1 For the first group, it's\\d{3} . So output 150 * * 8388

System.out.println("15088688388".replaceAll("(\\d{3})(\\d{4})","\$1 222 "); output 1502228388

Example 2:

System.out.println("15088688388".replaceAll("\d","b")); output bbbbbbbbbbb

\d is a number, but because including itself is preceded by \ so we need another\

System.out.println("15088688388".replaceAll("\d+","b")); output b,

+The sign indicates one or more times, so the whole is replaced.

## 2.3 variable string StringBuffer/StringBuilder

The last blog provided an example to verify the performance of both.

Capacity > = length space size.

For example, the StringBuffer string can be changed.

```public class StringBufferReferenceTest {

public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("123");
StringBuffer sb2 = sb1;

sb1.append("2222");
System.out.println(sb1);
System.out.println(sb2);  //sb1 and sb2 still point to the same memory

}

}
//Output:
1232222
1232222
```

Examples of common functions

```public class StringBuffertest {

public static void main(String[] args) {
// Method stubs generated automatically by TODO
StringBuffer sb1 = new StringBuffer("123");
sb1.append("12");//12312
System.out.println(sb1);
sb1.insert(2,"haha");//Insert 12haha12 after the second character
System.out.println(sb1);
sb1.delete(2,3);//Delete the second to third characters, including the tail but not the head
System.out.println(sb1);
sb1.replace(2,5,"222");//Replace the 2nd to 5th characters (3rd, 4th, 5th), including the tail but not the head
System.out.println(sb1);
String s1=sb1.substring(3,6);//Intercept 3-6 characters (4th, 5th, 6th), the original string remains unchanged
System.out.println(s1);
System.out.println(sb1);

}

}
//Output:
12312
12haha312
12aha312
12222312
223
12222312

```

## 3.1Calendar

Give an example:

Obtain the time, time, minute and second of the day, calculate the last day of each month, set the day, and modify the day, month and year

```import java.util.Calendar;

public class CalendarTest {

Calendar calendar = Calendar.getInstance();

public void test1() {
// Year of acquisition
int year = calendar.get(Calendar.YEAR);
// To get the month, you need the range of months to be 0-11, so you need + 1 to get the current month value
int month = calendar.get(Calendar.MONTH) + 1;
// Acquisition date
int day = calendar.get(Calendar.DAY_OF_MONTH);

// Acquisition time
int hour = calendar.get(Calendar.HOUR);
// Int hour = calendar. Get (calendar. Hour of day); / / 24 hours means
// Acquisition score
int minute = calendar.get(Calendar.MINUTE);
// Get seconds
int second = calendar.get(Calendar.SECOND);

// Weekdays in English speaking countries begin on Sunday
int weekday = calendar.get(Calendar.DAY_OF_WEEK);

System.out.println("Now is" + year + "year" + month + "month" + day + "day" + hour
+ "Time" + minute + "branch" + second + "second" + "week" + weekday);
}

// Today, a year later
public void test2() {
// Similarly, the next month's today's calendar.add(Calendar.MONTH, 1);

// Year of acquisition
int year = calendar.get(Calendar.YEAR);
// Acquisition month
int month = calendar.get(Calendar.MONTH) + 1;
// Acquisition date
int day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println("Today, a year later:" + year + "year" + month + "month" + day + "day");
}

// Get the last day of any month
public void test3() {
// Suppose the last day of June
int currentMonth = 6;
// First, find out the first day of July. In fact, here 6 is the currentMonth variable passed in from outside
// 1
calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);

// Acquisition date
int day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println("6 The last day of the month is" + day + "Number");
}

// Setting date
public void test4() {
calendar.set(Calendar.YEAR, 2000);
System.out.println("Now is" + calendar.get(Calendar.YEAR) + "year");

calendar.set(2018, 7, 8);
// Year of acquisition
int year = calendar.get(Calendar.YEAR);
// Acquisition month
int month = calendar.get(Calendar.MONTH)+1;
// Acquisition date
int day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println("Now is" + year + "year" + month + "month" + day + "day");
}

//The difference between add and roll. If a roll changes its number, it will not change the month (it will not change the previous level).
public void test5() {

calendar.set(2018, 7, 8);

// Year of acquisition
int year = calendar.get(Calendar.YEAR);
// Acquisition month
int month = calendar.get(Calendar.MONTH)+1;
// Acquisition date
int day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println("2018.8.8, use add Eight days less, now" + year + "." + month + "." + day);

calendar.set(2018, 7, 8);
calendar.roll(Calendar.DAY_OF_MONTH, -8);

// Year of acquisition
year = calendar.get(Calendar.YEAR);
// Acquisition month
month = calendar.get(Calendar.MONTH)+1;
// Acquisition date
day = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println("2018.8.8, use roll Eight days less, now" + year + "." + month + "." + day);
}

public static void main(String[] args) {
CalendarTest c = new CalendarTest();
c.test1();
System.out.println("============");
c.test2();
System.out.println("============");
c.test3();
System.out.println("============");
c.test4();
System.out.println("============");
c.test5();

}

}
//Output:
//It's 8:13:51 Monday, January 12, 2020
============
//Today, a year later: January 12, 2021
============
6 The last day of the month is the 30th
============
//It's 2000
//It's August 8, 2018
============
2018.8.8, use add Eight days less, now 2018.7.31
2018.8.8, use roll Eight days less, now 2018.8.31

```

## 4.1 digital formatdecimalformat

#Represents: at most; 0 represents: only

If the integer part is 0, it is unnecessary to write if it is assumed that the integer does not exist; if it is assumed that 0, it is assumed that it does not exist, but at least one bit is written, and 0 is written

When the integer part is not 0, 0 and ා, the processing is the same when the integer part is many bits, that is, how many bits are written

Decimal part represents the maximum number of digits, and 0 represents the number of digits

Give an example:

Scientific counting, control integers, decimal places, percentage representation

```import java.text.DecimalFormat;

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

DecimalFormat df1,df2;

System.out.println("When the integer part is 0, 0/#The difference between them.
// If the integer part is 0, it is unnecessary to write if it is assumed that the integer does not exist; if it is assumed that 0, it is assumed that it does not exist, but at least one bit is written, and 0 is written
df1 = new DecimalFormat("#.00");
df2 = new DecimalFormat("0.00");

System.out.println(df1.format(0.1)); // .10
System.out.println(df2.format(0.1)); // 0.10

System.out.println("Decimal part 0/#The difference between them.
//#There must be at most several delegates, and only a few delegates can be represented by 0
df1 = new DecimalFormat("0.00");
df2 = new DecimalFormat("0.##");

System.out.println(df1.format(0.1)); // 0.10
System.out.println(df2.format(0.1)); // 0.1

System.out.println(df1.format(0.006)); // 0.01
System.out.println(df2.format(0.006)); // 0.01

System.out.println("Integer part has more than one bit");
//The processing of 0 and ා is the same when the integer part is many bits, that is, how many bits are written
df1 = new DecimalFormat("0.00");
df2 = new DecimalFormat("#.00");

System.out.println(df1.format(2)); // 2.00
System.out.println(df2.format(2)); // 2.00

System.out.println(df1.format(20)); // 20.00
System.out.println(df2.format(20)); // 20.00

System.out.println(df1.format(200)); // 200.00
System.out.println(df2.format(200)); // 200.00
double pi=3.1415927;//PI
//Take an integer
System.out.println(new DecimalFormat("0").format(pi));//3
//Take one integer and two decimals
System.out.println(new DecimalFormat("0.00").format(pi));//3.14
//Take two integers and three decimal places, and fill in the insufficient part with 0.
System.out.println(new DecimalFormat("00.000").format(pi));//03.142
//Take all integer parts
System.out.println(new DecimalFormat("#").format(pi));//3
//Count by percentage and take two decimal places
System.out.println(new DecimalFormat("#.##%").format(pi));//314.16%

long c=299792458;//Light speed
//Display as scientific counting method and take five decimal places
System.out.println(new DecimalFormat("#.#####E0").format(c));//2.99792E8
//Scientific method of counting displayed as two digit integers with four decimal places
System.out.println(new DecimalFormat("00.####E0").format(c));//29.9792E7
//Each three digits are separated by commas.
System.out.println(new DecimalFormat(",###").format(c));//299,792,458
//Embed formatting in text
System.out.println(new DecimalFormat("The speed of light is per second,###Meters "). format(c)); / / the speed of light is 299792458 meters per second

}
}
//Output:
//When the integer part is 0, the difference between 0 / #
.10
0.10
//Difference of decimal part 0 / ා
0.10
0.1
0.01
0.01
//Integer part has more than one bit
2.00
2.00
20.00
20.00
200.00
200.00
3
3.14
03.142
3
314.16%
2.99792E8
29.9792E7
299,792,458
//The speed of light is 299792458 meters per second
```

rounding. Please refer to the previous text 1 and figure class for the value up and down

```
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class TwoDigitsTest {

public static void main(String[] args) {
double   f   =   111231.5585;
BigDecimal   b   =   new   BigDecimal(f);
double   f1   =   b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(f1); //111231.56

DecimalFormat   df   =new DecimalFormat("#.00");
String f2 = df.format(f);
System.out.println(f2); //111231.56

String f3 = String.format("%.2f",f);
System.out.println(f3); //111231.56

NumberFormat ddf1=NumberFormat.getInstance() ;
System.out.println(ddf1.getClass().getName());
ddf1.setMaximumFractionDigits(2);
String f4= ddf1.format(f) ;
System.out.println(f4);  //111,231.56
}
}
//Output:
111231.56
111231.56
111231.56
java.text.DecimalFormat
111,231.56

```

## 4.2 string format

MessageFormat: string format, formatted with parameters and arrays

```import java.text.MessageFormat;

public class MessageFormatTest {

public static void main(String[] args) {
String message = "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}";

Object[] array = new Object[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q"};

String value = MessageFormat.format(message, array);

System.out.println(value);

message = "oh, {0,number,#.##} is a good number";

array = new Object[]{new Double(3.1415)};

value = MessageFormat.format(message, array);

System.out.println(value);
}
}
//Output:
ABCDEFGHIJKLMNOPQ
oh, 3.14 is a good number```

## 4.3 time format

### 4.3.1DateFormat

```import java.text.DateFormat;
import java.util.Locale;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateTest {

public static void main(String[] args) {

String strDate = "2008-10-19 10:11:30.345" ;
// Prepare the first template to extract the date number from the string
String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;
// Prepare the second template to change the extracted date number to the specified format
String pat2 = "yyyy year MM month dd day HH Time mm branch ss second SSS Millisecond" ;
SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;        // Instantiate template object
SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;        // Instantiate template object
Date d = null ;
try{
d = sdf1.parse(strDate) ;   // Extract the date from the given string
}catch(Exception e){            // If the provided string format is wrong, exception handling is performed
e.printStackTrace() ;       // Print exception information
}
System.out.println(sdf2.format(d)) ;    // Change date to new format

Date date = new Date();
DateFormat df1 = DateFormat.getInstance();
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EE");
DateFormat df3 = new SimpleDateFormat("yyyy year MM month dd day hh Time mm branch ss second  EE",Locale.CHINA);
DateFormat df4 = new SimpleDateFormat("dd-MMMM-yyyy hh:mm:ss EE",Locale.US);
DateFormat df5 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df6 = new SimpleDateFormat("yyyy year MM month dd day");

System.out.println("-------Output dates in different formats-------");
System.out.println("according to java Default date format:"+df1.format(date));
System.out.println("In the specified format yyyy-MM-dd hh:mm:ss EE,System default area:"+df2.format(date));
System.out.println("In the specified format yyyy year MM month dd day  hh Time mm branch ss second  EE,The region is China:"+df3.format(date));
System.out.println("In the specified format dd-MMMM-yyyy hh:mm:ss EE,The region is the United States:"+df4.format(date));
System.out.println("In the specified format yyyy-MM-dd :"+df5.format(date));
System.out.println("In the specified format yyyy year MM month dd day :"+df6.format(date));
}

}
//Output:
2008 10:11:30, October 19, 2015 345 MS
-------Output dates in different formats-------
//According to the java default date format: 20-1-12 8:55 PM
//According to the specified format yyyy MM DD HH: mm: SS EE, the system default area: 2020-01-12 08:55:22 Sunday
//According to the specified format, yyyy, mm, dd, HHH, mm, mm, ss, EE, China: January 12, 2020, 08:55, 22, Sunday
//According to the specified format dd-mm mm-yyyy HH: mm: SS EE, the region is the United States: 12-January-2020 08:55:22 Sun
//According to the specified format yyyy MM DD: 2020-01-12
//In the specified format MM / dd / yyyy: January 12, 2020
```

### 4.3.2LocalDate

```import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormatterTest {

public static void main(String[] args) {
//Convert string to time
String dateStr= "2016 October 25, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy year MM month dd day");
LocalDate date= LocalDate.parse(dateStr, formatter);
System.out.println(date.getYear() + "-" + date.getMonthValue() + "-" + date.getDayOfMonth());

System.out.println("==========================");

//Convert date to string output
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy year MM month dd day hh:mm:ss");
String nowStr = now.format(format);
System.out.println(nowStr);

}

}
//Output:
2016-10-25
==========================
2020 January 12, 2008:45:27

```

Reference: Chen Liangyu, core technology of mooc java, University of China

Published 18 original articles, won praise 8, visited 2047

Tags: Java less JDK

Posted on Sun, 12 Jan 2020 08:51:08 -0500 by Norsk.Firefox