1. Other APIs
1. System class
The methods and member variables in the system class are static and can be used directly without creating a System object.
1 /* 2 * Demonstrate the use of System 3 */ 4 public class SystemDemo { 5 public static void main(String[] args) { 6 7 /* 8 * Static member variables in the System class: the difference between out and err Both 9 * out and err can display the information that needs to be output on the console. 10 * But because the bottom layer of the JVM is two different implementation mechanisms for out and err 11 * When outputting, the display order of data cannot be determined 12 * 13 * Recommendation: Either all out or all err in development 14 */ 15 System.out.println("Hello"); 16 System.err.println("hello"); 17 //Force quit the JVM 18 System.exit(0); 19 //Get the current time of the system, and get the time difference between the current time and 1970-1-1 0:0:0 seconds 20 //The obtained is a millisecond value. 1 second = 1000 milliseconds 21 System.out.println(System.currentTimeMillis()); 22 } 23 }
Conclusion: You should consider using the System class whenever you want to obtain system-related information.
2. Math class
Math: It encapsulates methods related to mathematical operations.
The methods in the Math class are static and can be called directly by the class name.
1 /* 2 * Demonstration Math class 3 */ 4 public class MathDemo { 5 public static void main(String[] args) { 6 7 System.out.println(Math.E); 8 System.out.println(Math.PI); 9 10 //Return the smallest integer greater than the specified data 11 System.out.println(Math.ceil(4.56)); 12 //Return the largest integer less than the specified data 13 System.out.println(Math.floor(4.56)); 14 // round up 15 System.out.println(Math.round(4.56)); 16 //A random number between 0 and 1 17 System.out.println(Math.random()); 18 } 19 }
3. Random class
Random class It is a class specially responsible for generating random numbers.
1 /* 2 * Demonstration random number class 3 */ 4 public class RandomDemo { 5 public static void main(String[] args) { 6 7 // Create the object that generates the random number 8 Random r = new Random(); 9 10 System.out.println(r.nextFloat()); 11 System.out.println(r.nextDouble()); 12 System.out.println(r.nextInt()); 13 System.out.println(r.nextBoolean()); 14 System.out.println(r.nextLong()); 15 System.out.println(r.nextInt(100)); 16 17 for( int i = 0 ; i < 6 ; i++){ 18 System.out.println(r.nextInt(6) + 1); 19 } 20 } 21 }
4. Date class
a. Date类
There are time and date data in life, and there are corresponding classes in Java to describe these data.
The class Date represents a specific instant, accurate to the millisecond.
Before JDK 1.1, the class Date had two other functions. It allows interpretation of dates as year, month, day, hour, minute and second values. It also allows formatting and parsing of date strings. However, the API for these functions is not easy to internationalize. Starting from JDK 1.1, the Calendar class should be used to convert between date and time fields, and the DateFormat class should be used to format and parse date strings. The corresponding method in Date is obsolete.
The Date class is an object that represents time and date data, but the methods in this class are not conducive to the time display and other operations performed by programmers in other countries. Most of the methods are outdated and replaced by the Calendar and DateFormat classes.
1 /* 2 * Demo Date class 3 * Constructor: 4 * Date() 5 * Constructor of empty parameters in the Date class: its purpose is just to encapsulate the current time into a Date object 6 * Date(long date) 7 * The integer constructor that receives the long type in the Date class, its purpose is to encapsulate a specified millisecond value into a Date object 8 * Ordinary method: 9 * getTime() Get the millisecond value corresponding to the current time represented by the Date object 10 * setTime(long time) Modify the millisecond value corresponding to the current Date object to the specified millisecond value 11 * 12 * In the Date class, you need to master: 13 * Conversion between Date object and millisecond value. 14 * The role of the Date object to turn the millisecond value is to calculate the time difference between 2 times 15 * The calculated time difference is a millisecond value, which needs to be manually converted into a specific number of days, or months, or years, etc. 16 * 17 */ 18 public class DateDemo { 19 public static void main(String[] args) { 20 21 //Create a Date object using the constructor with empty parameters in the Date class 22 Date date = new Date(); 23 Date date2 = new Date(999900001231L); 24 //date.setTime(1230L); 25 //print 26 System.out.println(date); 27 System.out.println(date2); 28 } 29 }
b. Date time formatting class
b.1 Introduction to the DataFormat class
DateFormat is an abstract class for subclasses of date/time formatting that formats and parses dates or times in a language-independent manner. Date/time formatting subclasses (like SimpleDateFormat) allow formatting (aka date- > text), parsing (text-> date), and normalization. Represents a date as a Date object, or as the number of milliseconds since January 1, 1970 00:00:00 GMT (Greenwich Mean Time).
DateFormat provides many class methods to get default date/time Formatters based on default or given locale and various formatting styles. Formatting styles include FULL, LONG, MEDIUM, and SHORT. More details and examples of using these styles are provided in the method descriptions.
DateFormat class: It can complete the conversion between Date objects and strings. However, because this class is an abstract class, it cannot directly create objects, and this class has only four conversion methods between dates and strings, which cannot meet the format the user wants:
1 /* 2 * Simple demo DateFormat class 3 */ 4 public class DataFormatDemo { 5 public static void main(String[] args) { 6 7 //Get the DateFormat object 8 DateFormat format = DateFormat.getInstance(); 9 10 // Convert the date object to a string 11 Date d = new Date(); 12 String s = format.format(d); 13 System.out.println(s); 14 15 } 16 }
b.2 SimpleDateFormat class introduction
SimpleDateFormat: It has the same function as DateFormat. Both complete the conversion between Date objects and strings.
SimpleDateFormat is a subclass of DateFormat, and when creating a SimpleDateFormat object, how to complete the conversion format writing between date and string is specified by the developer.
How to specify the converted format when creating a SimpleDateFormat object:
Create a SimpleDateFormat object specifying the format:
Years of use yyyy
Month MM
dd
HH
min mm
seconds ss
The separator in the middle is specified by the programmer himself.
Parse the date: Convert the date data in the form of a string to the parse method in the SimpleDateFormat class used by the Date object
Format the date: Convert the Date object to date data in the form of a string, using the format method in the SimpleDateFormat class
1 /* 2 * Demo SimpleDateFormat class 3 */ 4 public class SimpleDataFormatDemo { 5 public static void main(String[] args) throws ParseException { 6 method3(); 7 } 8 /* 9 * The time data in the form of two strings as follows, calculate their time difference 10 * "2016-01-02 10:27:14" 11 * "2019-11/22 10:27:14" 12 * Calculate how many days are between them? 13 */ 14 public static void method3() throws ParseException { 15 16 String s = "2016-01-02 10:27:14"; 17 String s2 = "2016-01/03 10:27:14"; 18 19 //Need to define 2 different formatter objects 20 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 21 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM/dd HH:mm:ss"); 22 23 //parse 24 Date d = sdf.parse(s); 25 Date d2 = sdf2.parse(s2); 26 27 //Need to get the millisecond value corresponding to different Date objects 28 long t = d.getTime(); 29 long t2 = d2.getTime(); 30 31 //Calculate the time difference 32 long day = Math.abs((t - t2) / 1000 / 60 / 60 / 24); 33 System.out.println(day); 34 } 35 //Convert string data into Date object 36 public static void method2() throws ParseException { 37 38 String s = "2016-01-02 10:27:14"; 39 40 //Create a formatter object 41 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 42 43 // Convert the string to a Date object 44 Date d = sdf.parse(s); 45 46 System.out.println(d); 47 } 48 //Convert date object to string data 49 public static void method() { 50 // Create the formatter object 51 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); 52 53 // Convert date object to string 54 Date d = new Date(); 55 String s = sdf.format(d); 56 System.out.println(s); 57 } 58 }
3. Calendar
Calender class: It is the calendar class. In fact, this class is equivalent to a container. This container holds all information related to the current time.
For example: today is the day of the year, today is the day of the week, today is the week of the month, today is the month, day, hours, minutes, seconds and other information are stored in this container.
The English data corresponding to the calendar year, month, day, hour, minute, second, 12 months, and week are all encapsulated into static member variables.
The Calender class is an abstract class, which provides the static getInstance method to obtain the Calender object ().
1 // Simple demo Calendar 2 public static void method() { 3 4 //Get the Calendar object 5 Calendar c = Calendar.getInstance(); 6 7 System.out.println(c); 8 9 System.out.println(c.get( Calendar.YEAR )); 10 /* 11 * Months in computers are zero-based. 12 * 0 means January 13 * 1 means February 14*11 means December 15 * 12 means January of the next year 16 */ 17 System.out.println(c.get( Calendar.MONTH )); 18 System.out.println(c.get( Calendar.DAY_OF_MONTH )); 19 20 } 21 22 23 /* 24 * How many days are there in February in any year? 25 * Since the time data is continuous, we can set the current time as 26 * On March 1 of the current year, and then let the number of days -1, the current time will automatically become the last day of February. 27 * We only need to get the number of days in the current month, that is how many days there are in February 28 */ 29 public static void method2() { 30 31 //Get the Calendar object 32 Calendar c = Calendar.getInstance(); 33 34 // Set the current time to March 1st 35 for (int year = 1000; year < 2555; year++) { 36 c.set(year, 2, 1); 37 // let the number of days -1 38 c.add(Calendar.DAY_OF_MONTH, -1); 39 // Get the number of days in the currently processed month 40 System.out.println(year + "year in February" + c.get(Calendar.DAY_OF_MONTH) + "day"); 41 } 42 }
2. Features of JDK5
1. Static import
1 /* 2 * static import demo 3 * If you need to use static members in some classes in the program, you can, at the beginning of the program, 4 * First import these static members into the program 5 * Then you can use static members directly in the program without specifying the class name 6 */ 7 import static java.lang.Math.PI; 8 import static java.lang.System.out; 9 10 public class StaticImportDemo { 11 public static void main(String[] args) { 12 out.println(PI); 13 } 14 }
2. Variable parameters
1 /* 2 * Demonstration variable parameters 3 */ 4 public class ParameterArgumentsDemo { 5 public static void main(String[] args) { 6 7 int sum = getSum(1, 2, 4); 8 System.out.println(sum); 9 /* 10 * If you need to manipulate multiple data of the same type, pass these data to a method 11 * Before JDK5: you can store this data into an array first, then pass the array to the method 12 * 13 * After JDK5, you can use variable parameter technology to receive an indeterminate number of data 14 * 15 */ 16 int[] arr = {11,22,33,44,55,66,77,88}; 17 18 int sum2 = getSum(12,33,44,55 ); 19 System.out.println(sum2); 20 } 21 22 /* 23 * Demonstrate how to define variable parameters 24 * Variable parameters: 25 * 1. After the data it actually receives, it is still kept in the array, and the method still needs to be operated through the array. 26 * 2. If the method has other parameters besides variable parameters, the variable parameters must be written at the end of the entire method parameter list. 27 */ 28 public static int getSum(int x , int ... arr ) { 29 30 int sum = 0; 31 for (int i = 0; i < arr.length; i++) { 32 sum += arr[i]; 33 } 34 return sum; 35 } 36 /* Calculate the sum value in the passed array 37 public static int getSum(int[] arr) { 38 39 int sum = 0; 40 for (int i = 0; i < arr.length; i++) { 41 sum += arr[i]; 42 } 43 return sum; 44 } 45 */ 46 // Requirements: define a function to calculate the sum of 2 numbers 47 public static int getSum(int i, int j , int k) { 48 return i + j + k; 49 } 50 51 // Requirements: define a function to calculate the sum of 2 numbers 52 public static int getSum(int i, int j) { 53 return i + j; 54 } 55 }
3.foreach loop
1 /* 2* In JDK5 there is a technique that can simplify the for loop: 3* foreach technique: advanced for loop 4 * The writing format of the ordinary for loop: 5 * for( expression1 ; expression2 ; expression3 ){ 6 * loop body 7 * } 8 * foreach writing format: 9 * for(element type variable name in array space: array name){ 10 * loop body 11 * } 12 * When using foreach to traverse the array, the data stored in the defined variable name is the element taken from the array 13 * Disadvantages: foreach can only traverse, and cannot perform other operations on the values in the array space 14 */ 15 public class ForEachDemo { 16 public static void main(String[] args) { 17 18 int[] arr = {11,22,33,44,55,66}; 19 20 //Use a normal for loop to traverse 21 for(int i = 0 ; i < arr.length ; i ++){ 22 System.out.print(arr[i] + " "); 23 } 24 System.out.println("\n==================="); 25 //Use foreach to traverse the array 26 for( int x : arr ){ 27 System.out.print(x + " "); 28 } 29 } 30 }