Common classes required in Java (very practical), java is very practical

Source: Internet
Author: User

Common classes required in Java (very practical), java is very practical
Common classes that must be understood in Java I. Packaging classes

I believe that you are familiar with basic data types, such as int, float, double, boolean, and char. Basic data types do not have the characteristics of objects. For example, basic data types cannot call methods and have simple functions ..., java provides a packaging class for each basic data type so that we can operate on the basic data type just like an object.

Mappings between basic types and packaging classes:

Note: There are two packaging classes with special names: Integer, Character, and uppercase letters of the basic data class.

Packaging provides two main methods:

1. Method for converting this type and other basic types

2. Convert the string and the current type and the packaging class to each other.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Conversion between primitive types and packaging classes in Java

The conversion between the basic type and the packaging class is often required. Take Integer as an example (the operations of other packaging classes are the same ):

1 Integer a = new Integer (3); // defines an Integer packaging class object with a value of 32 int B = a + 5; // calculates the object and basic type.

After the automatic packing and unpacking mechanism is introduced in JDK1.5, the conversion between the packaging class and the basic type is easier and more convenient.

So what is packing and unpacking? Let's take a look at the following:

Packing:Converts a basic type to a packaging class so that it has the object nature. It can also be divided into manual packing and automatic packing.

1 int I = 10; // specify an int Basic Data Type 2 Integer x = new Integer (I); // manually boxed 3 Integer y = I; // automatically boxed
1 Double n = I; // different types cannot be automatically packed; 2 Double m = new Double (I); // You can manually pack different types

Unpack:In contrast to packing, you can convert a packaging object to a value of the basic type, which can be divided into manual unpacking and automatic unpacking.

1 Integer j = new Integer (8); // defines the Integer packaging class object. The value is 82 int n = j. intValue (); // manually unpack 3 int m = j; // automatically unpack
1 double x = j. doubleValue (); // Manual unpacking for different types; 2 double y = j; // automatic unpacking for Different Types

Note::Different types cannot be automatically packed,Different types can be automatically split.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Conversion between basic types and strings in Java

In program development, we often need to convert between the basic data type and string.

Where,Convert basic type to stringThere are three methods:

1. Use the toString () method of the packaging class

2. Use the valueOf () method of the String class

3. Add the basic type with an empty string to obtain the string corresponding to the basic data type.

The Code is as follows:

1 // convert the basic type to String 2 int x = 10; 3 String str1 = Integer. toString (x); // Method 4 String str2 = String. valueOf (x); // method 2 5 String str3 = x + ""; // method 3, essentially using the system's automatic conversion type

Let's take a look.String Conversion to basic typeThere are two methods:

1. Call the parseXxx static method of the packaging class

2. Call the valueOf () method of the packaging class to convert it to the basic type of the packaging class, and the package will be automatically split.

The Code is as follows:

1 // convert String to basic type 2 String str = "8"; 3 int n = Integer. parseInt (str); // Method 4 int y = Integer. valueOf (str); // method 2

Note: If the string contains other characters in the basic type, an exception is thrown during the program running. Therefore, it is best to use the try-catch statement to capture and process this method.

PS: Conversion of other basic types and strings is not listed here. The methods are similar.

Ii. Date and SimpleDateFormat classes

In program development, we often need to process Date and time-related data. In this case, we can use the Date class in the java. util package. The main role of this class isGet current timeLet's take a look at the use of the Date class:

1 Date d = new Date (); // use the default constructor to create the Date object 2 System. out. println (d );

Use the Date classDefault Construction Method without ParametersThe created object representsCurrent TimeYou can directly output the Date object to display the current time. The result is as follows:

Among them, Thu represents Thursday, Jul represents July, 06 represents 06, and CST represents China Standard Time (China Standard Time, that is, Beijing Time, UTC + 8 ).

From the above output results, we found that the default time format is not very friendly and is not the same as the date format we see on a daily basis. If you want to display it in the specified format, such as 13:31:28, what should we do?

In the java. text packageSimpleDateFormat classIt's time to show off !! You can use SimpleDateFormat to performFormatFor example, you can convert a date to a text in the specified format or a text to a date.

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

1. Use the format () method to convert a date to a text in the specified format

1 // use the format () method to convert a Date to text in the specified format 2 Date d = new Date (); // use the default constructor to create the Date object 3 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "); // specify the date format 4 String today = sdf. format (d); 5 System. out. println (today );

Running result:

Result Analysis:

In the Code, "yyyy-MM-dd HH: mm: ss" is a predefined string. yyyy indicates four-digit year, MM indicates two months, and dd indicates two dates, HH indicates the hour (in the 24-hour format), mm indicates the minute, and ss indicates the second. In this way, the target format of the conversion is specified.Format ()Method to convert the time to a string in the specified format.

2. convert text to date using the parse () method

