Java-包装类

涎涎原创约 881 字大约 3 分钟...JavaJava

116-Java-包装类.mdopen in new window

注意

本博文仅供学术研究和交流参考,严禁将其用于商业用途。如因违规使用产生的任何法律问题,使用者需自行负责。

  • Everything is object.
    • Java编程语言不把基本数据类型看作对象。Java 编程语言提供包装类来将基本数据类型看作对象。
    • 在功能上包装类能够完成数据类型之间(除boolean)的相互转换,尤其是基本数据类型和String类型的转换。
    • 包装类中包含了对应基本数据类型的值,封装了String和基本数据类型之间相互转换的方法,还有一些处理这些基本数据类型时非常有用的属性和方法。
  • 包装类简介
    • 基本数据类型不是对象层次结构的组成部分。有时需要像处理对象一样处理这些基本数据类型,可通过相应的“包装类”来将其“包装”。
数据类型封装类
booleanBoolean
byteByte
charCharacter
doubleDouble
floatFloat
intInteger
longLong
shortShort
  • 字符串与基本数据类型、包装类型转换图
  • 基本数据类型转换为包装类
int pInt = 500;
Integer wInt = new Integer(pInt);
  • 字符串转换为包装类
    • 字符串通过构造方法转换为包装类
String sInt = “500”;
Integer wInt = new Integer(sInt);
  • 字符串通过包装类的valueOf(String s)转换为包装类
String sInt = “500”;
Integer wInt = Integer.valueOf(sInt);

注意:字符串不能通过以上两种方式转换为Character

  • 包装类转换为基本数据类型
    • 包装类通过xxxValue()方法转换为基本数据类型
Integer wInt = new Integer(500);
int pInt = wInt.intValue();
  • 包装类转换为字符串
    • 包装类通过toString()方法转换为字符串
Integer  wInt = new Integer(500);
String sInt = wInt.toString();
  • 字符串转换为基本数据类型
    • 字符串通过parseXXX(String s)方法转换为基本数据类型
String sInt = “500”;
int pInt = Integer.parsetIInt(sInt);

  • 自动的装箱和自动拆箱
    • 在进行基本数据类型和对应的包装类转换时,系统将自动进行
    • JDK自从5.0版本后引入
    • 方便程序的编写

示例代码:

package 包装类;

public class Test1 {

	public static void main(String[] args) {

		/**
		 * 所有的包装类:
		 * 1.为了解决基本类型没有对象的问题,所以为8种基本类型各自量身定做了包装类
		 * 2.包装类一共有8个:
		 * 3.封装类提供了丰富的数据类型之间转换的方法
		 */
		Character c;
		Boolean b;
		Float f;
		Double d;
		
		Byte bt;
		Short s;
		Integer i;
		Long ong;
	}
}
package 包装类;

public class Test2 {

	public static void main(String[] args) {
		//需求:
		//1. int --- Integer
		int a = 100;
		Integer a2 = new Integer(a);
		
		Integer a3 = Integer.valueOf(a);
		
		//2.Integer ----- int
		Integer b = new Integer(123);//new Integer(123)是自动装箱:把int  123 自动装箱成Integer对象类型
		int b2 = b;//int b2 = b 是自动拆箱,把Integer对象b脱去外衣,还原成int类型
		int b3 = b.intValue();
		//3.String ----- int
		String s = new String("666");
		int s2 = Integer.parseInt(s);
		int s3 = new Integer(s);
		//4.String ----- Integer
		String ss = new String("888");
		Integer i = Integer.parseInt(ss);
		Integer ii = new Integer(ss);
		//5.int ---- String
		int p = 333;
		String y = new String(p + "");
		String yy = Integer.toString(p);
		//6.Integer ---- String
		Integer g = new Integer(10);
		String k = Integer.toString(g);
		String kk = g.toString();
		System.out.println(kk);//10
	}
}

分割线


相关信息

以上就是我关于 Java-包装类 知识点的整理与总结的全部内容,另附源码open in new window

上次编辑于:
贡献者: 涎涎
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.4