JAVA Coercion Type conversion

Source: Internet
Author: User
Tags object object

Reference: http://blog.csdn.net/aeolus1019/article/details/7971309

Some summary of converting object object to String

In the actual development and application of Java projects, it is often necessary to use the basic function of converting objects to string. This article will make a summary of the common conversion methods. Common methods are object.tostring (), (String) objects to be converted, string.valueof (object), and so on. Each of these methods is analyzed below.
Method 1: Use the Object.ToString () method
Take a look at the following example:

Object object =

Note 1
In this method of use, because the public method is already in the Java.lang.Object class. ToString (), this method can be called for any Java object that is strictly meaningful. Note, however, that object must be guaranteed to be not a null value, otherwise the NullPointerException exception will be thrown. With this approach, the derived class typically overrides the ToString () method in object.
Method 2: Use the type conversion (String) object method
This is the standard type conversion, which converts an object to a value of type string. When using this method, it is important to note that the type must be able to be turned into a string type. Therefore, it is best to use instanceof as a type check to determine whether it can be converted. Otherwise it is easy to throw calsscastexception exceptions. In addition, it is particularly necessary to be especially careful that the syntax check does not cause an error when the object that is defined as type objects is turned into a string, which can lead to potential errors. Be extra careful at this point. Such as:

New Integer (+); String strval = (string) obj;

Errors will occur at run time because the integer type is cast to a string type and cannot be passed. But

New Integer (+); String strval = (string) obj;

As in the format code, the syntax error will be reported.
In addition, because null values can be cast to any Java class type, (String) NULL is also legal.
Method 3: Use String.valueof (Object)
String.valueof (Object) is based on object.tostring (). But it's different from objec.tostring (). In the previous analysis of Method 1, it was mentioned that the latter should be guaranteed not to be null. However, with the third approach, you will not have to worry about whether object is a null value. For the sake of explaining the problem, let's analyze the relevant source code. A string in the JDK. ValueOf (Object) source code is as follows:

Static String valueOf (Object obj) {       null)? "Null" : Obj.tostring ();}  