1 // create Date Format String 2 String day = "July 06, 2017 13:42:10"; 3 // create SimpleDateFormat object, specify the date format of the string 4 SimpleDateFormat sd = new SimpleDateFormat ("yyyy MM dd HH: mm: ss"); 5 // call the parse method, convert the string to Date 6 date; 7 try {8 Date = sd. parse (day); 9 System. out. println (date); 10} catch (ParseException e) {11 // TODO Auto-generated catch block12 e. printStackTrace (); 13}

Running result:

Result Analysis:

In the Code, "yyyy MM dd HH: mm: ss" specifies the date format of the string.Parse ()Method to convert text to date. If you convert a string to the Date type, an exception may be thrown. You must use the try-catch statement to capture the exception.

Be sure to note:

1. When you call the parse () method of the SimpleDateFormat object, a conversion exception may occur, that is, ParseException. ThereforeException Handling is required.

2. When using the Date class, you must import the java. util package. When using SimpleDateFormat, you must import the java. text package.

Iii. Applications of the Calendar class

The main role of the Date class is to obtain the current time. At the same time, this class also has time setting and some other functions. However, due to design problems, these methods have been criticized, not recommended.We recommend that you use the Calendar class to process the time and date.

The java. util. Calendar class isAbstract classYou can call the getInstance () static method to obtain a Calendar Object, which has been initialized by the current date and time, that isThe default value is the current time., Such as Calendar c = Calendar. getInstance ();

So how can I use Calendar to obtain information such as year, month, day, and time? Let's look at the following code:

1 public static void main (String [] args) {2 // TODO Auto-generated method stub 3 Calendar c = Calendar. getInstance (); // create a Calendar Object 4 int year = c. get (Calendar. YEAR); // obtain the YEAR 5 int month = c. get (Calendar. MONTH) + 1; // obtain the MONTH. 0 indicates that the MONTH of February 6 int day = c. get (Calendar. DAY_OF_MONTH); // obtain the date 7 int hour = c. get (Calendar. HOUR_OF_DAY); // get the hour 8 int minute = c. get (Calendar. MINUTE); // get the MINUTE 9 int second = c. get (Calendar. SECOND); // obtain the SECOND 10 System. out. println ("current time:" + year + "-" + month + "-" + day + "-" + hour + ":" + minute + ": "+ second); 11 12}

Running result:

Result Analysis:

Call the getInstance () method of the Calendar class to obtain an instance, and then call the get () method to obtain the date and time information. The parameter is the value of the field to be obtained, Calendar. year and so on are static constants defined in the Calendar class.

Note: There are two special parameters: DAY_OF_MONTH and HOUR_OF_DAY. Do not write them as DAY and HOUR,0 indicates January 1, January..

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

The Calendar class provides the getTime () method,Used to obtain the Date objectTo convert the Calendar and Date. You can also use the getTimeInMillis () method to obtain the time value of the Calendar, in milliseconds. As follows:

1 Date date = c. getTime (); // convert the Calendar Object to the Date object 2 Long time = c. getTimeInMillis (); // get the current number of milliseconds 3 System. out. println ("current time:" + date); 4 System. out. println ("Current millisecond count" + time );

Running result:

Summary:

1. Call the getInstance () static method to obtain a Calendar Object-object initialization

Calendar c = Calendar. getInstance ();

2. Call the get () method to obtain the date and time information.

Int month = c. get (Calendar. MONTH) + 1; ---- 0 indicates February

3. The getTime () method is provided to obtain the Date object.

Date date = c. getTime (); ---- convert a Calender object to a Date object

4. Use the getTimeInMillis () method to obtain the time value of the Calendar.

Long time = c. getTimeInMillis (); ---- get the current millisecond

4. Use Math to operate data

The Math class is located in the java. lang Package and containsPerform basic mathematical operationsMethods of the Math classAll methods are static methods.When using the methods in this class, you can directly use the class name. method name, such as Math. round ();

Common Methods:

The following code is used:

1 public static void main (String [] args) {2 double a = 12.81; 3 int B = (int) a; // force type conversion 4 System. out. println ("forced type conversion:" + B); 5 long c = Math. round (a); // call the round method and round it to 6 systems. out. println ("Rounding:" + c); 7 double d = Math. floor (a); // call the floor method and return the maximum integer 8 System smaller than the parameter. out. println ("floor method:" + d); 9 double e = Math. ceil (a); // call the ceil method and return the minimum integer 10 System greater than the parameter. out. println ("ceil method:" + e); 11 double x = Math. random (); // call the random method to generate a random number of 12 systems between [0, 1. out. println ("random number:" + x); 13 int y = (int) (Math. random () * 100); // generate a random number between [0,100) 14 System. out. A random number between println ("[0,100):" + y); 15 16}

Running result:

Note: the return value types of each Math method can be converted to the desired type by force type conversion.

PS: The Math class also provides many other methods. You can go to the API documentation as needed to find the methods you want to know.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.