Conversion Value and Casting JAVA

Conversion Value and Casting JAVA

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:

01public class Konversi{
02public 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);
09   }
Conversion Value and Casting JAVA
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:

01class Cast {
02public static void main(String args[]) { double x, y;
03byte b; int i; char ch; x = 10.0;
05i = (int) (x / y); // cast double to int
06System.out.println(“Integer Output from x / y: ” + i); i = 100;
07b = (byte) i;
08System.out.println(“Value of b: ” + b); i = 257;
09b = (byte) i;
10System.out.println(“Value of b: ” + b); b = 88; // ASCII code for X
11ch = (char) b; System.out.println(“ch: ” + ch);
Conversion Value and Casting JAVA
java coding results cast

Leave a Reply

Your email address will not be published. Required fields are marked *