java类型转换的例子

Java中数据类型自动转换优先级

犹由于java是强类型语言,所以进行一些运算的时候,必须进行类型转换
运行中不同类型数据先转为同一类型再进行运算

 

/*注意点:1.不能对布尔值进行转换2.不能把对象类型转换为不相干的类型3.转换的时候可能存在内存溢出或者精度问题!4.向下转型需要强转,向上自动转型,也就是把高容量转为低容量的时候,强制转换 */

代码1

public class Demo5 {
   public static void main(String[] args) {
       //大转小,强制转换,小转大,自动转换
       //===========================低-高
       //byte,short,char,int,long,float,double
       int i=128;
       byte a=(byte) i;//内存溢出
       System.out.println(a);
       //强制转换 (类型)变量名 高-低

       byte b=12;
       int c=b;
       System.out.println(c);
       //自动转换 低-高

       System.out.println("========================================");
       System.out.println((int)23.99);//23
       System.out.println((int)-45.9);
       System.out.println("========================================");
       char t='a';
       int e=t+1;
       System.out.println(e);
  }
}
     

代码2

    public class Demo6 {
  public static void main(String[] args) {
      //JDK7新特性,可以在int类型加下划线,且下划线不会被打印输出
      //操作比较大的数据时候,注意溢出问题
      int money=10_0000_0000;
      int years=20;
      int total=money*years;//
      long total2=money*years;
      long total3=(long)money*years;
      System.out.println(total);//-1474836480
      System.out.println(total2);//-1474836480
      System.out.println(total3);//20000000000
  }
}

 

posted @ 2021-09-23 00:10  帆再小也能远航  阅读(185)  评论(0)    收藏  举报