JAVA不同数据类型的转换和运算符

目录

一,数据类型的转换

二,基本数据类型之间的转换

1.1,int转换为byte

 2.1,int转换为char类型

3.1,int和string类型的转换

4.1,boolean数据类型

5.1,int和double类型的转换


一,数据类型的转换

1.基本数据类型之间的转换
2.字符串与其它数据类型的转换
3.其它实用数据类型转换

二,基本数据类型之间的转换

1.1,int转换为byte

public static void main(String[] args) {
        int a = 20 ;
        byte b= (byte) a;//大类型转换为小类型,需要强制转换
        int c = b;//小类型转换为大类型,自动提升
    }

需要注意

public static void main(String[] args) {
        byte a = 127 ;
        byte b= 130;//此处编译不通过是因为超过了byte取值范围
        byte c = (byte) 130;//此处强制转换为byte类型
    }

byte类型的取值范围-128到127

public static void main(String[] args) {
      int a = 20;
      byte b = a;//此处编译不通过是因为20虽然是取值范围内,
                 // 但是a为int类型,仍然需要强制转换
        byte c = 10;
        byte d = 15;
        byte e = c + d;//此处编译不通过是因为计算机中数据的存取
                       // 是按4个字节进行的,c和d为int类型,需要强制转换
        byte f = (byte)(c + d);//编译通过
    }

 不过上述情况使用final时,可以不用强制类型转换,因为final修饰的变量,数值和类型都不能改变,叫做最终变量,byte仍然为byte类型。

public static void main(String[] args) {
        final byte c = 10;
        final byte d = 15;
        byte e = c + d;//编译通过

 2.1,int转换为char类型

java对char类型的数据在底层是按int类型来处理的,由于java采用unicode编码,char 在java中占2个字节,用2个字节(16位)来表示一个字符。

public static void main(String[] args) {
        char a ='g';
        int b = a;//小类型转换为大类型,自动提升
        int c = '龙';
        char d = 69;
        System.out.println(c);
        System.out.println(d);
    }

69被自动转换成unicode编码所对应的字符 ‘E’ ,字符  ‘龙’  被自动转换成unicode码 40857

3.1,int和string类型的转换

1,使用字符串的拼接方法

public static void main(String[] args) {
        int a = 20;
        String str1 = "" + a;
        System.out.println("str1:" + str1);
    }

运行结果

2, 使用String类的静态方法 valueOf

public static void main(String[] args) {
        int a = 20;
        String str1 =String.valueOf(a);
        System.out.println("str1:" + str1);
    }
}

3,使用Integer类中的toString()方法,int转为Integer后再转为String

public static void main(String[] args) {
        int num = 20;
        Integer a =new Integer(num);
        String str1 =a.toString();
        System.out.println("str1:" + str1);
    }

4,string转为int类型,使用Integer类中的parseInt()方法。

 public static void main(String[] args) {
        String str = "1000";
        int a = Integer.parseInt(str);
        System.out.println(a);
    }

4.1,boolean数据类型

不能和其他数据类型进行转换,会出错

 public static void main(String[] args) {
        boolean a = true;
        int b = (boolean) a;
    }

5.1,int和double类型的转换

 public static void main(String[] args) {
        int a =20;
        double b =(double) a;
        System.out.println(b);
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值