-1

This is what my method looks like

public int abc()
{
  int x;
  if(x > 100)
  {
    //Say ok
    return x;//Causes compiler error
  }

  //if something more, x = some number 

  return x;//Causes compiler error


}

I saw an answer at SO - Java: "Local variable may not have been initialized" not intelligent enough?

But, I am still not sure why this error happens. Its a compiler error and not a warning. So, the problem must be something more serious than "taking a safe route".

Community
  • 1
  • 1
FirstName LastName
  • 639
  • 2
  • 8
  • 21
  • Look at http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java – Swapnil Jan 20 '13 at 08:06
  • 1
    The compiler is not smart enough to solve for the condition. It will only check that all paths to where the variable is read contains an initial write. – nhahtdh Jan 20 '13 at 08:07
  • 1
    well even if if condition is true its not intializing anywhere – jmj Jan 20 '13 at 08:09
  • try 'int x = 100 ;' then have a look at the logic - all that is happening is x is being returned. Maybe you want to pass in x as parameter. – Keith John Hutchison Jan 27 '13 at 08:11

1 Answers1

5

Local variables must be initialized before they are accessed. This is why there is a compiler error.

You should must have an error at the if statement where it's first accessed.

jmj
  • 237,923
  • 42
  • 401
  • 438