This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
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?