Java基础数据类型

基础数据类型

  基础数据类型:byte(字节型),short(短整型),int(整型),long(长整型),float(单精度浮点型),double(双精度浮点型),char(字符型)

 

     1.byte字节型

  占1个字节,范围-128到127

byte a=5;
byte b=6;
//byte c=200;//编译错误,超出范围

  2.short短整型

  占2个字节,范围-32768到32767

short a=10;

  3.int整型

  占4个字节,范围-2^31到2^31-1,大概正负21亿

        int a=25;//25为整数直接量,默认为int类型
        //int b=10000000000;//编译错误,100亿默认为int类型,但超出范围
        //int c=3.14;//编译错误整型变量中只能装整数

        System.out.println(5/2);//2
        System.out.println(2/5);//0
        System.out.println(5/2.0);//2.5


        int d=2147483647;//int最大值
        d=d+1;
        System.out.println(d);//-2147483648,int最小值,发生了溢出

 

  4.long长整型

  占8个字节,-2^63到2^63-1,大概正负900万万亿

long a=25L;//25L为长整型直接量
       // long b=10000000000;//编译错误,100亿默认为int类型,但超出范围
//        long c=3.14;//编译错误,长整型变量中只能装整数

        long e=1000000000*2*10L;
        System.out.println(e);//200亿
        long f=1000000000*3*10L;
        System.out.println(f);//不是300亿
        long g=1000000000L*3*10;
        System.out.println(g);//300亿

  5.float单精度浮点型

  占4个字节,精确到小数点后6-7位

float a=3.14F;

  6.double双精度浮点型

  占8个字节,精确到小数点后15-16位

        double a=3.14;
        double c=6.0,d=1.9;
        System.out.println(c-d);//4.1

        double e=1.0,f=0.9;
        System.out.println(e-f);//0.09999999999999998

        double g=4.9,h=1.0;
        System.out.println(g-h);//3.9000000000000004    

  7.boolean布尔型

  占1字节

 boolean a=true;//true为布尔型直接量
      boolean b=false;//false为布尔型直接量
//      boolean c=250;//编译错误,布尔型只能存储true和false

  8.char字符类型

  占2个字节

char c1='女';//字符女
        char c2='f';//字符f
        char c3='6';//字符6
        char c4=' ';//空格符
        //char c5= 女;//编译错误,字符直接变量必须放到单引号中
        //char c6='';//编译错误,必须有字符
        //char c7='10';//编译错误,只能存储一个字符

      
        char c9='\\';//转义符
        System.out.println(c9);// \

类型转换

分为自动类型转换(隐式类型转换)和强制类型转换

int a=5;
        long b=a;//自动类型转换
        int c=(int)b;//强制类型转换

        long d=5;//自动类型转换
        double e=5;//自动类型转换

        long f=10000000000L;
        int g=(int)f;
        System.out.println(g);//1410065408,强制类型转换可能溢出
        double h=25.678;
        int i=(int)h;
        System.out.println(i);//25,强制类型转换可能丢失精度

两点规则

//演示两点规则
        //1.整数直接变量可以直接赋值给byte、char、short,但不能超出范围
        //2.byte、short、char型数据参与运算时,先一律自动转换为int类型在计算
        byte b1=5;
        byte b2=6;
        byte b3=(byte) (b1+b2);//因为计算所以b1和b2都转换成了int类型,所以要强制转换

        System.out.println(2+2);//4
        System.out.println('2'+'2');//100
        System.out.println(2+'2');//52
        System.out.println('2');//2,因为没有运算,所以输出字符2

        int a='a';
        System.out.println(a);//97,查看字符对应的码
        char b=97;
        System.out.println(b);//a,查看码对应的字符

 

posted @ 2023-08-01 20:46  tian0000000  阅读(534)  评论(0)    收藏  举报