Java Foundation Learning Note 14 Basic types of common API wrapper class

Source: Internet
Author: User
Tags wrapper

Basic type wrapper class

There are 8 basic data types in Java, but this data is basic data, it is difficult to do complex operation. What do we do?
In the actual program use, the user input data on the program interface is stored as a string type. In the program development, we need to convert the string data to the specified basic data type according to the requirement, such as the age needs to be converted into int type, the test result needs to be converted into double type, etc. So, what about converting between strings and basic data?
The corresponding object is provided in Java to solve the problem, the basic data type Object wrapper class: Java encapsulates the base data type value into an object. What are the benefits of encapsulating objects? The ability to provide more basic values for operations. The packaging classes for the 8 basic types are as follows:

It is important to note that int corresponds to the integer,char corresponding to the character, the other 6 are the basic type of the first letter uppercase.

Basic data type Object wrapper class features: Used to convert between basic data and strings.

Convert a string to a base type

Parsexxx (string s), where xxx represents the base type, the argument is a string that can be converted to the base type, and if the string cannot be converted to the base type, a problem with the number conversion will occur numberformatexception

System. out. println (Integer.parseint ("123"2); // Print result is
Convert a base value to a string

There are 3 ways of doing this:

    • The basic type is directly connected with ""; 34+ ""
    • Call the ValueOf method of String; String.valueof (34);

    • Call the ToString method in the wrapper class; Integer.tostring (34);

basic types and Object conversions

Using the int type to demonstrate with integer object conversions, the other basic types are converted in the same way.

Basic values----> Wrapper objects

New Integer (4); // using constructor functions New Integer ("4"); // A numeric string can be passed in the constructor  = integer.valueof (4); // using the ValueOf method in the wrapper class Integer IIII = integer.valueof ("4"); // using the ValueOf method in the wrapper class
Package Object----> Basic Values

int num = I.intvalue ();
automatic packing and unpacking

The base type and the wrapper type can be generic if required. Sometimes when we have to use reference data types, we can pass in the base data type.
Like what:
The base type can be evaluated directly using an operator, but the reference type is not available. The basic type wrapper class, as one of the reference types, can be computed because Java "secretly" automatically transforms an object into a basic data type.
Correspondingly, the value of the reference data type variable must be the memory space address value of new, and we can assign a value of a base type to a reference to a basic type wrapper class. The same reason is that Java also "secretly" automatically transforms the basic data type to the object.
Auto-Unpacking: objects are converted to basic values
Auto-Boxing: Basic values turn into objects

4; // Automatic Boxing. Equivalent to Integer i = integer.valueof (4); 5; // To the right of the equals sign: Converts the I object to the base value (auto-unpacking) I.intvalue () + 5; After the addition operation is finished, it is boxed again, and the base value is converted to the object. 

Auto-Boxing (byte Chang) details

When the value is within the byte range, auto-boxing does not create the new object space but uses the existing space.

Integer A =NewInteger (3); Integer b=NewInteger (3); System. out. println (A==B);//falseSystem. out. println (A.equals (b));//trueSystem. out. println ("---------------------"); Integer x=127; Integer y=127;//when the jdk1.5 is boxed automatically, if the value is within the byte range, the object space is not newly created, but the original space is used. System. out. println (X==y);//trueSystem. out. println (X.equals (y));//true
System Class

The system class introduced in the API is relatively simple, we give the definition, systems in which the program is located, provide some of the corresponding system property information, and system operation.
The system class cannot create objects manually because the constructor method is private and prevents objects from being created by the outside world. The system class is a static method, and the class name is accessed. In the JDK, there are many such classes.
Common methods

Currenttimemillis () Gets the millisecond difference between the current system time and the January 01, 1970 00:00 Point

Exit (int status) is used to end a running Java program. parameter to pass in a number. Typically incoming 0 is recorded as normal, others are in an abnormal state

GC () is used to run the garbage collector in the JVM to complete the removal of garbage in memory.

GetProperty (string key) to get the system property information that is recorded in the specified key (string name)

The Arraycopy method, which is used to implement copying a portion of a source array to a specified location in the destination array

method exercises for the system class

Verifying the amount of time (in milliseconds) required for a for loop to print the number 1-9999

 Public Static void Main (string[] args) {        long start = system.currenttimemillis ();          for (int i=0; i<10000; i++) {            System.out.println (i);        }         long end = system.currenttimemillis ();        System.out.println ("Total time-consuming milliseconds:" + (end-start));    }

Exercise two: Copy the first 3 elements of the SRC array to the first 3 positions of the dest array

Before copying an element: src array element [1,2,3,4,5],dest array element [6,7,8,9,10]
After copying an element: src array element [1,2,3,4,5],dest array element [1,2,3,9,10]

 public  static  void   main (string[] args) { int  [] src = new  int  []{1,2,3,4,5};  int  [] dest = new  int  []{6,7,8,9,10};        System.arraycopy (SRC,  0, dest, 0, 3);  //  After code runs: two elements in the array have changed  // src array element [1,2,3,4,5]  // dest array element [1,2,3,9,10] } 

Exercise three: loop to generate three digits between 100-999 and print that number, when the number can be divisible by 10, the end of the running program

 Public Static void Main (string[] args) {        new  Random ();          while (true) {            int//0-899 +            if (nmumber% = = 0) {                system.exit (0);}}    }
Math class

The math class is a mathematical tool class that contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.
A tool class like this [Tool class, which represents a class capable of accomplishing a series of functions, does not create an object when using them, the method in that class is a static method], all of its methods are static methods, and the object is generally not created. such as the System class

Common methods

Abs method, the result is positive

Double // the value of D1 is 5 Double // The value of D2 is 5

The Ceil method, which results in a double value of the smallest integer greater than the value of the parameter

Double // the value of D1 is 4.0 Double // The value of D2 is-3.0
Double D3 = Math.ceil (5.1); The value of D3 is 6.0

The floor method, which results in a double value of the largest integer smaller than the value of the parameter

Double // the value of D1 is 3.0 Double // The value of D2 is -4.0 Double // The value of D3 is 5.0

Max method, returns the larger value of two parameter values

Double // the value of D1 is 5.5 Double // The value of D2 is -3.3

Min method, returns the lower value of the two parameter values

Double // the value of D1 is 3.3 Double // The value of D2 is -5.5

Pow method, which returns the value of the second parameter of the first argument to a power of

Double // the value of D1 is 8.0 Double // The value of D2 is 27.0

Round method, returns the result of rounding the parameter value

Double // the value of D1 is 6.0 Double // The value of D2 is 5.0

The random method that produces a double decimal that is greater than or equal to 0.0 and less than 1.0

double D1 = Math.random ();
Arrays Class

This class contains various methods for manipulating arrays, such as sorting and searching. It is important to note that if the specified array reference is null, access to methods in this class throws a null pointer exception nullpointerexception.

Common methods

Sort method for sorting elements in the specified array (element values are sorted from small to large)

// The source arr array element {1,5,9,3,7}, sorted after the arr array element is {1,3,5,7,9} int [] arr = {1,5,9,3,7}; Arrays.sort (arr);

ToString method that returns the string form of the contents of the specified array element

int [] arr = {1,5,9,3,7//  str values are [1, 3, 5, 7, 9]

The BinarySearch method, in the specified array, to find where the value of the given element appears. If no query is reached, the return position is-1. Requires that the array must be an ordered array.

int [] arr = {1,3,4,5,6}; int // The value of index is 2 int // the value of Index2 is-1
methods of arrays class practice

Exercise One: Define a method that receives an array that stores 10 student test scores, which requires returning the last three test scores with the lowest test score.

   Public Static int [] Method (double[] arr) {        // sort array elements (element values are sorted from small to large)        int  Newint// store three exam scores        system.arraycopy (arr, 0, result, 0, 3);   copies the first 3 elements of the ARR array into the result array and        return  result;    
Big Data OperationsBigInteger

The long type in Java is the largest integer type, and how to represent data that is longer than long. In the world of Java, integers longer than long can no longer be called integers, and they are encapsulated as BigInteger objects. In the BigInteger class, Implementing arithmetic is implemented by methods, not by operators.
How to construct the BigInteger class:

In the constructor method, an integer is given in the form of a string
Arithmetic code:

   Public Static voidMain (string[] args) {//Big Data Encapsulation for BigInteger objectsBigInteger BIG1 =NewBigInteger ("12345678909876543210"); BigInteger Big2=NewBigInteger ("98765432101234567890");//Add to implement the addition OperationBigInteger Bigadd =Big1.add (BIG2);//subtract implementing the subtraction operationBigInteger bigsub =big1.subtract (BIG2);//multiply implementing multiplication operationsBigInteger Bigmul =big1.multiply (BIG2);//Divide Implementing Division operationsBigInteger Bigdiv =big2.divide (BIG1); }
BigDecimal

What happens when you execute the following code in your program?

System.out.println (0.09 + 0.01); System.out.println (1.0-0.32); SYSTEM.OUT.PRINTLN (1.015 *); System.out.println (1.301/100);

Double and float types are prone to loss of precision in operations, resulting in inaccurate data, and Java provides our BigDecimal class with high-precision operations that enable floating-point data

The construction method is as follows:

It is recommended that floating-point data be given as a string because the parameter results are predictable
Implement the addition subtraction multiplication code as follows:

  Public Static voidMain (string[] args) {//Big Data Encapsulation for BigDecimal objectsBigDecimal BIG1 =NewBigDecimal ("0.09"); BigDecimal Big2=NewBigDecimal ("0.01");//Add to implement the addition OperationBigDecimal Bigadd =Big1.add (BIG2); BigDecimal Big3=NewBigDecimal ("1.0"); BigDecimal BIG4=NewBigDecimal ("0.32");//subtract implementing the subtraction operationBigDecimal bigsub =big3.subtract (BIG4); BigDecimal Big5=NewBigDecimal ("1.105"); BigDecimal Big6=NewBigDecimal ("100");//multiply implementing multiplication operationsBigDecimal Bigmul =big5.multiply (BIG6); }

For the division operation of floating-point data, unlike integers, there may be infinite repeating decimal, so you need to preserve and select rounding mode for the number of digits you need

Java Foundation Learning Note 14 Basic types of common API wrapper class

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.