Java基本数据类型之间的转换

      我们在平时开发过程中经常会处理到不同类型直接相互转换的情况,深入了解他们的关系十分重要。我们首先以byte类型为例


public class DataTypeChangeTest {
   private static byte byteV;
    private static short shortV;
    private static int intV;
    private static long longV;
    private static float floatV;
    private static double doubleV;
    private static boolean booleanV;
    private static char charV;
    static {
        byteV=120;
        shortV=200;
        intV=-40000;
        longV=System.currentTimeMillis();
         floatV=311.22222F;
         doubleV=311.111777111777111D;
         booleanV=false;
         charV='d';
    }

    public static void main(String[] args) {
        testByte();


    }

    /**
     * 测试基本数据类型与byte之间转换关系
     * 1.byte 可以直接转换为 short int long float double
     * 2. byte 可以转换为char 但是需要强制转换
     * 3. byte 不可以转换为boolean
     * 4. short int long float double float char 转化为byte 需要强制类型转换 会丢失精度
     * 5. short int long float double float char 转化为byte 如果原值不在-128 ~127 范围内
     * 转换后的值是原值加上或是减去256的整数倍
     * 当然最准确的还是将十进制转换为二进制 若是二进制不止8位就截取最后八位 二进制如果是以1开始要取补码(反码+1)
     */
    private static void testByte() {
        short shortVV=byteV;
        System.out.println(String.format("byte 转换为 short:%s,%s",byteV,shortVV));
        int intVV=byteV;
        System.out.println(String.format("byte 转换为 int:%s,%s",byteV,intVV));
        long longVV=byteV;
        System.out.println(String.format("byte 转换为 long:%s,%s",byteV,longVV));
        float floatVV=byteV;
        System.out.println(String.format("byte 转换为 float:%s,%s",byteV,floatVV));
        double doubleVV=byteV;
        System.out.println(String.format("byte 转换为 double:%s,%s",byteV,doubleVV));
        char charVV= (char) byteV;
        System.out.println(String.format("byte 转换为 char:%s,%s",byteV,charVV));

        byte byteV1= (byte) shortV;
        System.out.println(String.format("short 转换为 byte:%s,%s",shortV,byteV1));
        byte byteV2= (byte) intV;
        System.out.println(String.format("int 转换为 byte:%s,%s",intV,byteV2));
        byte byteV3= (byte) longV;
        System.out.println(String.format("long 转换为 byte:%s,%s",longV,byteV3));
        byte byteV4= (byte) floatV;
        System.out.println(String.format("float 转换为 byte:%s,%s",floatV,byteV4));
        byte byteV5= (byte) doubleV;
        System.out.println(String.format("double 转换为 byte:%s,%s",doubleV,byteV5));
        byte byteV6= (byte) charV;
        System.out.println(String.format("char 转换为 byte:%s,%s",charV,byteV6));
        //        boolean ag=a;
    }
}

现在,我们可以来总结下:

  • 1.占用字节少的类型可以直接转换为转换字节多的类型
  • 2.整数类型 浮点数类型 都不可以转换为boolean类型
  • 3.占用字节高的类型转换为占用字节少的类型需要强制转换,会丢失精度
  • 4.占用字节高的类型转换为占用字节少的类型会丢失精度,转换后的值是原值加上或是减去新的类型取值范围的整数倍
  • 当然最准确的还是将十进制转换为二进制 若是二进制超过低字节类型的位数就截取最后的位数:以byte为例就是最后八位 二进制如果是以1开始要取补码(反码+1)

你可能感兴趣的:(Java基础)