1、基本数据类型转String
语法:将基本数据类型的值+" ",即可。
package HackerDemo;
public class SecondDemo {
public static void main(String[] args){
int a =100 ;
char b = 'a';
float f = 3.14f;
double e = .78;
String s1 = a+"";
String s2 = b+"";
String s3 = f+"";
String s4 = e+"";
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
2、String类型转基本数据类型
语法:通过基本数据类型的包装调用parseXX方式即可。
int s1 = Integer.parseInt("123");
Boolean s2 = Boolean.parseBoolean("true");
float s3 = Float.parseFloat("7.90f");
double s4 = Double.parseDouble(".78");
Byte s5 = Byte.parseByte("30");
注意事项:
将String类型转为基本数据类型时,要确保String类型能够转成有效的数据,比如“123”可以转成整数,但不能把“hello”,转成整数。