Common classes that you must know in Java

Source: Internet
Author: User

 1, the Java packaging class

Basic data types We are familiar with, for example: int, float, double, Boolean, Char, and so on, the basic data type does not have the characteristics of the object, cannot call the method, generally can achieve the function is relatively simple, in order to let the basic data type also has the characteristics of the object, Java provides a wrapper class for each data type, so that we can manipulate these basic data types just like the object.

The common wrapper classes and basic types correspond to the following relationships:

The wrapper class provides two main types of methods:

1. Convert between multiple types

2. Convert the string and the type and wrapper class to each other

For example, the following code:

1 int i = 2;2 integer m = new Integer (5), 3 integer n = new Integer ("8");

The first line defines the integer variable I with the base type, the second line defines the Int object m with the Int wrapper class, although the assignment is 5 of the integer type, but now converts the base type to 5 in the wrapper class

The third line initializes the value to "8" of the string type, but is converted to an integer type by the wrapper class, which is the basic use of the wrapper class

Each wrapper class can be converted to another class, such as an integer wrapper class, and the corresponding relationship of the transformation is as follows:

  

Depending on the corresponding relationship of the transformation, a simple example can be written as follows:

1 public class HelloWorld {2 public     static void Main (string[] args) {3   4          int score1 =;  5           6          //Create an Integer wrapper class object that represents the value of the variable score1 7          integer score2=new integer (score1); 8           9          // Converts an integer wrapper class to a double type of ten          double Score3=score2.doublevalue ()          ;          //Convert integer wrapper class to float type 13          float Score4=score2.floatvalue ();          convert an          integer wrapper class to an int type int          score5 =score2.intvalue () ;          System.out.println ("Integer wrapper class:" + Score2);          System.out.println ("Double type:" + score3); 20          System.out.println ("Float type:" + score4);          SYSTEM.OUT.PRINTLN ("int type:" + score5);      }23  }

With this simple wrapper class conversion program, it is also convenient to see that the wrapper class is converted to a variety of basic data types.

So how does the basic type convert to the object of the wrapper class? In fact, the previous three lines of code has been reflected, but not quite complete, the basic type conversion to the wrapper class can be understood as a boxing process, boxing has two ways: manual boxing and Automatic boxing, then the same wrapper class conversion to the basic type is called unboxing, also divided into: manual unpacking and automatic unpacking, The example above is an example of a manual unpacking,

Then the auto-boxing and auto-unpacking, the compiler automatically completes the conversion according to the data type, the simple code is as follows:

1 public class HelloWorld {2 public      static void Main (string[] args) {3          double A = 91.5; 4           5           //double type hand Dynamic Boxing 6          double b = new double (a);     7           8          //double type auto Boxing 9          double C = A;  Ten          System.out.println ("Boxed results are:" + B + "and" + C);          Double d = new double (87.0);          15          //Double wrapper class object is manually removed by          double e = D.doublevalue ();          //double wrapper class object automatically unpacking          double f = d;20          +           SYSTEM.OUT.PRINTLN ("The result after unpacking is:" + E + "and" + f);      }23  }

The example is simple, automatic and manual two operations are done for each data type, so the values for B and C are the same, and the values for E and F are the same.

In addition to wrapper conversions for basic data types, conversions can also be made between basic types and strings

For example, a basic type: int a = 30; there are 3 ways to convert to a string object:

1. Use the ToString method of the wrapper class, String str1 = integer.tostring (a);

2. Using the ValueOf method of the String class, String str2 = String.valueof (a);

3. With an empty string plus the base type, the system converts the base type to a string type, string str3 = A + "";

In turn, the definition is: string str = "18"; Converting a string type to a base type has the following two methods:

1. Call the Parsexxx static method of the wrapper class, int b = Integer.parseint (str);

2, call the wrapper class ValueOf method, complete the automatic unpacking, int c = integer.valueof (str);

Other types of conversions are the same, replacing the type inside, here's a simple example:

1 public class HelloWorld {2 public      static void Main (string[] args) {3           4          Double m = 78.5; 5          //convert base type to character String 6          String str1 = Double.tostring (m); 7           8          System.out.println ("M is converted to String and the sum of the integer 20 is:" + (STR1+20)); 9          String str = "180.20"; converts a          string to a basic type,          Double a = double.valueof (str);          System.out.println ("The sum of the integer 20 after the STR is converted to Double is:" + (A+20));      }16  }

This example implements two conversions, so the str1+20 should output: 78.520,a+20 should output: 200.20, the former result is a string type, the latter result is the basic floating-point type

  2. Java Date and time processing

Process development, time processing is essential, these content is relatively simple, will use some fixed classes to

First, we can use the date class in the Java.util package to get the time, as follows:

1 Date D = new Date (); 2 System.out.println (d);

This is the simplest method, but the output format may not be suitable for us: Mon Sep 21:46:13 CST 2015

So we need to make a simple modification, then we need to format the text with the format method in the SimpleDateFormat class in the Java.text package, the code is as follows:

1 Date D = new Date (), 2 simpledateformat sdf = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 3 String today = Sdf.format (d); 4 System.out.println (today);

This will output our usual time: 2015-09-21-21:51:39, another format we can also define according to our needs

Conversely, we can also change the text into the default time format, which uses the parse method in the SimpleDateFormat class, but this method can be an exception, So we need to Java.text exception class ParseException class for exception handling, see a small instance:

 1 Import java.text.ParseException; 2 Import Java.text.SimpleDateFormat; 3 Import java.util.Date;           4 5 public class HelloWorld {6 7 public static void Main (string[] args) throws ParseException {8 9//Use the format () method to convert the date to the text in the specified format. SimpleDateFormat sdf1 = new SimpleDateFormat ("yyyy mm month DD day hh"); 1 1 SimpleDateFormat sdf2 = new SimpleDateFormat ("Yyyy/mm/dd hh:mm"); SimpleDateFormat sdf3 = new Simple          DateFormat ("Yyyy-mm-dd HH:mm:ss"); 13 14//Create a Date object that represents the current time date now = new Date (); 16 17//Call the format () method to convert the date to a string and output the System.out.println (Sdf1.format (now)); System.out.println (SD F2.format (now)), System.out.println (Sdf3.format (now)); 21 22//Use the parse () method to convert text to a date of           D = "2015-9-21 21:56:36"; SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 25 26 Call the Parse () method to convert the string to dateDate = Sdf.parse (d); System.out.println (date); 30}31} 

The example is simple, it implements the time format, the conversion of the text to the date

There is also a time-processing calendar class in the Java.util package, because the design method of the date class has been criticized, so it is recommended to use the Calendar class to process the time, and the Calendar class is an abstract class that can obtain CALs by calling the GetInstance static method An object of Endar, which is initialized by default by the current time and comes directly to a simple instance:

1 package com.imooc.collection; 2  3 import Java.util.Calendar; 4  5 public class Dateaction {6  7 public     static void Main (string[] args) { 8         Calendar C = calendar.getinstance ();    Instantiate Calendar Object 9         int year = C.get (calendar.year);    Get the current year int by the Get method         month = C.get (calendar.month) + 1;    Month 0-11, need to add 111         int day = C.get (calendar.day_of_month);    Date         int hour = C.get (calendar.hour_of_day);    Get hours         int minute = C.get (Calendar.minute);    Get minutes         int second = C.get (Calendar.second);    Gets the number of seconds         System.out.println ("Current time:" + year + "years" + month + "Month" + Day + "days" + "+   hour + +"                 : "+ minute + ":" + second);     }18 19}

This prints out the result: Current time: September 21, 2015 22:12:13

The calendar also provides a gettime method for retrieving the date object, enabling the interaction of the calendar and date objects, and using Gettimeinmillis to get the number of milliseconds from January 01, 1970 0:0 0 seconds to the current time. It's about 1000 times times the Unix timestamp.

The simple code is as follows:

1 Date date = C.gettime ();    Object Conversion 2 Long time = C.gettimeinmillis ();    Gets the number of milliseconds to now 3 System.out.println ("Current time:" + date), 4 System.out.println ("Current number of milliseconds:" + time);

This enables the conversion

  3. Java Math arithmetic Math class

The math class is also commonly used in Java to do the class, in the Java.lang package, the system will be automatically imported, here is a simple record, commonly used methods:

  

Look directly at a simple example:

1 public class Mathaction {2  3 publicly     static void main (string[] args) {4         double A = 12.86; 5         int b = (in t) A;    Coercion Type conversion 6         System.out.println ("Forced type conversion:" + B); 7         Long C = Math.Round (a);    Rounded 8         System.out.println ("rounded:" + C); 9         Double d = Math.floor (a);    Returns the largest integer less than the parameter A,         System.out.println ("the largest integer less than a:" + D);         double E = Math.ceil (a);    Returns the smallest integer greater than the parameter A,         System.out.println ("the smallest integer greater than a:" + e);         Double x = Math.random ();    Generates a random floating-point number in the [0,1] interval,         System.out.println ("Default random Numbers:" + x);         int y = (int) (Math.random () *99);    Generates a random integer in the [0,99] interval of         System.out.println ("0-99 random integer (excluding the):" + y);     }19 20}

A very easy to understand example, the effect is as follows:

The above is commonly used in Java development classes and methods, the above is mainly packaging class, time processing, mathematical calculation of these

Common classes that you must know in Java

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.