nick5454
asked on
getting passed error:might not have bee initialized
When I initialize a variable inside a block but you that variable in another block it gives me the following error
error: might not have been initialized
how do I get around this at compile time?
thanks
Nick
error: might not have been initialized
how do I get around this at compile time?
thanks
Nick
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
what? return a String in a void method?
I am sorry; forgot to take out "return", while doing copy /paste.
public void test(){
String s;
try{
s="blah";
System.out.println(s);
}catch (Exception e){}
}
public void test(){
String s;
try{
s="blah";
System.out.println(s);
}catch (Exception e){}
}
wrt bobbit31's post: If it's a native type, it will always be initialized to a default value (false for booleans, zero for integers, etc), and you won't even see this error.
Otherwise, setting it to null will work fine, just doublecheck your logic to make sure it does get initialized with the right values when you use it...
- Eugene
Otherwise, setting it to null will work fine, just doublecheck your logic to make sure it does get initialized with the right values when you use it...
- Eugene
easy to do ;-)
ASKER
not really sure who to give this one to, thier all great including the convo started. If EE could split them that would be nice also
1. When method returns void.
for ex.
public void test(){
String s;
try{
s="blah";
System.out.println(s);
}catch (Exception e){}
return s;
}
This will compile without a problem.
2. When method returns a Type.
public String test(){
String s;
try{
s="blah";
System.out.println(s);
}catch (Exception e){}
return s;
}
Compiler will issue error "variable s might not have initialzed return s".
So initialze your local variable , if you are returning that variable from the method.