
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011541946/article/details/79976650
这篇我们来学习基本数据类型的包装类。什么是包装类呢?在Java中有八种基本数据类型(byte char short long int Boolean float double ), 基本数据类型的操作简单,没有像对象调用方法去操作便利,所以就产生了包装类。包装类是为了更好地去操作基本数据类型,例如把一个int类型的数据,通过包装类的方法,可以快速得到一个二进制的值。
1.基本数据类型和对应的包装类
除了int和char的包装类的名称需要特殊记住,其他六种类型直接和基本数据类型一样,首字母大写就可以。
2.Integer API方法查看
打开JAVA JDK API 1.6, 搜索integer打开,找到以下图片内容位置。
上面可以把一个Int数据类型转成成二进制,八进制,16进制,字符串,返回的数据类型都是字符串类型。
写代码来测试一下
package eclipse; public class Test_Integer { publicstaticvoid main(String[] args) { System.out.println(Integer.toBinaryString(68)); System.out.println(Integer.toOctalString(68)); System.out.println(Integer.toHexString(68)); } }
输出结果:
1000100
104
44
如果你怀疑这个输出结果,你可以在你电脑找到计算器,点击查看菜单,选择程序员类型,然后输入68,点击二进制,观察。
3. Integer 包装类的构造方法和常见方法
在学习和使用一个对象类之前,我们先学习它的构造函数。在API文档中,Integer只有两个构造函数:Integer(int value) 和 Integer(String str)
package eclipse; public class Test_Integer { public static void main(String[] args) { //1.构造方法1.参数本身是int基本数据类型,作用就是把int基本数据装换成Integer类 Integer ig1 = new Integer(100); System.out.println(ig1); //2.构造方法2,参数是字符串格式的数字,不能是字符 Integer ig2 = new Integer("200"); System.out.println(ig2); } }
运行输出: 100 200
4.Integer的常量
处理构造方法,有时候我们还会使用Integer里的常量,有两个常量,一个表示Int类型的最大值,一个表示最小值。
package eclipse; public class Test_Integer { public static void main(String[] args) { System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); } }
运行输出:
2147483647
-2147483648
5. 常见String和Int类型的相互转换
1)int转换成String
package eclipse; public class Test_Integer { public static void main(String[] args) { //方法1:和""进行拼接变成String类型 inti = 100; String s1 = i + ""; System.out.println(s1); // 打印100 //方法2,使用String类的 valueOf(inti)的方法 String s2 = String.valueOf(i); System.out.println(s2); //方法3,int先转换Integer然后利用toString方法转换 intc = 200; Integer ig = new Integer(c); String s3 = ig.toString(); System.out.println(s3); //方法4 利用Integer静态方法toString intd = 300; String s4 = Integer.toString(d); System.out.println(s4); } }
运行结果:
100
100
200
300
上面四种方法,前面两种推荐使用。
2)String转成int
package eclipse; public class Test_Integer { public static void main(String[] args) { // 方法1,String->Integer->int String s1 = "200"; Integer ig = new Integer(s1); intx = ig.intValue(); System.out.println(x); //方法2 parseInt()方法:将字符串参数作为有符号的十进制整数进行解析 String s2 = "300"; inty = Integer.parseInt(s2); System.out.println(y); } }
运行结果: 200 300