I'm trying to create a String of an array {1, 2, 3, 4, 5, 6, 7} but I can't seem to get the right answer when I run it.
int [] arr = {1, 2, 3, 4, 5, 6, 7};
String s = " ";
for(int i = 0; i < arr.length; i++){
s = (arr[i] + ", ");
}
System.out.println(s);
The answer I get is 7 when I was actually hopping to get 1, 2, 3, 4, 5, 6, 7
Can someone please explain to me why this code below gives me the correct answer but when I use a string it doesn't and how I should correct my code above.
int [] arr = {1, 2, 3, 4, 5, 6, 7};
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + ", ");
}
Arrays.toString()?=with+=StringBuilderinstead. JavaStringobjects are immutable, and it's expensive to create and discard lots of intermediate copies;StringBuilderlets you add all the characters you need and then turn it into aString.