java包装类_基本类型与字符串类型之间的相互转

java 包装类_基本类型与字符串类型之间的相互转

​ 基本类型与字符串类型之间的相互转换

基本类型->字符串(String)

​ 1.基本类型的值+"" 最简单的方法(工作中常用)
​ 2.包装类的静态方法toString(参数),不是Object类的toString() 重载
​ static String toString(int i) 返回一个表示指定整数的 String 对象。
​ 3.String类的静态方法valueOf(参数)
​ static String valueOf(int i) 返回 int 参数的字符串表示形式。

字符串(String)->基本类型

  • public static byte parseByte(String s):将字符串参数转换为对应的byte基本类型。
  • public static short parseShort(String s):将字符串参数转换为对应的short基本类型。
  • public static int parseInt(String s):将字符串参数转换为对应的int基本类型。
  • public static long parseLong(String s):将字符串参数转换为对应的long基本类型。
  • public static float parseFloat(String s):将字符串参数转换为对应的float基本类型。
  • public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。
  • public static boolean parseBoolean(String s):将字符串参数转换为对应的boolean基本类型。

​ 使用包装类的静态方法parseXXX(“字符串”);
​ Integer类: static int parseInt(String s)
​ Double类: static double parseDouble(String s)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.itheima.demo07Integer;

public class Demo03Integer {
public static void main(String[] args) {
//基本类型->字符串(String)
int i1 = 100;
String s1 = i1+"";
System.out.println(s1+200);//100200

String s2 = Integer.toString(100);
System.out.println(s2+200);//100200

String s3 = String.valueOf(100);
System.out.println(s3+200);//100200

//字符串(String)->基本类型
int i = Integer.parseInt(s1);
System.out.println(i-10);

int a = Integer.parseInt("a");//NumberFormatException
System.out.println(a);
}
}