Conversion Value in the Assignment
Converting the value of a variable to another variable can be done with the following requirements:
• Two compatible data types
• Type of interest must be greater scope than other types of sources.
For example, the source integer into String destination.
Syntax as follows:
static int parseInt (String s)
static int parseInt (String s, int radix)
Parameter Explanation:
- s - This is a representation of a decimal string.
- radix - this will be used to convert string s to an integer.
- parseInt (String s): This returns an integer (decimal lodging only).
- parseInt (int i): This returns an integer, given a string representation of a decimal, binary, octal, or hexadecimal (radix equal to each of 10, 2, 8, or 16) numbers as input.
The program conversion Java example as follows:
01 |
public class Konversi{ |
02 |
public static void main(String args[]){ |
03 |
int x = Integer.parseInt( "9" ); |
04 |
double c = Double.parseDouble( "5" ); |
05 |
int b = Integer.parseInt( "444" , 16 ); |
06 |
System.out.println(x); |
07 |
System.out.println(c); |
08 |
System.out.println(b); |
 |
coding result, in the above example is the conversion from Integer to Double, and Double to Integer |
Type Casting against type that does not Compatible
Cast is an instruction to the compiler to convert one type to the other. The syntax is as follows:
(Target-type) expression
Examples coding Java programs using a cast:
02 |
public static void main(String args[]) { double x, y; |
03 |
byte b; int i; char ch; x = 10.0 ; |
05 |
i = ( int ) (x / y); / / cast double to int |
06 |
System.out.println( "Integer Output from x / y: " + i); i = 100 ; |
08 |
System.out.println( "Value of b: " + b); i = 257 ; |
10 |
System.out.println( "Value of b: " + b); b = 88 ; / / ASCII code for X |
11 |
ch = (char) b; System.out.println( "ch: " + ch); |
 |
java coding results cast |