how to convert int to string java

how to convert int to string java

To convert an int to a String in Java, you can use the String class's constructor or the valueOf method.

Here is an example of how you can use the String class's constructor to convert an int to a String in Java:

refer to:‮l‬autturi.com
int i = 42;
String s = new String(i);

This code defines an int variable called i and assigns it the value 42, and then creates a String object called s using the String class's constructor and passing the int value as an argument.

You can also use the valueOf method of the String class to achieve the same result, like this:

int i = 42;
String s = String.valueOf(i);

This code defines an int variable called i and assigns it the value 42, and then creates a String object called s by calling the valueOf method of the String class and passing the int value as an argument.

Both of these approaches will create a String object with the same value as the int variable.

Note that in Java, the int primitive type and the String class are not the same thing. The int primitive type is a primitive data type that represents a 32-bit signed integer, while the String class is an object that represents a sequence of characters.

You can use the String class to manipulate text data in various ways, such as concatenating strings, searching for substrings, and formatting strings. However, the String class is generally slower than the int primitive type, so it is usually more efficient to use the int primitive type whenever possible.

Created Time:2017-11-01 12:05:15  Author:lautturi