您的位置:首页 > 移动开发 > Android开发

Android 之路22---Java基础16

2017-12-30 15:55 465 查看

导读

1.包装类型与基本数据类型的比较

2.包装类及常用方法的简介

3.装箱与拆箱

4.基本类型与字符串的互相转化

5.补充

包装类型与基本数据类型的比较









包装类及常用方法的简介

































装箱与拆箱



package Warpped;

public class WarpTest {

public static void main(String[] args){
//装箱
//1.自动装箱
int t1=2;
Integer t2=t1;
//2.手动装箱
Integer t3=new Integer(t1);
Integer t4=new Integer("2");
//测试
System.out.println("t1="+t1);
System.out.println("t2="+t2);
System.out.println("t3="+t3);
System.out.println("t4="+t4);

//拆箱
//1.自动拆箱
int t5=t2;
//2.手动拆箱
int t6=t2.intValue();
System.out.println("t5="+t5);
System.out.println("t6="+t6);
}

}


输出结果

t1=2

t2=2

t3=2

t4=2

t5=2

t6=2

基本类型与字符串的互相转化

package Warpped;

public class WarpTest {

public static void main(String[] args){
//基本数据类型转换为字符串
int t1=2;
String t2=Integer.toString(t1);
//字符串转换为基本数据类型
//方法一:包装类的parse
int t3=Integer.parseInt(t2);
//方法二:包装类的valueOf,先将字符串转为包装类型,再通过自动拆箱转为基本类型
int t4=Integer.valueOf(t2);
//测试:
System.out.println("基本数据转字符 t2="+t2);
System.out.println("字符转基本数据方法一 t3="+t3);
System.out.println("字符转基本数据方法二 t4="+t4);
}

}


输出结果

基本数据转字符 t2=2

字符转基本数据方法一 t3=2

字符转基本数据方法二 t4=2

补充



⚠️包装类型的初始值均默认为null

package Warpped;

public class WarpTest {

public static void main(String[] args){
Integer one=new Integer(100);
Integer two=new Integer(100);
System.out.println("one与two进行比较:"+(one==two));
//因为one和two对应两块不同的空间
Integer three=100;
System.out.println("three与100进行比较:"+(three==100));
//three在进行比较时进行了自动拆箱
Integer four=100;
System.out.println("three与four进行比较:"+(three==four));
//见下图
Integer five=200;
System.out.println("five与200进行比较:"+(five==200));
//five在进行比较时进行了自动拆箱
Integer six=200;
System.out.println("five与six进行比较:"+(five==six));
//见下图
}

}


输出结果

one与two进行比较:false

three与100进行比较:true

three与four进行比较:true

five与200进行比较:true

five与six进行比较:false





⚠️ecplise显示编程行号的设置

偏好设置->General->Editors->Text Editors

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: