Classes commonly used in Java: include basic types of wrapper classes, Date classes, SimpleDateFormat classes, Calendar classes, Math classes

Source: Internet
Author: User
Tags time and date wrapper

wrapper classes in JAVA

There is no string inthe wrapper class, it is a reference data type

A base type cannot call a method, and its wrapper class has many methods

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

Basic type

The corresponding packaging class

Byte

Byte

Short

Short

Int

Integer

Long

Long

Float

Float

Double

Double

Char

Character

Boolean

Boolean

Integer m=NewInteger (5);//defines an integer wrapper class object with a value of 5Integer n=NewInteger ("8");//defines an integer wrapper class object with a value of 8 Public Static voidMain (string[] args) {intScore1=86; //creates an integer wrapper class object that represents the variable Score1Integer score2=NewInteger (Score1); //converting an Integer wrapper class to a double type        Doublescore3=Score2.doublevalue (); //converting an Integer wrapper class to a float type        floatscore4=Score2.floatvalue (); //converting an Integer wrapper class to an int type        intscore5=Score2.intvalue (); System.out.println ("Integer wrapper class" +score2); System.out.println ("Double type" +score3); System.out.println ("Float type" +Score4); System.out.println ("Int type" +Score5); }
conversions between basic types and wrapper classes

Boxing: converts the basic type into a wrapper class, which has the properties of the object and can be divided into manual boxing and automatic packing.

char sex= ' male '; // define a basic type    Character sex1=new Character (sex); // Manual Boxing    Character Sex2=sex; // Automatic Boxing, omitting new

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

Integer j=NewInteger (8);//defines an integer wrapper class object    intM=j.intvalue ();//Manual Unpacking    intN=j;//automatic unpacking to int type    Doublea=91.4; Double b=NewDouble (a); Double C=A; System.out.println (b+ "and" +c); //Double d=NewDouble (87.0); DoubleE=D.doublevalue (); Doublef=D; System.out.println (e+ "and" +f);

Conversions between basic types and strings

There are three ways to convert a 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

// converting a base type to a string        double a=91.4;        String str1=double.tostring (a);        String str2=string.valueof (a);        String str3=a+ "";

There are two ways to convert a string into 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

// Convert a string to a base type    String str= "9";     int d=integer.parseint (str);     int e== "180.20";     // Convert a string to a base type    Double a =double.parsedouble (str2);     // other basic types and string conversions are no longer listed here, and the methods are similar

Use Date and simpledateformat classes represent time

Use The default parameterless construction method of the date class creates an object that represents the current time , and we can directly output a Date object that displays the current time

Date nowtime=new date (); // Create a Date object using the default construction method        System.out.println (Nowtime); // output Date Object     >>>  Sat Mar 13:46:10 CST 2018

can use SimpleDateFormat to format datetime, such as the ability to convert a date to text in the specified format, or to convert the text to a date.

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

ImportJava.text.SimpleDateFormat;Importjava.util.Date; Public Static voidMain (string[] args) {//creates a Date object that represents the current timeDate nowtime=NewDate (); //Create a SimpleDateFormat object that specifies the destination formatSimpleDateFormat sdf=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); //call the Format () method, format the time, convert to the specified format stringString today=Sdf.format (nowtime);    System.out.println (today); }
    1. Convert text to a date using the Parse () method
      // Create a string    of date format String day= "February 14, 2014 October 30:13";     // creates a SimpleDateFormat object that specifies the date format of the string (to correspond to the format of the string)    SimpleDateFormat df=New SimpleDateFormat ("YYYY year mm month DD Day hh month MM:SS");     // Call the Parse () method to convert the string to a date    Date date=df.parse (day);    SYSTEM.OUT.PRINTLN (date);

Be sure to note:

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

2. Use the Date class to import the java.util package, using the simpledateformat You need to import the java.text Package

Application of Calendar class

more recommended to use the Calendar class takes 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 , This object has been initialized by the current datetime, which means that the default is the current time, such as Calendar C = calendar.getinstance ();

Calendar C=calendar. getinstance ();//Create a Calendar object

 Public Static voidMain (string[] args) {Calendar C=calendar.getinstance ();//Create a Calendar object        intYear=C.get (calendar.year); intMonth=c.get (calendar.month) +1;//get month, 0 for January        intday=C.get (Calendar.day_of_month); intHour=C.get (Calendar.hour_of_day); intMinute=C.get (Calendar.minute); intSecond=C.get (Calendar.second); System.out.println ("Current time:" +year+ "-" +month+ "-" +day+ "" +hour+ ":" +minute+ ":" +second ";}

The Calendar class provides the getTime () method, which is used to get the Date object, complete the calendar and Date conversion, but also through the Gettimeinmillis () method to obtain this Calendar the time value, in milliseconds.

 Public Static void Main (string[] args) {        Calendar C=calendar.getinstance ();   Create calendar object        Date date=c.gettime ();   Converts a calendar object to a Date object        long time=c.gettimeinmillis ();   Gets the current time, in milliseconds        System.out.println (date+ "/" + Time);    }

Date/simpledateformat/calendar Comprehensive Application

 Public Static void Main (string[] args) {        Calendar c=calendar.getinstance ();        Date Date=c.gettime ();        SimpleDateFormat sdf=new simpledateformat ("Yyyy-mm-dd HH:mm:ss");        Stringnow =Sdf.format (date);        System.out.println ("Current time:" + now);    }

Use Math class operation data

The math class is located in the java.lang Package and contains methods for performing basic mathematical operations, and all methods of the math class are static methods . So when using the methods in this class, you can use the class name directly . method names, such as: Math.Round ();

Common methods:

return 0~1 Random floating-point number between

return value

Method name

explanation

Long

Round ()

Returns rounded integers

Double

Floor ()

Returns the largest integer less than the parameter

Double

Ceil ()

Returns the smallest integer greater than the parameter

Double

Random ()

 Public Static voidMain (string[] args) {Doublea=12.81; intB= (int) A; System.out.println ("A forces the type after the converted value:" +b); LongC=Math.Round (a); System.out.println ("Rounding:" +c); DoubleD=Math.floor (a); System.out.println ("The maximum integer less than the parameter:" +d); DoubleE=Math.ceil (a); System.out.println ("The smallest integer greater than the parameter:" +e); Doublef=Math.random (); //generate random integers, first call the random () method to generate a 0~1 floating-point number//multiply the largest integer to be generated, and finally force the type conversion to be called int type        intG= (int) (Math.random () *99); System.out.println (f+" / "+g); } Public Static voidMain (string[] args) {int[] nums=New int[10];  for(inti=0;i<nums.length;i++) {Nums[i]=(int) (Math.random () *10); }         for(intx:nums) {System.out.print (x+" "); }    }

END

Classes commonly used in Java: include basic types of wrapper classes, Date classes, SimpleDateFormat classes, Calendar classes, Math classes

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.