基本数据类型、包装类、String之间的转换

清疚 2022-06-04 00:48 304阅读 0赞

package 包装类;

import org.junit.Test;

/**
*8种基本数据类型对应一个类,此类即为包装类
* 基本数据类型、包装类、String之间的转换
* 1.基本数据类型转成包装类(装箱):
* ->通过构造器 :Integer i = new Integer(11)
* ->通过字符串参数:Float f = new Float(“12.1f”)
* ->自动装箱
* 2.基本数据类型转换成String类
* ->String类的:String.valueOf(基本数据类型);
* ->2.1+” “
* 3.包装类转换成基本数据类型(拆箱):
* ->调用包装类的方法:xxxValue()
* ->自动拆箱
* 4.包装类转换成String类
* ->包装类对象的toString方法
* ->调用包装类的toString(形参)
* 5.String类转换成基本数据类型
* ->调用相应包装类:parseXxx(String)静态方法
* ->通过包装类的构造器:Integer i = new Integer(11)
* 6.String类转换成包装类
* ->通过字符串参数:Float f = new Float(“12.1f”)
*/

public class TestWrapper {

//基本数据类型和包装类之间的转换
@Test//单元测试
public void test1(){
int i = 10;//基本数据类型
float f = 10.1f;
Integer i1 = new Integer(i);//包装类
Float f1 = new Float(f);
String str = “123”;//字符串
//1.基本数据类型转成包装类(装箱):
Float f2 = new Float(1.0);//参数可以是包装类对应的基本数据类型
Float f3 = new Float(“1.0”);//也可以是字符串类型,但其实体(其值)必须是对应的基本数据类型
System.out.println(“基本数据类型转成包装类:”+f2);
System.out.println(“基本数据类型转成包装类:”+f3);
//2.基本数据类型转换成String类
String str1 = String.valueOf(f);
String str2 = f+””;
System.out.println(“基本数据类型转换成String:”+str1);
System.out.println(“基本数据类型转换成String:”+str2);
//3.包装类转换成基本数据类型(拆箱):
int i2 = i1.intValue();
int i3 = i1;//自动拆箱
System.out.println(“包装类转换成基本数据类型”+i2);
System.out.println(“包装类转换成基本数据类型”+i3);
//4.包装类转换成String类
String str3 = f1.toString();
String str4 = Float.toString(f1);
System.out.println(“包装类转换成String类”+str3);
System.out.println(“包装类转换成String类”+str4);
//5.String类转换成基本数据类型
int i4 = Integer.parseInt(str);
int i5 = Integer.valueOf(str);
System.out.println(“String类转换成基本数据类型”+i4);
System.out.println(“String类转换成基本数据类型”+i5);
//6.String类转换成包装类
Integer i6 = new Integer(str);
System.out.println(“String类转换成包装类”+i6);
}

}

  1. public class Learn4 {
  2. public static void main(String[] args) {
  3. int a = 10;
  4. Integer integer = new Integer(a);
  5. System.out.println(Integer.MAX_VALUE+1);
  6. System.out.println(Integer.MIN_VALUE-1);
  7. System.out.println(Long.MAX_VALUE);
  8. Integer integer1 = 10;//自动装箱
  9. int num = new Integer(10);//自动拆箱
  10. Object[] obj = new Object[10];
  11. obj[0] = new Learn4();
  12. obj[1] = 10;
  13. obj[2] = true;
  14. obj[3] = 0.0;
  15. obj[4] = "呵呵哒~";
  16. int num1 = (Integer)obj[1];
  17. System.out.println(num);
  18. String str= "110";
  19. Integer integer2 = new Integer(str);
  20. System.out.println(integer2+1);
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,304人围观)

还没有评论,来说两句吧...

相关阅读