Java Notes 程序猿的读书笔记

Java 1_convert

2018-09-01  本文已影响0人  綿綿_

How to convert any other type to a string

String byteString = Byte.toString(bigByte);
            String shortString = Short.toString(bigShort);
            String intString = Integer.toString(bigInt);
            String longString = Long.toString(bigLong);
            String floatString = Float.toString(bigFloat);
            String booleanString = Boolean.toString(trueOrFalse);
            String charString = Character.toString(randomChar); // You don't need to do this
            System.out.println(charString);
            // Can't do this because char is a primitive data type
            // System.out.println(randomChar.getClass());
            // You can do this because String is an object  
           System.out.println(charString.getClass());

How to use casting to convert from one primitive type to another

         double aDoubleValue = 3.1456789;
         int doubleToInt = (int) aDoubleValue;
         /* To cast to other primitive types just proceed with the conversion to type
          * ie (byte) (short) (long) (double)
          * (float) & (boolean) & (char) don't work.
          * (char) stays as a number instead of a character*/

Use parseInt to convert a string into an integer

            int stringToInt = Integer.parseInt(intString);
            /* Other parse functions
             * parseShort, parseLong, parseByte, parseFloat, parseDouble, parseBoolean
             * There is no reason to parse a Character */
上一篇下一篇

猜你喜欢

热点阅读