0
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);

Samurai
3,7295 gold badges29 silver badges41 bronze badges
asked Jun 21, 2015 at 19:23
1
  • Change String disp; to String disp = ""; or some default value Commented Jun 21, 2015 at 19:24

2 Answers 2

3

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;
answered Jun 21, 2015 at 19:26
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Jun 21, 2015 at 19:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.