Hi, 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. kevin
Joined: Sep 29, 2000
The easiest is to just initialize the keywords variable to some temporary value, and then change it in your for loops.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Aug 24, 2001
I understand, but not. how do I initialize a whole array of strings?
Joined: Nov 06, 2000
You can do this at the beginning String keywords = null then in your loop/method keywords = new String[whatever]
Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Joined: Aug 03, 2001
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. ------------------ Ian Darwin, Author of Java Cookbook: Solutions and Examples for Java Developers
I've tried the String keywords = null and then keywords = new String[list.length], where list.length is the number of files in the directory. Now I am getting an error that says :java.lang.ArrayIndexOutOfBoundsException = 4, which is the number of files in the directory. What would cause this exception?
Joined: Jun 13, 2000
If you have 4 items in an array, the max index is 3. 0, 1, 2 and 3