Required common classes in Java (very useful)

Source: Internet
Author: User

Common classes that must be understood in Java, wrapper classes

I believe that all of you are very familiar with the basic data types, such as int, float, double, Boolean, Char, and so on. Basic data types do not have the properties of the object, such as the basic type cannot invoke the method, the function is simple ... , Java provides a wrapper class for each base data type, so that we can manipulate the base data type as an operand, in order for the basic data type to have the properties of the object.

Correspondence between the base type and the wrapper class:

Note: There are two wrapper class names compared to the Special One is an integer, the other is character, and the other is the base data class with the first letter capitalized.

The wrapper class provides two main types of methods:

1. Ways to convert this type and other basic types

2. Ways to convert strings and this type and wrapper class to each other

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

Conversions between basic types and wrapper classes in Java

The basic types and wrapper classes often need to be converted to each other, in the case of an Integer (the operation of several other packaging classes is similar):

1 integer a=new Integer (3);  defines an integer wrapper class object with a value of 3int b=a+5;  To perform an operation on an object and a base type     

With the introduction of the automatic boxing and unpacking mechanism in JDK1.5, the conversion between the wrapper class and the base type is easier and more convenient.

So what is packing and unpacking? Let's look at each of them:

Boxing: The basic type is converted into a wrapper class, so that it has the nature of the object, but also can be divided into manual boxing and automatic boxing.

int i=10; // set an int basic data type 2 integer x=new Integer (i);  Manual Boxing 3 Integer y=i;  Automatic boxing        
1 Double n=i; // type different cannot be boxed automatically 2 double m=new double (i);  different types can be boxed by hand     

unpacking: In contrast to boxing, the wrapper class object is converted into a basic type of value, which can be divided into manual unpacking and automatic unpacking.

1 integer j=new Integer (8);  defines an integer wrapper class object with a value of 8int n=j.intvalue ();  manual unboxing int m=j;  Automatic unpacking        
Double X=j.doublevalue (); // Different types of manual unboxing double y=j;  different types can be automatically removed     from the box

Note : different types cannot be boxed automatically , but different types can be automatically disassembled .

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

Conversions between basic types and strings in Java

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

There are three ways to convert the base type to a string :

1. Use the ToString () method of the wrapper class

2. Using the ValueOf () method of the String class

3. Using an empty string with the base type, you get the string that corresponds to the base type data

The code is as follows:

Converts the base type to a string int x=10;  3 String str1=integer.tostring (x); // method one 4 String str2=string.valueof (x);  method Two 5 String str3=x+ "";  method Three, essentially using the system automatic conversion type           

Again, there are two ways to convert a character string to a basic type :

1. Call the Parsexxx static method of the wrapper class

2. The ValueOf () method that calls the wrapper class is converted to the basic type of wrapper class, and the box is automatically disassembled

The code is as follows:

converts a string to a base type of 2 string str= "8";  int N=integer.parseint (str); // method one int y=integer.valueof (str);  method Two        

Note: strings are converted to basic types if the string contains other characters, the program will throw an exception when it runs. Therefore, it is best to use the Try-catch statement to capture and process the method.

PS: Other basic types and string conversions are no longer listed here, and the methods are similar.

Second, Date and SimpleDateFormat classes

In program development, it is often necessary to deal with date and time related data, when we can use the date class in the Java.util package. The main function of this class is to get the current time , let's look at the use of the Date class:

1 Date d=new Date ();  Create a Date object using the default construction method 2 System.out.println (d)            ;   

The object created by using the default parameterless construction method of the date class represents the current time , and we can directly output a Date object that displays the current time, showing the following results:

Among them, Thu stands for Thursday, Jul for July, 06 for No. 06, CST for China Standard Time (Beijing time, the East eight district).

From the above output, we found that the default time format is not very friendly, and we see the date format is not the same, if you want to display in the specified format, such as 2017-07-06 13:31:28, then how to do?

At this time to the Java.text package of SimpleDateFormat class to do their time!! You can use SimpleDateFormat to format datetime, such as to convert a date to text in a specified format, or to convert text to a date.

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

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

use the Format () method to convert a date to the specified format of text 2 date d=new Date ();  Use the default construction method to create a Date object 3 SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");  Specify date format 4 String today=Sdf.format (d);  5 System.out.println (today);           

Operation Result:

Results Analysis:

The code "YYYY-MM-DD HH:mm:ss" is a predefined string, yyyy represents four-bit years, MM for two-bit months, DD for two-bit dates, HH for hours (using 24-hour system), MM for minutes, and SS for seconds, so that the conversion is specified Format, and finally calls the format () method to convert the time to a string of the specified format.

2. Use the parse () method to convert text to a date

