You can append an integer to a string in Java using the +
operator. This operator performs string concatenation, combining the string and the integer into a single string.
Example:
String str = "The number is: ";
int num = 10;
String result = str + num;
System.out.println(result); // Output: The number is: 10
Explanation:
- The
+
operator concatenates the stringstr
with the integernum
. - Java automatically converts the integer
num
into its string representation before appending it to the stringstr
. - The resulting string
result
contains both the original string and the appended integer.
Alternative Methods:
-
String.valueOf()
: This method converts the integer to its string representation, which can then be concatenated with the string.String str = "The number is: "; int num = 10; String result = str + String.valueOf(num); System.out.println(result); // Output: The number is: 10
-
StringBuilder.append()
: This method allows you to append the integer to aStringBuilder
object, which can then be converted to a string.StringBuilder sb = new StringBuilder("The number is: "); int num = 10; sb.append(num); String result = sb.toString(); System.out.println(result); // Output: The number is: 10
Practical Insights:
- Using the
+
operator for string concatenation is generally the most straightforward approach. - For more complex string manipulation, consider using
StringBuilder
orStringBuffer
for better performance. - The
String.valueOf()
method is useful when you need to convert an integer to a string for other purposes.