Converting Types

Suppose that you have a number stored in a String. How do you add two to the number in the String? Well, you need to change the String into an integer.

This isn't an uncommon thing. All of the textfields in Java return a String. Sometimes the textfield will hold an integer that you need to convert from the String to an integer.

Here are some examples:

String to Double

   String s = "23.4567";
   double g = Double.valueOf(s).doubleValue();
   System.out.println("String to double: "+g);

String to Integer

   String s1 = "980";
   int h = Integer.parseInt(s1);
   System.out.println("String to int: "+h);

Integer to String

   int i = 234;
   String j = ""+i;
   System.out.println("Int to string: "+j);

Casting

A short form way of converting types.

   byte a = (byte) Math.PI;
   System.out.println ("Pi as a byte: " + a);
   short b = (short) Math.PI;
   System.out.println ("Pi as a short: " + b);
   int c = (int) Math.PI;
   System.out.println ("Pi as a int: " + c);
   float d = (float) Math.PI;
   System.out.println ("Pi as a float: " + d);
   double e = (double) Math.PI;
   System.out.println ("Pi as a double: " + e);
   String f = ""+Math.PI;
   System.out.println ("Pi as a String: " + f);

The output:

   Pi as a byte: 3
   Pi as a short: 3
   Pi as a int: 3
   Pi as a float: 3.1415927
   Pi as a double: 3.141592653589793
   Pi as a String: 3.141592653589793