Java数据基本类型

位、字节

位(bit)是计算机内部数据储存的最小单位。

字节(byte)是计算机中数据处理的基本单位,习惯上用B表示

1B=8 bit

基本数据类型

数值类型

整数类型

byte占1个字节范围(2^8):-128-127;

short占2个字节范围(2^16):-32768-32767;

int占4个字节范围(2^32):-2147483648-2147483647

long占8个字节范围(2^64):-9223372036854775808-9223372036854775807

浮点类型

float占4个字节范围

double占8个字节范围

字符类型

char占2个字节范围

boolean类型

该类型占1位且值只有true和false两个


public class Eight_basic_types {
   public static void main(String[] args) {
//       八大基本类型

       //整数
       int num1=20;
       byte num2=-5;
       short num3=12345;
       long num4 =123546L;//long类型后面要加个 ‘L’

       //小数
       float num5=26.53F;//float类型后面要加个'F'
       double num6= 1.23456789;

       //字符
       char name='w';//引号里只能有一个字母或者汉字

       //布尔类型
       boolean flag1=true;
       boolean flag2=false;
       
  }
}

最好完全避免使用浮点数进行比较

public class float_comparison {
   public static void main(String[] args) {
       float num1=0.1f;
       double num2=1/10;
       System.out.println(num1==num2); //false

       float num3=2333333333333333333f;
       float num4=num3+1;
       System.out.println(num3==num4);//true
  }
}

数据类型转换

1.不能对布尔类型进行转换。

2.不能把对象类型转换成不相干的类型,比如不能把数值类型转换成布尔类型。

3.在把高容量类型转到低容量类型时需要强制转换。

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

4.转换时可能存在内存溢出或者精度问题。

public class type_conversion {
   public static void main(String[] args) {
       //高容量向低容量转换,需要强制转换
       int a=128;
       byte b= (byte) a;
       System.out.println(b);
       //这个结果输出是-128,因为byte的容量是-128-127,强转时内存溢出了

       //低容量像高容量转换,可以自动转换
       int c=28;
       double d =c;
       System.out.println(d);
       //结果为28.0

       //当可能存在内存溢出问题时,在计算之前就需要强制转换
       int money =10_0000_0000;
       int year=20;
       int total=money*year;
       System.out.println(total);
       //该结果打印出来为 -1474836480,出现内存溢出

       long total1 =money*year;
       System.out.println(total1);
       //这种写法依然会内存溢出

       //正确写法
       long total2=money*((long) year);
       System.out.println(total2);
       //结果为20000000000

  }
}

 

 

 

posted @ 2021-02-20 05:12  QZheng  阅读(41)  评论(0)    收藏  举报