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);
2 Answers 2
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;
Comments
There are two things to mention:
a) initialize your String:
String disp = "";
If you do not initialize
disp
, it isnull
and therefore may cause trouble. The compiler recognizes, thatdisp
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 viaInteger.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.
String disp;
toString disp = "";
or some default value