数据类型及转换

数据类型

强类型语言

要求变量使用严格符合规定,所有变量必须定义后才能使用

弱类型语言

Java数据类型

基本类型

1、整型

byte 、short 、int 、long

2、浮点型

float 、 double

3、字符型

char

4、布尔型

boolean

名称占用字节默认值封装器类
byte(字节型)10Byte
short(短整型)20Short
int(整型)40Integer
long(长整型)80.0lLong
float(浮点型)40.0fFloat
double(双精度浮点型)80Double
char(字符型)2\u0000(空格)Character
boolean(布尔型)1falseBoolean
引用类型
  • 接口
  • 数组

例:

public static void main(String[] args) {
        float a=0.1f;(结果为0.1)
        float b=1.0/10;(结果为0.1)
        System.out.println(a==b);
    }

输出结果为flase

 public static void main(String[] args) {
        float a=4545456654f;
        float b=a+1;
        System.out.println(a==b);
    }

输出结果为true

float 有限 离散 舍入误差 大约 接近不等于

float和double对数据判断不准确有误差,尽量不用浮点数去比较,需要用一个新的java数学类**BigDecimal **

字符

        public static void main(String[] args) {
        char c1='A';
        char c2='中';
        System.out.println(c1);
        System.out.println((int)c1);//强转
        System.out.println(c2);
        System.out.println((int)c2);//强转
    }

输出结果

image-20210607143323296

所有字符的本质还是数字

编码Unicode表中:A=65,中=20013

转义字符
  • \t 制表符
  • \n 换行
            • 等等

简单底层

            String sa = new String("hello world");
            String sb = new String("hello world");
            System.out.println(sa==sb);

            String sc = "hello world";
            String sd = "hello world";
            System.out.println(sc==sd);

image-20210607145855925

布尔类型

boolean e=true;
            if (e==true){}//if(e){}同样意思

类型转换

java是最强类型语言,所以运算时需要类型转换

低--------------------------------------------------------->高

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

运算中不同数据类型的数据需要先转为同一类型后再进行运算

强制转换

            int i=128;
            byte b=(byte) i;//强转   内存溢出btye数据大小是从-128到127,内存溢出后循环从-128开始,
            System.out.println(i);
            System.out.println(b);

image-20210607154100262

自动转换(低转到高不需要强转)

            int o=128;
            double p= i;//自动转换
            System.out.println(o);
            System.out.println(p);

image-20210607154915776

注意点
  • 不能对布尔类型进行转换true和flase

  • 不能把对象类型转换为不相干的类型

  • 转换的时候可能存在内存溢出

  • 转换的时候还可能出现精度问题。例:如果将double类型的22.2转换为int类型最后输出的值为22

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值