Implicit type conversion: Difference between revisions
Content added Content deleted
No edit summary |
(Added Java example) |
||
Line 567: | Line 567: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
The Java Language Specification includes several varieties of implicit type conversion. This code illustrates: <ul><li>widening conversions of primitives</li><li>boxing and unboxing conversions</li><li>string conversions (with the + operator)</li></ul> |
|||
{{incorrect|Java}} |
|||
<lang java>public class ImplicitTypeConversion{ |
|||
See [https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html|Java Language Specification Chapter 5. Conversions and Promotions] |
|||
public static void main(String...args){ |
|||
System.out.println( "Primitive conversions" ); |
|||
byte by = -1; |
|||
short sh = by; |
|||
int in = sh; |
|||
long lo = in; |
|||
System.out.println( "byte value -1 to 3 integral types: " + lo ); |
|||
float fl = 0.1f; |
|||
double db = fl; |
|||
System.out.println( "float value 0.1 to double: " + db ); |
|||
int in2 = -1; |
|||
float fl2 = in2; |
|||
double db2 = fl2; |
|||
System.out.println( "int value -1 to float and double: " + db2 ); |
|||
int in3 = Integer.MAX_VALUE; |
|||
float fl3 = in3; |
|||
double db3 = fl3; |
|||
System.out.println( "int value " + Integer.MAX_VALUE + " to float and double: " + db3 ); |
|||
char ch = 'a'; |
|||
int in4 = ch; |
|||
double db4 = in4; |
|||
System.out.println( "char value '" + ch + "' to int and double: " + db4 ); |
|||
System.out.println(); |
|||
System.out.println( "Boxing and unboxing" ); |
|||
Integer in5 = -1; |
|||
int in6 = in5; |
|||
System.out.println( "int value -1 to Integer and int: " + in6 ); |
|||
Double db5 = 0.1; |
|||
double db6 = db5; |
|||
System.out.println( "double value 0.1 to Double and double: " + db6 ); |
|||
} |
|||
} |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
Primitive conversions |
|||
byte value -1 to 3 integral types: -1 |
|||
float value 0.1 to double: 0.10000000149011612 |
|||
int value -1 to float and double: -1.0 |
|||
int value 2147483647 to float and double: 2.147483648E9 |
|||
char value 'a' to int and double: 97.0 |
|||
Boxing and unboxing |
|||
int value -1 to Integer and int: -1 |
|||
double value 0.1 to Double and double: 0.1 |
|||
</pre> |
|||
Notice that in the second and fourth conversions the result is a slightly different value. |
|||
Not included are: |
|||
<ul> |
|||
<li>reference conversions (for example, you can treat a reference as if it were a reference to its superclass)</li> |
|||
<li>unchecked conversions (the sort of thing that the compiler warns about if you use non-generic collections) |
|||
<li>capture conversions (not sure I understand, but it seems to allow wildcard generics where explicit generics would otherise be required) |
|||
</ul> |
|||
=={{header|jq}}== |
=={{header|jq}}== |