Java基本类型数据转换

亦凉 2023-05-22 14:27 129阅读 0赞

基本类型数据转换(1-2)

1.2.1、定义变量

  1. 变量格式:
  2. 数据类型 变量名 = 初始化值
  3. 数据类型:
  4. byte,short,int,long,float,double,char,boolean

Demo

  1. public class VariableDemo {
  2. /*
  3. * 变量的定义
  4. * */
  5. public static void main(String[] args){
  6. // 定义byte 类型
  7. byte a = 10;
  8. System.out.println(10);
  9. System.out.println(a);
  10. // 定义 short类型
  11. short b = 11;
  12. System.out.println(b);
  13. // 定义int类型
  14. int c = 12;
  15. System.out.println(c);
  16. // 定义long类型
  17. long d = 1231L;
  18. System.out.println(d);
  19. // 定义float类型
  20. float e = 1.23F;
  21. System.out.println(e);
  22. // 定义double类型
  23. double f = 1.23;
  24. System.out.println(f);
  25. // 定义char类型
  26. char g = 'a';
  27. System.out.println(g);
  28. // 定义boolean类型
  29. boolean h = true;
  30. System.out.println(h);
  31. }
  32. }

1.2.2、变量定义的注意事项

  1. package one;
  2. /**
  3. * Created by JackFeng on 2020/2/22.
  4. */
  5. public class BianLiang {
  6. /*
  7. * 变量定义的注意事项
  8. * A: 变量未赋值,不能直接使用
  9. * B:变量只在所属的范围内有效(仅在它所在的大括号中有效)
  10. * C: 一行可以多个变量(不建议)
  11. * */
  12. public static void main(String[] args){
  13. // 定义变量aa、
  14. int aa = 2020;
  15. System.out.println(aa);
  16. {
  17. // 大括号中的就是代码块
  18. int ab = 131;
  19. System.out.println(ab);
  20. }
  21. // 定义多个变量
  22. int a1, a2;
  23. a1 =11;
  24. a2 = 20;
  25. System.out.println(a1);
  26. System.out.println(a2);
  27. }
  28. }

1.2.3、类型转化

  1. package one;
  2. /**
  3. * Created by JackFeng on 2020/2/25.
  4. */
  5. /*
  6. * +: 加法运算符
  7. *
  8. * 运算中,要求参与运算的数据类型必须一致
  9. *
  10. *
  11. * 类型转化:
  12. * 隐式转化
  13. * 强制转化
  14. * 隐式转化:
  15. * byte,short,char -- int --long --float --double
  16. * byte+ int === int 类型
  17. * 强制转化:
  18. * 目标类型 变量名 = (目标类型)(被转化的数据)
  19. * 建议:数据做运算,最好以结果类型为准(不要随意转化,否则可能损失精度)
  20. * int a = 10;
  21. * byte b = 20;
  22. * int c = a+b
  23. *
  24. * byte d = (byte)(a + b)
  25. *
  26. *
  27. * */
  28. public class TypeCastDemo {
  29. public static void main(String[] args) {
  30. // 1、 定义同类型变量
  31. int a = 11;
  32. int b = 22;
  33. int c = a + b;
  34. System.out.println(c);
  35. // 定义一个 byte 类型 一个int类型
  36. int a1 = 10;
  37. byte a2 = 20;
  38. System.out.println(a1+a2);
  39. }
  40. }

format_png期待您的行动

format_png 1

在看和转发

都是一种支持

format_png 2

发表评论

表情:
评论列表 (有 0 条评论,129人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java基本数据类型转换

    概述 基本数据类型有空间大小的关系,所以基本数据类型之间就可以进行相互的转换,但是转换之前要首先了解数据类型的排序。 基本数据类型从大到小排序 double >

    相关 Java基本数据类型转换

    学习目标: 掌握Java的基本数据类型转换 学习内容: 1、转化规则 在8大基本数据类型中,boolean不属于数值类型,所以不参与转换,其他类型的转