Sunday, May 22, 2016

Casting Numbers


In java you can cast from type to type as long as there in the same class. For example you can cast a floating number to a double, but not an integer to a string. Some types can only hold a certain amount of memory. So when converting between types you must be careful that the type you’re casting to can hold that value. If you do convert a number that doesn’t fit in that type, it may cut off the extra spaces. For example if you cast a floating number to an integer it will cut of the decimals. (It won’t round the number. Math.round does that for you.) When casting a number you must set a variable equal to the variable you want to cast. In parenthesis before the casted variable you must put the type you want to convert to.

Below shows code where I did many different casts. At the bottom I tried to cast a value of 128 to a byte. The problem is that a byte only holds up to 127, so what you get as an output is byte’s minimum, -127.

public class App {

      public static void main(String[] args){
            byte byteValue = 20;
            short shortValue = 55;
            int intValue = 808;
            long longValue = 3332322;
            float floatValue = 8834.8f;
            double doubleValue = 32.4;      
            
            System.out.println(Byte.MAX_VALUE);
            intValue = (int)longValue;
            System.out.println(intValue);
            doubleValue = intValue;
            System.out.println(doubleValue);       
            intValue = (int)floatValue;
            System.out.println(intValue);

            //ByteMax is 127;
            // the following won't work as we expect it to .
            //128 is to big for a byte.
            byteValue = (byte)128;
            System.out.println(byteValue);
          
      }
}

No comments:

Post a Comment