zoukankan      html  css  js  c++  java
  • java基础05-类型转换

    Java类型转换

    • 由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换

      低 -------------------------------------------------------- 高

      byte -- short -- char -- int -- long -- float -- double

    • 运算中,不同类型的数据需要转换成同一类型数据,然后再进行计算

    • 强制类型转换

    • 自动类型转换

      示例

      public static void main(String[] args) {
      
          int i = 128;
          int i1 = 129;
          byte b = (byte) i; // 强制转换 高-->低
          double d = i; // 自动转换 低-->搞
          byte b1 = (byte) i1;
          System.out.println(b); // -128 因为内存溢出
          System.out.println(b1); // -127 因为内存溢出(但是会根据指针确定值)
      
          /**
           * 注意点: 
           * 1. 不能对布尔类型进行转换 
           * 2. 不能把对象类型转换为不相关类型 
           * 3. 把高容量转换为低容量的时候,需要强制转换 
           * 4. 转换的时候可能存在溢出,或者精度问题
           */
          System.out.println((int) 23.7f); // 23
          System.out.println((int) -45.87); // 45
      
          char c = 'a';
          int e = c + 1;
          System.out.println(e); // 98
          System.out.println((char) e); // b
      
          /**
           * 操作比较大的数字的时候注意内存溢出问题
           * Java7新特性,数字中间可以加下划线,方便我们识别
           */
          int money = 10_0000_0000;
          int year = 20;
          int total1 = money * year;
          System.out.println(total1); // -1474836480 由于内存溢出导致
      
          long total2 = money * year;
          System.out.println(total2); // -1474836480 由于内存溢出导致,因为计算之前就已经存在内存溢出问题了。
      
          long total3 = money * (long) year;
          System.out.println(total3); // 20000000000 提前转换,会用转换后类型去计算
      }
      
    欢迎一起来学习和指导,谢谢关注!
  • 相关阅读:
    《吊打面试官》系列-缓存雪崩、击穿、穿透
    WebGL学习之纹理贴图
    小试小程序云开发
    关于socket.io的使用
    动画函数的绘制及自定义动画函数
    canvas实现俄罗斯方块
    Redis集群
    手工搭建基于ABP的框架
    手工搭建基于ABP的框架(3)
    手工搭建基于ABP的框架(2)
  • 原文地址:https://www.cnblogs.com/mask-xiexie/p/14563257.html
Copyright © 2011-2022 走看看