Java type conversions and object conversion to other types

Source: Internet
Author: User
Tags object object

object to int

int count= (int) map.get ("Count")

int Count=integer.parseint (String) map.get ("Count"));
int Count=integer.parseint (Map.get ("Count"). ToString ());

Automatic data type conversions

Automatic conversions are converted in order from low to high. The priority relationships between different types of data are as follows:
Low---------------------------------------------> High
byte,short,char-> int, long, float---double

Operations, different types of data are converted to the same type first, then the operation, the conversion rules are as follows:

operand 1 Type operand 2 Type the converted type
Byte, short, Char Int Int
Byte, short, char, int Long Long
Byte, short, char, int, long Float Float
Byte, short, char, int, long, float Double Double
Forcing data type conversions

The format of the cast is to add "()" before the data that needs to be transformed, and then add the data type that needs to be converted in parentheses. Some data after transformation operation, the accuracy will be lost, and some will be more accurate, the following example can illustrate this problem.

  1. Public class Demo {
  2. Public static void main(String[] args){
  3. int x;
  4. Double y;
  5. X = (int)34.56 + (int)11.2; //Loss of precision
  6. Y = (double) x + (double) + 1; //Improve accuracy
  7. System. Out. println("x=" + x);
  8. System. Out. println("y=" + y);
  9. }
  10. }

Operation Result:
X=45
y=56.0

Carefully analyze the above program segment: Since there is a forced type conversion of int before 34.56, 34.56 becomes 34. The same 11.2 becomes 11, so the result of X is 45. There is a cast of type double before x, so the value of x becomes 45.0, and the front of 10 is also coerced to a double type, so it becomes 10.0, so the value of the last Y becomes 56.

Object to String

Method 1: Use the Object.ToString () method
Take a look at the following example:

1 Object object = GetObject ();

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:

Object obj = new Integer (100);
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

Integer obj = new integer (100);
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:

public static String valueOf (Object obj) {
return (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 2
SYSTEM.OUT.PRINTLN (NULL);


The output we see will be identical: null, but do they mean the same thing?
Note 1: The use of light in terms of SYSTEM.OUT.PRINTLN, statement System.out.println (Object.ToString ()); Change to System.out.println (object); Better. 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)); It is not recommended to use SYSTEM.OUT.PRINTLN (string.valueof (null)), which is a good practice when using overloaded methods.
The above is a summary of the conversion of object objects to string.

String Goto INT

1). int i = Integer.parseint ([String]); Or

i = Integer.parseint ([string],[int radix]);

2). int i = integer.valueof (my_str). Intvalue ();

Note: The string is converted to Double, Float, and Long in a similar way.

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.

object to int

int a=1;
Object Ao=a;
SYSTEM.OUT.PRINTLN ((int) AO); You can also output 1.

int B=inerger.parseint (obj.tostring ());

Turn from:

Java coercion type conversion

Java type conversions and object conversion to other types

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.