A2oz

How to Append an Integer in a String in Java?

Published in Java Programming 2 mins read

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 string str with the integer num.
  • Java automatically converts the integer num into its string representation before appending it to the string str.
  • 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 a StringBuilder 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 or StringBuffer for better performance.
  • The String.valueOf() method is useful when you need to convert an integer to a string for other purposes.

Related Articles