• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 208
  • Last Modified:

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
0
nick5454
Asked:
nick5454
1 Solution
 
bobbit31Commented:
set it = to null;

String s = null;

try {
  s = "blah";
} catch (Exception e) {}

(if it's a native type, you will have to set a default value (ie, true/false for boolean) b/c you can't assign null)



0
 
allahabadCommented:
local variable is not initialized:
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.
0
 
warsqlCommented:
what? return a String in a void method?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
allahabadCommented:
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){}
           
   
  }
 
0
 
ykaganovCommented:
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
0
 
warsqlCommented:
easy to do ;-)
0
 
nick5454Author Commented:
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
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now