八种基本数据类型(java)

基础准备:   8种基本数据类型包括4种整型,2种浮点型,1个字符型,1个布尔型   暂且称呼为:(4211)    4种整型: byte  short  int  long   2种浮点型:float ...

基础准备:

  8种基本数据类型包括4种整型,2种浮点型,1个字符型,1个布尔型

  暂且称呼为:(4211) 

  4种整型: byte  short  int  long

  2种浮点型:float  double

  1种字符型:char

  1种布尔型:boolean

详细分析:

  基本数据类型和引用数据类型的区别:  

    基本数据类型 是JAVA程序里已经定义好的规则,引用类型 是程序员在程序编写时定义的,一般只在程序员写的某个程序里有意义。

   Java中如何强制类型转换?

    通常有两类类型转换规则:

      自动类型转换(自动),较小的类型转换为一个更大的类型

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

      强制类型转换(手动),更大的类型转换到一个较小的类型

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

    为什么要强制类型转换:

      因为java是强制类型语言,程序在运行到不同数据类型的时,需要转变类型才能正常运行.

    什么情况下使用强制类型转换:

      程序遇到大单位转换小单位;

      int——》byte

      例如:一瓶水倒入水杯中,剩下多余的去掉。

    自动类型转换示例:

1 public class TestClass {
2   public static void main(String[] args) {
3     int testInt = 2;
4     double testDouble = testInt; // 自动类型转换,将int转换为double
5  
6     System.out.println(testInt);      // 输出 2
7     System.out.println(testDouble);   // 输出2.0
8   }
9 }

    强制类型转换示例:

    

public class TestClass {
  public static void main(String[] args) {
    double testDouble = 5.68;
    int testInt = (int) testDouble; // 强制类型转换: double 转换成 int
 
    System.out.println(testDouble);   // 输出 5.68
    System.out.println(testInt);      // 输出 5
  }
}
  • 发表于 2020-03-08 12:05
  • 阅读 ( 184 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除