A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. /*
  2. 基础类型的隐式转换:
  3. byte,short,char  --> int --> long --> float --> double
  4. byte可隐转short

  5. 除了boolean,基础类型之间都可进行强制转换
  6. */

  7. public class TypeDemo {
  8.        
  9.         public static void isType(byte b) {System.out.println("it is a byte");}   //注释该行,isType(b)输出short
  10.         public static void isType(short s) {System.out.println("it is a short");}  //注释该行,isType(s)输出int
  11.         public static void isType(char c) {System.out.println("it is a char");}    //注释该行,isType(c)输出int
  12.         public static void isType(int i) {System.out.println("it is a int");}      //注释该行,上四个输出long
  13.         public static void isType(long l) {System.out.println("it is a long");}    //注释该行,上五输出float
  14.         public static void isType(float f) {System.out.println("it is a float");}  //注释该行,全输出double
  15.         public static void isType(double d) {System.out.println("it is a double");}


  16.         public static void main(String[] args) {
  17.                 byte b = 1;
  18.                
  19.                 short s = 1;
  20.                 short s2 = b;     //byte可隐转为short
  21.                 char c = 'c';
  22.                 //char c2 = b;    //报错,byte无法隐转char
  23.                 int i = 1;
  24.                 long l = 1;
  25. /*
  26.         整数型和char总结
  27.                 byte,short,char 中,只有byte可隐转为short

  28.                 byte,short,char 都可隐转int、float,运算时都隐转为int,'整数常量'默认类型为int

  29.                 赋值优化机制,'整数常量'可强转为 short,byte,char 赋值给基础数据类型
  30.                
  31. */
  32.                     
  33.                 //float f = 1.1;  可用float f = 1;  1隐转float,但是不能赋值默认double型小数给float
  34.                 float f = 1.0F;
  35.                 float f2 = 1L;    //可把long类型隐式转换为float
  36.                 double d = 1.0D;

  37.                 /*
  38.                 isType(c+b);      //it is a int
  39.                 isType(s+b);          //it is a int  ,char,short,byte    整数型和char型运算时会隐转为int
  40.                 isType(f+l);      //it is a double,   浮点数运算会隐转为double
  41.                 */
  42.                
  43.                 isType(b);
  44.                 isType(s);
  45.                 isType(c);
  46.                 isType(i);
  47.                 isType(l);
  48.                 isType(f);
  49.                 isType(d);

  50.         }
  51. }
复制代码
今天总结的时候写得测试小程序,基本上通过注释和反复运行,可以了解不同类型之间相互转换的情况。  有兴趣的同学可以copy下来,自己试试。明天我会发我写的关于JAVA各部分初始化顺序的小程序。看过的朋友帮忙顶顶~~ 谢谢~  一起加油

3 个回复

正序浏览
66666666666666666666666
回复 使用道具 举报
顶一下,感受感受正能量
回复 使用道具 举报
自顶~~~   希望大家多多围观支持
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马