1

I am writing a code which tends to reverse a string as follows:

public class Main {
  public static void main(String[] args) {
    String str1;
    str1 = "This text is waited to be reversed.";
    char letters[];

    for(int i = str1.length() - 1; i >= 0; i--) {
      System.out.print(letters[i]);
    }
 }
}

But at run-time, system shows that

"Main.java:9: error: variable letters might not have been initialized
      System.out.print(letters[i]);
                       ^
1 error"

I cannot get this point. Can anyone explain it for me? Thank U very much!

  • 2
    Not at runtime, at compile time. But you've *definitely* not assigned a value to `letters`: you don't write `letters =` anywhere in this code before you try to use it. – Andy Turner Oct 20 '17 at 08:08
  • You mean that when I initiate letters[ ], I should assign value to it, or set boundary for this kind of array? But I want to set an array which store value of reversed string. So is there anyway to do that? – viet.nguyenhoang01 Oct 20 '17 at 08:50

1 Answers1

4

Writing

char letters[];

or more commonly

char[] letters;

doesn't initialise the variable, i.e. no =

From your use I suspect you intended

char[] letters = str1.toCharArray();

However the array itself isn't needed. You can just use str1

String str1 = "This text is waited to be reversed.";

for(int i = str1.length() - 1; i >= 0; i--) {
     System.out.print(str1.charAt(i));
}

a shorter way to write this is

System.out.println(new StringBuilder(str1).reverse());

But at run-time

"Run time" has a specific meaning which is; when I run the program after it has been compiled.

"Compile time" error is an error detected by the compiler, without actually running the program.

I assume you meant; when I try to run the program in my IDE.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thank U so much. You way is much better and efficient. But, I am trying to learn Java and do not let me depend too much on prebuild API. I want to reverse the string in "basic, traditional" way. Follow my method, can U give me some ways to do this? – viet.nguyenhoang01 Oct 20 '17 at 08:52
  • @viet.nguyenhoang01 the first example I gave is the simplest. – Peter Lawrey Oct 20 '17 at 09:01