封装类

来源:互联网 发布:java数字转字符串 编辑:程序博客网 时间:2024/06/15 09:42

Integer 对应 int

Float 对应 float

Double 对应 double

Character 对应 char

Boolean 对应 bool

public class EncapsulationDemo {public static void main(String[] args) {int n1 = 100;//不是对象//Integer n2 = new Integer(100);//生成整型对象Integer n2 = new Integer("100");//Integer n2 = new Integer("abc");//抛出异常System.out.println(n2);System.out.println("---------------------");Float f = new Float("3.1415");System.out.println(f);System.out.println("---------------------");Boolean flag = new Boolean("ture");System.out.println(flag);}

输出的结果

100---------------------3.1415---------------------false

装箱与拆箱

装箱:把基本类型的值或者变量赋给一个封装类型的引用

Integer n = 100;

拆箱:把封装类的对象赋给基本类型的变量

int num = new Integer(100);


基本类型转换成String类型

public class Test {public static void main(String[] args) {//从基本数据类型转换为String类型int num = 100;String s = String.valueOf(num);System.out.println(s);float f = 3.1415f;double d = 23.456;long l = 123456789;boolean flag = true;//s = (String)num;//错误s = String.valueOf(f);System.out.println(s);s = String.valueOf(d);System.out.println(s);s = String.valueOf(l);System.out.println(s);s = String.valueOf(flag);System.out.println(s);Integer n = new Integer("100000");s = String.valueOf(n);//自动拆箱System.out.println(s);}}

输出结果

3.141523.456123456789true100000

//string类型转换成基本数据类型String s2 = "123";int i = Integer.parseInt(s2);System.out.println(i);String s3 = "123.023";double d2 = Double.parseDouble(s3);System.out.println(d2);


补充

Integer方法

<span style="white-space:pre"></span>int maxInt = Integer.MAX_VALUE; //int类型的最小值int minInt = Integer.MIN_VALUE;//int类型的最大值String string = Integer.toString(10);//获取数字的十进制字符串String binaryString = Integer.toBinaryString(10);//将十进制数转换为二进制,返回结果为String类型String octalString = Integer.toOctalString(10);//将十进制数转换为八进制,返回结果为String类型String hexString = Integer.toHexString(10);//将十进制数转换为十六进制,返回结果为String类型Integer number = new Integer(10);int value = number.intValue();//返回Integer对象的int型Integer strInteger = Integer.valueOf("10");//返回指定String值的Integer对象int intValue = Integer.parseInt("100");//将字符串类型的整数转换为int类型的数据






0 0
原创粉丝点击