Not sure if this has been done before, but I couldn't find one with Google or searching here, so thought I'd recreate it.
The Problem
Variable abcd has may not have been initialized
The Scenario
Code Java:
Why the error occurs
In the code above, it is intuitively obvious that someVariable will be initialized. However, because Java will not hard-code that, the compiler does not have the same intuition. Suppose you modified the if-statement in the above example to use the condition "1 == 2", making the new program:
What is the compiler suppose to print out?Code Java:
The Solution
Initialize your variable to some arbitrary value, or use else statements. Any statement that will always be called, no matter the conditions of the program. Two possible fixes for the example program above would be:
orCode Java:
Code Java:String someVariable; if(1 == 2) //This could be a while-loop, for-loop, switch statement, etc. { someVariable = "Butterflies"; //If true, set the variable here }else //If thats not true, go here. The variable will always be initialized. { someVariable = "Ladybugs"; } System.out.println(someVariable); //No error!
Code for linking here
Code :[url=http://www.javaprogrammingforums.com/java-code-snippets-tutorials/12025-initializing-variables.html]Initalizing Variables by TJStretch[/url]
