Java基础【基本数据类型包装类、int与String 之间的相互转换】

为什么会有基本类型包装类?

将基本类型数据类型封装成对象,这样的好处可以在对象中定义更多方法操作该数据。

包装类常用的操作就是用于基本数据类型与字符串之间的转换

问题:
int a=100; 为什么不能使用 String s = (String) a;
String s 是对象引用,a是基本数据类型,

基本数据类型 存放的就是数值
对象就是引用类型 对象变量存的是内存地址

所以不能强制转换


基本数据对应的包装类
byte Byte
short Short
int Integer [先学习这个 其他的后面用到在学习]
float Float
double Double
char Character
boolean Boolean


//1.Integer 构造方法
Integer (int value)
Integer (String s) //构造一个新分配的Integer对象,他表示指定的int值

int a =100;
Integer integer = new Integer(a);
String s = integer.toString();

//2.Integer 的静态属性
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);

//3.Integer 的其他方法(进制间转换)

Integer.toBinaryString(8); //1000 把int转换成二进制的字符串

Integer.toOctalsString (9); //11 把int转换成八进制的字符串

Integer.toHexString(17); // 11 吧int转换成十六进制的字符串

String 与 int 之间的转换

一、int转String

1.1 和 "" 进行拼接
int a = 100;
String s1 = a+"";

1.2 public static String valueOf(int i)
String s2 = String.valueOf(a);

1.3 int 转换成包装类 然后在使用toString()
Integer integer = new Integer (a);
String s3 = integer.toString(a);
1.4 public static String toString(int i)
String s4 = integer.toString(a);

对象.getClass() 打印对象在运行时的类型


二、String 转int
String str = "520"
2.1 String -- Integer -int
Integer int1= new Integer(str);
int value = int1.intValue();

2.2 public static int parseInt(String s)
int c = Integer.parseInt(str); //这个是经常使用的方法