如何将 Java int
转换为String
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-int-to-string
在 Java 中,我们可以通过两种方式将int
转换为字符串:
通过使用 String.valueOf() 方法
通过使用 Integer.toString() 方法
也可以使用一些替代方法,如String.format()
方法、字符串连接运算符等。
1.通过使用String.valueOf()
方法
()方法的值是字符串类的一部分。这是一个静态方法,它将 int 值转换为 String 值。
例 1:
这里,方法中传递的 int 值被转换成一个字符串。
public class Main
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = String.valueOf(n);
System.out.println("The string value is " +s);
}
}
int 值为 500 字符串值为 500
2.通过使用Integer.toString()
方法
toString() 方法是整数类的一部分。这是一个静态方法,也可以用来将 int 值转换为字符串。
例 2:
这里,在toString()
方法中传递一个 int 值以获得一个String
值。
public class Main
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = Integer.toString(n);
System.out.println("The string value is " +s);
}
}
int 值为 500 字符串值为 500
3.通过使用String.format()
方法
format() 方法是字符串类的一部分,用于格式化字符串中的给定参数。
例 3:
这里,在format()
方法中传递一个 int 值以获得一个String
值。
public class Studytonight
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = String.format("%d",n);
System.out.println("The string value is " +s);
}
}
int 值为 500 字符串值为 500
4.通过使用+
运算符(连接)
我们可以使用+
运算符将任意值连接成一个字符串。+
运算符在连接后返回一个String
对象。请看下面的例子。
例 4:
这里,一个int
值与一个 emty 字符串连接,将 int 转换为String
。
public class Studytonight
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = "" + n;
System.out.println("The string value is " +s);
}
}
int 值为 500 字符串值为 500