Java面向对象高级--包装类

本文详细介绍了Java中的包装类,包括其使用方式、自动装箱拆箱的过程,以及如何利用包装类将字符串转换为指定的数据类型。通过具体示例展示了基本数据类型与包装类之间的转换方法。

1、包装类的介绍



这八种包装类,继承的父类不全都相同。

数字:


public final class Float
  extends Number
  implements Comparable<Float>
________________________________________________________________________________________________________________________

2、包装类的说明





public class WrapperDemo01{
	public static void main(String args[]){
		int x = 30 ;		// 基本数据类型
		Integer i = new Integer(x) ;	// 装箱:将基本数据类型变为包装类
		int temp = i.intValue()	;	// 拆箱:将一个包装类变为基本数据类型
	}
};
再以小数为例:
public class WrapperDemo02{
	public static void main(String args[]){
		float f = 30.3f ;		// 基本数据类型
		Float x = new Float(f) ;	// 装箱:将基本数据类型变为包装类
		float y = x.floatValue()	;// 拆箱:将一个包装类变为基本数据类型
	}
};

public class WrapperDemo03{
	public static void main(String args[]){
		Integer i = 30 ;	// 自动装箱成Integer
		Float f = 30.3f ;	// 自动装箱成Float
		int x = i ;			// 自动拆箱为int
		float y = f ;		// 自动拆箱为float
	}
};

在包装类中、还有一个最大的特点:就是可以将字符串变为指定的数据类型。

3、包装类的应用


public class WrapperDemo04{
	public static void main(String args[]){
		String str1 = "30" ;	// 由数字组成的字符串
		String str2 = "30.3" ;	// 由数字组成的字符串
		int x = Integer.parseInt(str1) ;	// 将字符串变为int型
		float f = Float.parseFloat(str2) ;	// 将字符串变为float型
		System.out.println("整数乘方:" + x + " * " + x + " = " + (x * x)) ;
		System.out.println("小数乘方:" + f + " * " + f + " = " + (f * f)) ;
	}
};

public class WrapperDemo05{
	public static void main(String args[]){
		int x = Integer.parseInt(args[0]) ;	// 将字符串变为int型
		float f = Float.parseFloat(args[1]) ;	// 将字符串变为float型
		System.out.println("整数乘方:" + x + " * " + x + " = " + (x * x)) ;
		System.out.println("小数乘方:" + f + " * " + f + " = " + (f * f)) ;
	}
};

4、总结




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值