Java基础之数据类型

一、数据类型

  1. 基本数据类型介绍
  • byte 1字节
  • char 2字节
  • short 2字节
  • int 4字节
  • long 8字节
  • float 4字节
  • double 8字节

  以上有Java中八大基本类型的7种,而boolean类型的字节数没有明确规定。boolean类型有两个值:true、false,他们可以用1字节进行存储。JVM会在编译时期将boolean类型的值转化为int类型进行存储,1表示true,0表示false。

JDK官方文档:boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

  基本类型的两条准则:

  • Java中,如果对整型数据不指定类型默认为int类型,浮点数默认为double类型
  • 基本数据类型从小到大可以自动转换,从大到小需要进行类型强制转换

  2.类型转换

  上面提到基本数据类型从大到小需要强制转换,但是并不说明都需要用户手动转换,Java提供了在编译期间的隐式转换,当赋值语句右边为字面常量时,编译器自动进行类型转换。如:

public static void main(String[] args) {
        short a = 1;//1是字面常量,自动转换为short类型
        char b =1+5;//1+5为常量表达式,编译器自动计算结果并转换
        byte c = a+1;//编译不通过,a+1为变量表达式,运行期才可计算

    }

  但是字面常量的隐式转换也存在着限制:

  • 整型字面常量大小超出目标类型的表示范围时需要强制转换:
public static void main(String[] args) {
        byte b = 128;//编译错误,byte 范围在-128 到 127之间
        byte c = (byte)128;//编译通过
    }
  • 对于传参数时,必须要显式地进行强制类型转换,明确转换的类型

  编译器子所以这样要求,其实为了避免 方法重载出现的隐式转换 与 小类型自动转大类型 发生冲突。

public static void main(String[] args) {
    
    shortMethod(8);//编译错误
    shortMethod((short)8); //编译通过
    longMethod(8);//编译通过,因为这是小类型变成大类型,是不需要强制类型转换的
}

public static void shortMethod(short c){
    System.out.println(c);
}

public static void longMethod(short l){
    System.out.println(l);
}
  • 复合运算符的隐式转换

  在Java中复合运算符+=、-=、*=、/=、%= 可以自动的将右边表达式类型强制转换为左边的表达式类型,不需要用户显式的转换:

 public static void main(String[] args) {
       int a = 1;
       short b = 2;
       b = b+a;//编译不通过,类型转换失败
       b += a;//使用+=复合运算符 编译器自动处理成:b=(short)(b+a);
    }

  3.运算结果类型

  在Java中表达式的结果类型为参与运算的类型中的最高类型

 public static void main(String[] args) {
       float a = 1.2f;
       double b = 33;
       float c = a+b;//编译不通过:类型为double类型,需要强制转换
    }

  而在byte,short,char中则不同,它们的运算结果都为int类型。

 public static void main(String[] args) {
       byte b = 1;
       short c = 2;
       char a = b+c;//编译不通过,结果类型为int类型
    }

综上所述,java的运算结果的类型有两个性质:

  • 运算结果的类型必须是int类型或int类型以上。
  • 最高类型低于int类型的,运算结果都为int类型。否则,运算结果与表达式中最高类型一致。

二、包装类型

  Java为面向对象语言,但为了更加的效率及方便依旧使用了基本数据类型。为了让对象类型与基础类型联系起来以及让基础类型能向类类型一样具有方法使其操作更加便捷,Java提供了基础类型的包装类。

基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成。

public static void main(String[] args) {
       Integer i = 1;//自动装箱
        int s = i; //自动拆箱
    }

  参考博文:

作者:jinggod
出处:http://www.cnblogs.com/jinggod/p/8424583.html

作者:cyc

出处:https://cyc2018.github.io

原文地址:https://www.cnblogs.com/ring2/p/11068302.html