基本数据类型转换和 String类型的转换

一、基本数据类型转换

1.1 自动类型转换

当Java程序在进行赋值或运算时,精度小的类型自动转换为精度大的数据类型,这个就是 自动类型转换

char - int - long - float - double

byte - short - int - long - float- double

int a = ‘c‘;	//ok
double d = 80;	//ok

1.2 自动类型转换注意和细节

  1. 有多种类型的数据混合运算时,系统首先自动将所有数据转换成容量最大的那种数据类型,然后再进行计算。
  2. 当我们把精度(容量)打的数据类型赋值给精度(容量)小的数据类型时,就会报错,反之就会进行自动类型转换。
  3. (byte, short) 和 char 之间不会相互自动转换,可以计算,不过首先要转换为int类型
  4. boolean 不参与转换
  5. 自动提升原则:表达式结果的类型自动提升为 操作数中最大的类型

1.3 强制类型转换

自动类型转换的逆过程,将容量大的数据类型转为容量小的数据类型。使用时要加上强制类型转换符() , 但可能造成精度降低或溢出,格外要注意

int i = (int)1.9;
System.out.println(i);

int j = 100;
byte b1 = (byte)j;
System.out.println(b1);

1.4 强制类型转换细节说明

  1. 当进行数据的大小从 大 ---> 小,就需要使用到强制转换

  2. 强转符号只针对于最近的操作数有效,往往会使用小括号提升优先级

    //int x = (int)10 * 3.5 + 6 *1.5;
    int y = (int)(10 * 3.5 + 6 *1.5);
    System.out.println(y);
    
  3. char 类型可以保存 int的常量值,但不能保存int的变量值,需要强转

    char c1 = 100;	//ok
    int m = 100;	//ok
    char c2 = m;	//错误
    char c3 = (char)m;	//ok
    System.out.println(c3);	//100对应的字符 d
    
  4. byte和 short,char类型在进行运算时,当做 int类型处理。

二、基本数据类型和 String类型的转换

2.1介绍和使用

我们经常需要将基本数据类型转成 String类型,或者将 String类型转成基本数据类型

  • 基本类型转 String类型

    语法:将基本类型的值 + "" 即可

int n1 = 100;
float n2 = 1.1f;
double n3 = 3.4;
boolean b1 = true;
String str1 = n1 + "";
String str2 = n2 + "";
String str3 = n3 + "";
String str4 = b1 = "";
System.out.println(str1 + " " + str2 + " " + str3 + " " + str4);
  • String 类型转基本数据类型

    语法:通过基本类型的包装类调用 parseXX 方法即可

Integer.parseInt("123");
Double.parseDouble("123.1");
Float.parseFloat("123.45");
Short.parseShort("12");
Long.parseLong("12345");
Boolean.paerseBoolean("true");
Byte.parseByte("12");

2.2注意事项

? 在将 String类型转成基本数据类型时,要确保 String类型能够转成有效的数据,比如 我们可以把 "123",转成一个整数,但是不能把 "hello" 转成一个整数。

? 如果格式不正确,就会 抛出异常,程序就会终止

基本数据类型转换和 String类型的转换

上一篇:CF808E Selling Souvenirs (已解决)


下一篇:深入浅出Map、WeakMap、Set、WeakSet