zoukankan      html  css  js  c++  java
  • Java基础知识强化22:Java中数据类型转换

    数据类型转换:

    (1). 自动转换

    低级变量可以直接转换为高级变量,这叫自动类型转换。比如:

    byte b; int b;  long b;  float b;   double  b;

    上面的语句可以在Java中直接通过.

    (2).如果低级类型为char型,向高级类型(整型)转换时候,会转换为对应的ASCII码值,例如:

    char c ='c';  int i = c;  System.out.println("output:"+i);

    输出: output:99

    (3).对于byte/short/char三种类型而言,它们是相同级别的,因此,不能相互自动转换类型,可以使用强制类型转换。

    short i=99; char c=(char)i;  System.out.println("output:"+c);

    输出: output:c

    (4).高级类型向低级类型转换会出现精度损失

    (5).包装类过渡类型转换  (弥补4中精度损失的问题)

    java中共有6个包装类分别是Boolean,Character,Integer,Long,Float和Double;

    而String和Date本身就是类,不存在包装类。

    e.g: float--->double

    float  f1 =  100.00f;

    Float  F1 = new Float(f1);

    Double d1 = F1.doubleValue();

    e.g: double--->int

    double  d1 =100.00;

    Double D1 = new Double(d1);

    int   i1 = D1.intValue(); 

    (6)字符串类型与其他数据类型的转换

    class   Test  {

         public  static  void  main(String  args[] ) {

                int  i1 = 10;

                float  f1 = 3.14f;

                double d1 = 3.1415926;

                Integer I1 = new Integer(i1);

                Float  F1 = new Float(f1);

                Double D1 = new Double(d1);

                String  si1 = I1.toString();

                String  sf1 = F1 .toString();

                String  sd1 = D1.toString();

                System.out.println("si1"+si1);

                System.out.println("sf1"+si1);

                System.out.println("sd1 "+si1); 

        }

    }

    (7)将字符型直接作为数值转换为其他数据类型

    使用Character的getNumericValue(char  ch)方法

  • 相关阅读:
    BEC listen and translation exercise 44
    中译英12
    BEC listen and translation exercise 43
    中译英11
    BEC listen and translation exercise 42
    中译英10
    BEC listen and translation exercise 41
    中译英9
    BEC listen and translation exercise 40
    中译英8
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4815401.html
Copyright © 2011-2022 走看看