Nabil Mustafa
Nabil Mustafa

Reputation: 13

Java: How to Concatenate a string in a loop

String disp;
for(int i=0; i<31 ; i++)
disp = disp + Integer.toString(i);

JOptionPane.showMessageDialog(null, disp);

ERROR GIVEN:

Calendar.java:28: error: variable disp might not have been initialized JOptionPane.showMessageDialog(null, disp);

Upvotes: 0

Views: 4822

Answers (2)

Turing85
Turing85

Reputation: 20185

There are two things to mention:

  • a) initialize your String:

    String disp = ""; 
    

    If you do not initialize disp, it is null and therefore may cause trouble. The compiler recognizes, that disp is uninitialized and therefore does not compile the program.

  • b) you do not need Integer.toString(...):

    for(int i = 0; i < 31 ; ++i) {
        disp = disp + i;
    }
    

    All primitives can be automatically casted to a String. Therefore, you can skip the cast via Integer.toString(...)in this case.

Final note: you might want to use a StringBuilder to gain some performance. Look at Pshemo's or Eran's answer for details.

Upvotes: 0

Pshemo
Pshemo

Reputation: 124215

You should avoid concatenating result String in loop since it each iteration in has to create copy of old String with new part. Instead use StringBuilder and its append method.

StringBuilder disp = new StringBuilder();

for (int i = 0; i < 31; i++)
    disp.append(i);

JOptionPane.showMessageDialog(null, disp);

Anyway cause of your problem is that disp doesn't have any string assigned to it, so there is nothing to concatenate to. Also while concatenating to string you don't need to explicitly parse its elements to String, code responsible for that will be added by compiler. Try

String disp = "";//assign value to `disp`
for (int i = 0; i < 31; i++)
    disp = disp + i;

Upvotes: 3

Related Questions