I'm declaring a "String keywords;" at the start of my program. Now I don't actually place anything into the array until I'm inside a couple for loops. When I compile, I get this error, "Variable keywords may not have been initialized." What do I do to fix this error. TIA.
String keywords = null
then in your loop/method
keywords = new String[whatever]
Originally posted by kevin schmidt:
I'm declaring a "String keywords;" at the start of my program. Now I don't actually place anything into the array until I'm inside a couple for loops. When I compile, I get this error, "Variable keywords may not have been initialized."
Cindy answered the "how to fix" but a bit more background may be helpful. The compiler is your friend when it gives you that message; the error message quoted above arises because there is at least one execution path (taking into account the flow of control during exception handling) that could possibly result in your trying to use the reference variable name "keywords" without having given it a value. Java is successfully preventing you from serious runtime errors. So you have to be a bit more careful when you take over responsibility and initialize the variables (BTW, I have looked into several complaints of people saying "the compiler is wrong" about these, but in every case, the compiler was correct).
As has been noted, the simplest way, if you must declare the variable in one place and assign to it in another, is to initialize it to "null" (the same rules apply to primitive types; initialize them to zero if numeric or false if boolean).
One thing further: variables declared as fields in a class are automatically assigned to the three values I listed, but this does not mean you should move local variables out to fields as one person once tried to convince me Just initialize the local variables and the compiler will be happy.
Author of Java Cookbook: Solutions and Examples for Java Developers