示例一:
/**
* 包装类
* 基本类型由8个,由于他们是以值的形式存在,没有继承
* 也不是引用类型,所以不继承自Object。
* 那么基本类型是不能参与面向对象开发的。
* 包装类的作用主要解决了基本类型不能参与面向对象开发
* 的问题。
*
* 其中6个表示数字的包装类全部继承自Number类
* Number类中定义了:
* int intValue()
* 将当前对象表示的数字已基本类型的int值返回
*
* double doubleValue()
* 将当前对象表示的数字已基本类型的double值返回
* ...6个数字类型的方法全有
*
* @author Administrator
*
*/
public class IntegerDemo {
public static void main(String[] args) {
//该对象表示小数1.2
Double doub = new Double(1.2);
double d = doub.doubleValue();
System.out.println(d);//1.2
//还可以转换为其他的基本类型数据,但可能丢失精度
int i = doub.intValue();
System.out.println(i);//1
}
}
实例二:
/**
* 数字包装类有两个常量,分别表示其对应的基本类型
* 数据的取值范围:
* MIN_VALUE
* MAX_VALUE
* @author Administrator
*
*/
public class IntegerDemo2 {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
System.out.println(max);
System.out.println(min);
}
}
示例三:
/**
* 包装类最常用的一个方法
* 数字包装类有一个静态方法:parseXXX()
* 可以将字符串转换为对应的基本类型
* @author Administrator
*
*/
public class IntegerDemo3 {
public static void main(String[] args) {
String intStr = "123";
/*
* 若想将字符串转换为对应的数字,前提是该字符串
* 描述的所有字符必须表示当前类型的数字才可以!
*/
int i = Integer.parseInt(intStr);
System.out.println(i+1);
double d = Double.parseDouble(intStr);
System.out.println(d);
}
}
示例四:
public class IntegerDemo4 {
public static void main(String[] args) {
dosome(1);
/*
* java自1.5之后推出了一个新的特性
* 自动拆装箱
* 有了这个特性后,我们在写程序的时候就不用特别
* 注意基本类型与对应的包装类互转的问题了。
* 但是这个不是JVM认可的。而是编译器认可的,原因
* 在于编译器将转换的代码帮我们补全后写入了字节码
* 文件中。
*/
/*
* 这里就用到了自动装箱特性
* 编译器在生成字节码文件时,将代码改为了:
* Integer inte = Integer.valueOf(1);
*/
Integer inte = 1;
/*
* 这里就用到了自动拆箱特性
* 编译器在生成字节码文件时,将代码改为了:
* int i = inte.intValue();
*/
int i = inte;
}
public static void dosome(Object o){
}
}
示例五:
/**
* 基本类型转换为包装类时建议使用
* 静态方法 valueOf()
* @author Administrator
*
*/
public class IntegerDemo5 {
public static void main(String[] args) {
/*
* valueOf在有些包装类中会重用对象
* 比如Integer,会缓存1字节的整数。-128到127之间
*/
Integer i1 = Integer.valueOf(1);
Integer i2 = Integer.valueOf(1);
System.out.println(i1==i2);
System.out.println(i1.equals(i2));
}
}