From the above source code can be very clear to see the null value without worrying reasons. However, this also gives us a hidden danger. We should note that when object is null, the value of String.valueof (object) is the string "null" instead of
Null!!! Remember to keep in mind when using the process. Imagine if we were to use if (string.valueof (object) ==null) {System.out.println ("the value passed in is null! ”);} Such a statement will likely be problematic. Think again, when outputting to the console, visually the following statements differ in the result of the execution:

System.out.println (string.valueof (Object)null); note 2system.out.println (null);  

> The output we see will be the same thing: null, but do they have the same meaning?
Note 1: The light is used for SYSTEM.OUT.PRINTLN, the statement System.out.println (Object.ToString ()), and the System.out.println (object); The use of this is primarily to illustrate the use of object#tostring ().
Note 2: It is recommended to use SYSTEM.OUT.PRINTLN (string.valueof (Object) null); System.out.println (string.valueof (NULL)) is not recommended; This is a good practice when using overloaded methods.
The above is a summary of the conversion of object objects to string. The
New integer.valueof () returns an Integer object.
Integer.parseint () returns the value of an int.

New Integer.valueof (). Intvalue (); Returns the value of an int as well.
Integer.valueof (String s) is a wrapper class object that converts an actual value to a number variable into a String and then turns it into an integer (equivalent to an object that has been converted to int) so that the object that is turned over has methods and properties.
and Integer.parseint (string s) just converts the string that is a number into a number, noting that he returns an int variable that does not have methods and properties.
1 string converted to data
The string is converted into an integer:

String MyNumber = "1234";  int MyInt = Integer.parseint (MyNumber); 

The string is converted to a byte, short, int, float, double, long, and other data types, which can be referenced by the Parsexxx method of Byte, short, Integer, float, double, long, respectively.
2 data converted into strings
Convert integers to Strings:

int MyInt = 1234; String MyString = "" + MyInt;

Other data types can be converted into strings using the same method.
3 Decimal to other binary conversions
A decimal integer is converted to a binary integer, and the result is a string:
integer.tobinarystring (int i);
Integer and long provide the tobinarystring, tohexstring, and tooctalstring methods to easily convert data into binary, hexadecimal, and octal strings. The more powerful feature is its ToString (int/long i, int radix) method, which converts a decimal number into any string form of any binary.
Data types such as Byte, short, float, and double can be used with an integer or a long tobinarystring, tohexstring, to The Octalstring and ToString methods are converted into other binary string forms.
4 Conversion to decimal for other binary
The five-binary string 14414 is converted to a decimal integer, and the result is 1234:

System.out.println (integer.valueof ("14414", 5);

The valueof (string source, int radix) method provided by integer and long allows you to convert any string into decimal data.
5 Conversion of integers to byte arrays

1PublicStaticByte[] Tobytearray (IntNumber) {2int temp =Number 3 byte[] b=new byte[4]; 4 for (int i = b.length-1; i >-1; I--)  { 6 b[i] = new Integer (temp & 0xff 7 temp = temp >> 8; 8 } 9 return10}             

6-byte array to integer conversion

1PublicStaticint Tointeger (Byte[] b) {2int s = 0;3for (int i = 0; I < 3; i++)4{5if (B[i] > 0)6 S = s + B[i];  7} else { 8 s = s + + B[i]; 9 s = s * 256; 10 }11 if (b[3] > 0) 12 s = s + b[3 13 else14 s = s + n + b[3< Span style= "color: #000000;" >]; 15 return S;16}                 


7 conversion between a short integer and a byte array
The difference between short and int is that short is two bytes, and int is four bytes. Therefore, you only need to change the sample program in 5 and 6 to make the conversion between the short integer and the byte array.
8-byte arrays converted to double-precision floating-point numbers

PublicDouble ToDouble (Byte[] b) {Long L = 0; Double D =new Double (0.0long) B[1]<<8); L |= ((long) B[2]<<16); L |= ((long) B[3]<<24); L |= ((long) B[4]<<32); L |= ((long) B[5]<<40); L |= ((long) B[6]<<48); L |= ((long) B[7]<<56); return d.longbitstodouble (l);}     

9 Converts a Boolean type into a string
The first method is:

Truenew Boolean (bool). toString ();  Converts bool to object S.equals ("true") using the object wrapper;  

The second method is:

True; String s = string.valueof (bool);

First of all, the second method is obviously more concise than the first method in terms of code length, and secondly, the first method introduces a completely unnecessary object in the process of conversion, therefore, it causes the waste of memory space and greatly slows down the running speed in the relative second method. Therefore, it is recommended to use the second method.
10 conversion between a numeric type and a numeric class object

1BYTE B = 169;2 Byte bo =NewByte (b);3 B =Bo.bytevalue ();4Short T = 169;5 Short to =NewShort (t);6 T =To.shortvalue ();7int i = 169;8 Integer io =NewInteger (i);9 i =Io.intvalue ();10Long L = 169;One Long lo =NewLong (l);L =Lo.longvalue ();13float F =169f;14 float fo = new Float (f ); 15 f = Fo.floatvalue (); double d = 169f; Double dobj = new18 d = Dobj.doublevalue ();  String to Integer20 Integer in=new Integer (String s); new Integer (Integer.parseint (String s));      

5.1 String to int

int i = Integer.parseint ([String]); or i = Integer.parseint ([string],[int radix]); int i = integer.valueof (my_str). Intvalue ();

5.2 How do I convert an integer int to a string string?

A. There are three ways:

String s = string.valueof (i); String s = integer.tostring (i); String s = "" + I; 

Note: Double, Float, Long turn into a string in a similar way.
5.3 String to Date

Import java.util.Date date=null; date=java.sql.date.valueof (String s); 

JAVA Coercion Type conversion

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.