1//Create a string of date format2 String day= "July 06, 2017 13:42:10";3//Creates a SimpleDateFormat object that specifies the date format of the string4 SimpleDateFormat sd=New SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS" 5 // Call the Parse method to convert the string to a date Span style= "COLOR: #008080" > 6  Date date; 7 try { 8 date =  Sd.parse (day);  9  System.out.println (date),  Ten} catch (parseexception e) { 11 // TODO auto-generated Catch Block12  E.printstacktrace (); 13}               

Operation Result:

Results Analysis:

The "yyyy mm DD day HH:mm:ss" in the code specifies the date format of the string, and the parse () method is called to convert the text to a date. Because converting a string to a date type may throw an exception, it is captured with the Try-catch statement.

Must pay attention to OH:

1. When invoking the parse () method of the SimpleDateFormat object, a conversion exception may occur, that is, parseexception, so exception handling is required.

2. You need to import the Java.util package when using the Date class, you need to import the Java.text package when using SimpleDateFormat.

Third, the Calendar class application

The most important role of the date class is to get the current time, while the class also has set time and some other functions, but because of its own design problems, these methods have been criticized many, not recommended, it is recommended to use the Calendar class for time and date processing.

The Java.util.Calendar class is an abstract class that can get a Calendar object by calling the GetInstance () static method, which is initialized by the current datetime, which is the default representation of the current time , such as Calendar C = calendar.getinstance ();

So how do you use Calendar to get information about the year, month, day, time, and more? Let's look at the following code:

1PublicStaticvoidMain (string[] args) {2//TODO auto-generated Method Stub3 Calendar C = calendar.getinstance ();//Create a Calendar object4int year = C.get (calendar.year);//Get year5int month = C.get (calendar.month) +1;//Get month, 0 = January 6 int day = C.get (calendar.day_of_month); // get date  7  int hour = C.get (Calendar.hour_of_day); // get hours  8 int minute = C.get (Calendar.minute); // get minutes  9 int second = C.get (Calendar.second); // get seconds 10 System.out.println ("Current Time:" +year+ "-" +month+ "-" +day+ "-" +hour+ ":" +minute+ ":" +second) ; 11 12}         

Operation Result:

Results Analysis:

Call the GetInstance () method of the Calendar class to get an instance, and then get the datetime information by calling the Get () method, which is the value of the field that needs to be obtained, calendar.year, and so on as the static constant defined in the Calendar class .

Note: There are two special parameters: Day_of_month and Hour_of_day, do not write day and hour; month,0 for January .

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

The Calendar class provides the GetTime () method to get the Date object , complete the calendar and date conversions, and the Gettimeinmillis () method to get the time value of this calendar, in milliseconds 。 As shown below:

1  Date date=c.gettime ();  converts a Calendar object to a Date object 2          Long time=c.gettimeinmillis ();  gets the current number of milliseconds 3 System.out.println ("Current time:" +date);  4 System.out.println ("Current number of milliseconds" +time);       

Operation Result:

Summarize:

1. Gets a Calendar object---object class by calling the GetInstance () static method.

Calendar C = calendar.getinstance ();

2. Get datetime information by calling the Get () method

int Month=c.get (calendar.month) +1;----0 represents January

3. Provide the GetTime () method to get the Date object

Date Date=c.gettime ();----Convert the Calender object to a Date object

4. Get the time value for this Calendar by using the Gettimeinmillis () method

Long Time=c.gettimeinmillis ();----Gets the current millisecond

Iv. manipulating data using the Math class

The math class is located in the Java.lang package and contains methods for performing basic mathematical operations , all methods of the math class are static methods , so you can use the class name directly when using the methods in that class. Method names, such as: Math.Round ();

Common methods:

The following code is used to implement:

1PublicStaticvoidMain (string[] args) {2Double a=12.81;3int b= (int) A;//Forcing type conversions4 System.out.println ("Forced type conversion:" +b);5Long C=math.round (a);//Call the Round method to rounding6 System.out.println ("Rounding:" +c);7Double D=math.floor (a);//Call the floor method to return the largest integer less than the parameter8 System.out.println ("Floor method:" +D);9double E=math.ceil (a); // call Ceil method, return the smallest integer greater than the parameter  System.out.println ("Ceil method:" +e);  One double x=math.random ();   Call the Random method, which produces a number of randomly between [0,1] 12 System.out.println ("Random number: "+x); 13 int y= (int) ( Math.random () *100); // generates a random number between [0,100] 14 System.out.println ("[0,100) Random number:" +y);  16}           

Operation Result:

Note: Be aware that the math methods return value types, and you can use coercion type conversions to convert to the type you want.

The Ps:math class also offers many other ways that you can go to the API documentation to find the way you want to know.

Required common classes in Java (very useful)

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.