1. 这是使用Integer包装类的拆箱和装箱:
public class test_03 {
//jdk5之前是手动装箱和拆箱:
//手动装箱: int->Integer
int n1=100;
Integer integer=new Integer(n1);
Integer integer1=Integer.valueOf(n1);
//手动拆箱: Integer->int
int i=integer.intValue();
//jdk5以后,就可以自动装箱和拆箱了
//自动装箱: int->Integer
//底层实际上使用的是valueOf()的手动装箱,可以Debug一下就知道使用的还是valueOf()方法
int n2=200;
Integer integer2=n2;
//自动拆箱 Integer->int
//底层实际使用的是intValue()的手动拆箱,可以Debug一下就知道使用的还是intValue()方法
int n3=integer2;
}
2. 其他包装类的用法与Integer包装类相似 ;
3. String类和包装类(Integer)之间的相互转换 :
public class test_04 {
public static void main(String[] args) {
//包装类(Integer)->String
Integer i=100; //自动装箱
//方式1:
String str1=i+"";
//方式2:
String str2=i.toString();
//方式3:
String str3=String.valueOf(i);
//String->包装类(Integer)
String str4="1234";
//方式1:
Integer i2=Integer.parseInt(str4); //使用到自动装箱,因为parseInt返回的是int类型
//方式2:
Integer i3= Integer.valueOf(str4);
}
}
4. 几种常用的包装类方法 :
public class test_05 {
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
System.out.println(Character.isDigit('a'));
System.out.println(Character.isLetter('a'));
System.out.println(Character.isUpperCase('a'));
System.out.println(Character.isLowerCase('a'));
System.out.println(Character.isWhitespace('a'));
System.out.println(Character.toUpperCase('a'));
System.out.println(Character.toLowerCase('a'));
}
}
5. Integer 实例 :
public class test_06 {
public static void main(String[] args) {
//如果是自动装箱,还是需要看一下源码,源码找到valueOf方法,发现如果数字在 -128~127 范围内,则返回是同一个对象
//所以为True
Integer m=1;
Integer n=1;
System.out.println(m==n);
//但是如果不在 -128~127 之间,则返回的是 new Integer(i),创建的新对象所以为False
Integer x=128;
Integer y=128;
System.out.println(x==y);
}
}
以下就是Integer源码 :
6. 判断是否相等 :
public class test_07 {
public static void main(String[] args) {
//由于int是基本数据类型,所以==判断的是值是否相等
Integer i1=127;
int i2=127;
System.out.println(i1==i2); //true
//由于int是基本数据类型,所以==判断的是值是否相等
Integer i3=128;
int i4=128;
System.out.println(i3==i4); //true
}
}