当前位置:   article > 正文

java学习Day10_请修改该方法,以保证打印对象时输出格式如下

请修改该方法,以保证打印对象时输出格式如下

类型转换

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k9fAcP7X-1611839061362)(C:\Users\86178\AppData\Roaming\Typora\typora-user-images\image-20210128152959758.png)]

运算中,不同类型的数据转化为同一类型,然后进行运算

强制类型转换

自动类型转换

import javax.xml.bind.SchemaOutputResolver;
import java.sql.SQLOutput;

public class JH04 {
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte) i;  //内存溢出

        //强制转换    (类型)变量名    高----低
        //自动转换    变量名    低----高

        System.out.println(i);
        System.out.println(b);
        System.out.println("================");
        System.out.println((int)23.7);//23
        System.out.println((int)-45.89f);//-45
        System.out.println("================");

        char c = 'a';
        int d = c+1;
        System.out.println(d);
        System.out.println((char) d);
    }
        /*
        注意点:
        1.不能对布尔值进行转换
        2.不能把对象类型转换为不相干的类型
        3.在把高容量转换为低容量的时候,强制转换
        4.转换的时候可能存在内存溢出或者精度问题!
         */


        //结果:  128    -128    23    -45    98    b
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
public class JH05 {
    public static void main(String[] args) {
        //操作比较大的数时,注意溢出问题
        //JDK7新特性
        int money = 10_0000_0000;
        int years = 20;
        int total = money*years;
        long total2 = money*years;
        long total123 = money*((long)years);

        System.out.println(money);
        System.out.println(total);//-1474836480,是否计算时溢出
        System.out.println(total2);//默认是int,转换之前已经存在问题
        System.out.println(total123);//200_0000_0000

        //  L  l  一般使用大写的L
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/804005
推荐阅读
相关标签
  

闽ICP备14008679号