I'm testing a piece of code

public class test { public static void main(String[] args) { String[] strArray = {"111", "222", "333", "444", "555"}; String strTmp1 = null; for (int i = 0; i < strArray.length; i++){ String strTmp = strArray[i]; strTmp1 = strTmp1 + " " + strTmp; } System.out.println(strTmp1); } } 

at the exit

 null 111 222 333 444 555 

How to remove null

  • one
    Wrote a question and the answer came by itself. Null simply changes to "" - fill
  • 2
    Googling for self education such a thing as StringBuilder. Each + with lines creates a new line in memory, so in real life your code, to put it mildly, is not quite good. StringBuilder allows you to make strings avoiding this problem. - Andrei Kurulyov 5:56 pm

3 answers 3

Solving this problem through StringBuilder - allows you to avoid memory littering due to the addition of strings (when adding strings in memory, a new string is created each time). Therefore, any repeated addition of strings is best done using StringBuilder .

 public class test { public static void main(String[] args) { String[] strArray = {"111", "222", "333", "444", "555"}; StringBuilder strTmp = new StringBuilder(); for (int i = 0; i < strArray.length; i++){ strTmp.append(' '); strTmp.append(strArray[i]); } System.out.println(strTmp.toString()); } } 
  • Adding strings uses StringBuilder , at least with Java 7. But for a loop, it is still more efficient to use StringBuilder explicitly. - Alexey Ivanov

Weed out the zero option in the cycle

  strTmp1 = ((strTmp1 == null)?"":strTmp1 ) + " " + strTmp; 

When you first enter the cycle, you have strTmp1 = null, so this value appears, and + 1, + 2 and so on goes to it.

Or, as option 2, assign the first value of the array to strTmp1, and then loop from 1 to the end.

  • 2
    What are the cons? - nick_n_a
  • 2
    Apparently, for the fact that strTmp1 you can assign an empty string during the declaration and thereby greatly simplify the code. PS Personally, I did not put cons. On the contrary, put a plus. :-) - user194374

You can create an ArrayList and not suffer, as an option.

  • And how will ArrayList help in this case? - Alexey Ivanov
  • When deleting, it will not be assigned a 'null', and the first line in the array will simply be deleted. - Artem Zaichikov
  • Nobody deletes anything. The problem is that the string is initialized to null instead of "" , and using an ArrayList instead of an array will not save it. - Alexey Ivanov