您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
【第6章:面向对象(高级)】_包装类
发布时间:2020-12-18 10:33:24编辑:雪饮阅读()
Number类对其下属子类如integer、float等提供了装箱与拆箱功能
装箱类似于向上转型,拆箱类似于向下转型
public class Hello{
public static void main(String args[]){
int x=30;
//装箱
Integer x1=new Integer(x);
//拆箱
int x2=x1.intValue();
float f=30.3f;
//装箱
Float f2=new Float(f);
//拆箱
float f3=f2.floatValue();
}
}
D:\>javac Hello.java
D:\>java Hello
Jdk1.5之后还提供了自动装箱与自动拆箱
就是向上转型不需要new关键字,向下转型不用当前对象调用额外方法。
public class Hello{
public static void main(String args[]){
Integer i=30;//装箱
Float f=30.34f;//装箱
int x=i;//拆箱
float y=f;//拆箱
}
}
D:\>javac Hello.java
D:\>java Hello
Number类还提供了字符串转型
前提字符串必须是数字
public class Hello{
public static void main(String args[]){
String str1="220807";
String str2="34.34";
int x1=Integer.parseInt(str1);
float x2=Float.parseFloat(str2);
System.out.println(x1);
System.out.println(x2);
}
}
D:\>javac Hello.java
D:\>java Hello
220807
34.34
当字符串不是纯数字的时候转型就会抛出异常
public class Hello{
public static void main(String args[]){
String str1="22f807";
String str2="34.34";
int x1=Integer.parseInt(str1);
float x2=Float.parseFloat(str2);
System.out.println(x1);
System.out.println(x2);
}
}
D:\>javac Hello.java
D:\>java Hello
Exception in thread "main" java.lang.NumberFormatException: For input string: "22f807"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at Hello.main(Hello.java:5)
利用字符串转型就可以将主方法默认的args字符串数组进行以数字传参然后就可以直接在命令行中做运算如:
public class Hello{
public static void main(String args[]){
int x=Integer.parseInt(args[0]);
float f=Float.parseFloat(args[1]);
System.out.println("整数乘方:" + x + " * " + x + " = " + (x * x)) ;
System.out.println("小数乘方:" + f + " * " + f + " = " + (f * f)) ;
}
}
关键字词:java,面向对象,装箱,拆箱