Translate

Search This Blog

Total Pageviews

Wednesday, October 10, 2018

Java Type Conversion

 Assignment = is really an operator in the sense that an
assignment can itself be used as an expression or as part of a more complex expression.
The value of an assignment such as A=B is the same as the value that is assigned to A. 
So, if you want to assign the value of B to A and test at the same time whether that value is zero, you could say:
if ( (A=B) == 0 )   // Usually don’t do things like that!

In general, the type of the expression on the right-hand side of an assignment statement must be the same as the type of the variable on the left-hand side.
However, in some cases, the computer will automatically convert(Implicit casting) the value computed by the expression to match the type of the variable.
Implicit casting(or promotion) happens when the source type has smaller range than the target type.


                      Numeric primitive casting

Consider the list of numeric types:
byte, short, int, long, float, double.
A value of a type that occurs earlier in this list can be converted automatically to a value that occurs later.
The idea is that conversion should only be done automatically(Implicit casting) when it can be done without changing the semantics of the value. 
//Implicit casting
byte byteVar = 42;
short shortVar = byteVar;
int intVar = shortVar;
long longVar = intvar;
float floatVar = longVar;
double doubleVar = floatVar;


char char1 = 1, char2 = 2;
short short1 = 1, short2 = 2;

// char1 = char1 + char2;  // Error: Cannot convert from int to char;
// short1 = short1 + short2; // Error: Cannot convert from int to short;



Any int can be converted to a double with the same numeric value. However, there are int values that lie outside the legal range of shorts.
There is simply no way to represent the int 100000 as a short, for example, since the largest value of
type short is 32767.
In some cases, you might want to force a conversion that wouldn’t be done automatically(Explicit casting). For this, you can use what is called a type cast.
Explicit casting has to be done when the source type has larger range than the target type.

 //Explicit casting
double doubleVar = 42.0d;
float floatVar = (float) doubleVar;
long longVar = (long) floatVar;
int intVar = (int) longVar;
short shortVar = (short) intVar;
byte byteVar = (byte) shortVar;


You can do type casts from any numeric type to any other numeric type.
However, you should note that you might change the numeric value of a number by type-casting it. 
For example, (short)100000 is -31072.
(The -31072 is obtained by taking the 4-byte int 100000 and throwing away two of those bytes to obtain a short—you’ve lost the real information that was in those two bytes.)
When you type-cast a real number to an integer, the fractional part is discarded. 
For example, (int)7.9453 is 7.
When casting floating point primitives (float, double) to whole number primitives, the number is rounded down.

As another example of type casts, consider the problem of getting a random integer between 1 and 6.
The function Math.random() gives a real number between 0.0 and 0.9999. . . 
and so 6*Math.random() is between 0.0 and 5.999. . . .
The type-cast operator, (int), can be used to convert this to an integer: (int)(6*Math.random()) is one of the integers 0, 1, 2, 3, 4, and 5..

To get a number between 1 and 6, we can add 1:
(int)(6*Math.random()) + 1”.
(The parentheses around 6*Math.random() are necessary because of precedence rules; without the parentheses, the type cast operator would apply only to the 6.)

              Non-numeric primitive casting

 The boolean type cannot be cast to/from any other primitive type.

int badInt = (int) true;  // Compiler error: incompatible types


 A char can be cast to/from any numeric type by using the code-point mappings specified by Unicode.
A char is represented in memory as an unsigned 16-bit integer value (2 bytes), so casting to byte (1 byte) will drop 8 of those bits (this is safe for ASCII characters). The utility methods of the Character class use int (4 bytes) to transfer to/from code-point values, but a short (2 bytes) would also suffice for storing a Unicode code-point.

The type char is almost an integer type. You can assign char values to int variables, and you can assign integer constants in the range 0 to 65535 to char variables.
You can also use explicit type-casts between char and the numeric types. 
For example,
(char)97 is ’a’,
(int)’+’ is 43, and
(char)(’A’ + 2) is ’C’.

char char1    =  (char) 65;  // A
byte byte1    =  (byte) 'A'; // 65
short short1  =  (short) 'A'; // 65
int int1          =  (int) 'A'; // 65


char char2 = (char) 8253; // ‽
byte byte2 = (byte) ' '; // 61 (truncated code-point into the ASCII range)
short short2 = (short) ' '; // 8253
int int2  = (int) ' '; // 8253


                           Object casting

As with primitives, objects can be cast both explicitly and implicitly.
Implicit casting happens when the source type extends or implements the target type (casting to a superclass or interface).
Explicit casting has to be done when the source type is extended or implemented by the target type (casting to a subtype). This can produce a runtime exception (ClassCastException) when the object being cast is not of the target type (or the target's subtype).
Float floatVar = new Float(42.0f);
Number n = floatVar;   //Implicit (Float implements Number)
Float floatVar2 = (Float) n;  //Explicit
Double doubleVar = (Double) n; //Throws exception (the object is not Double)

 

Testing if an object can be cast using instanceOf

Java provides the instanceOf operator to test if an object is of a certain type, or a subclass of that type. The program can then choose to cast or not cast that object accordingly.

Object obj = Calendar.getInstance();
long time = 0;
if(obj instanceOf Calendar) {
    time = ((Calendar)obj).getTime();
}
if(obj instanceOf Date) {  

    // This line will never be   reached, obj is not a Date type.
     time = ((Date)obj).getTime();
}


Type conversion between String and other types cannot be done with type-casts.
One way to convert a value of any type into a string is to concatenate it with an empty string.
For example,
"" + 42 is the string "42".
But a better way is to use a static member function in the String class aka the function String.valueOf(x): returns the value of x, converted into a string.
For example,
String.valueOf(42) is the string "42", and
if ch is a char variable, then String.valueOf(ch) is a string of length one containing the single character that is the value of ch.

It is also possible to convert certain strings into values of other types.
For example, the string "10" should be convertible into the int value 10, and the string "17.42e-2" into the double value 0.1742.
In Java, these conversions are handled by built-in functions.
The standard class Integer contains a static member function for converting from String to int.
In particular, if str is any expression of type String, then Integer.parseInt(str) is a function call that attempts to convert the value of str into a value of type int.
For example,
the value of Integer.parseInt("10") is the int value 10.
If the parameter to Integer.parseInt() does not represent a legal int value, then an error occurs.
Similarly, the standard class Double includes a function Double.parseDouble(str) .
If str is a String, then the function call Double.parseDouble(str) tries to convert str into a value of
type double.
An error occurs if str does not represent a legal double value.


Resources

Introduction to Programming Using Java - David J. Eck
 Java Notes for Professionals - Compiled from StackOverflow documentation (3.x)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.