In Java, what exactly constitutes as "initializing a local variable"? -


says that I have a piece of code in the local method

  int a = 5, b;   

and then start some code indirectly, such as

  if (true) b = 5; // legal if (someBool) b = 10; And b = 7; // Legal if (false) B = 5; // Invalid   

Invalid though B will always be started

  if (a & gt; 10) b = 4; If (a & lt; = 10) b = 4;   

My question is whether a local variable can be legally considered "start" in all precise conditions?

can be considered to be a local variable "if the compiler can easily assume that every Possible code path will lead through a path where the price has been set. "

  • Always (always) can always be set to run.
  • If (wrong) can not be run at any time
  • to run at least one branch if / or , you have to assign the variable to each branch if you want it to start. if / else if /.../ else
  • The switch statement will probably suppress the case s, or default , so if you specify the variable in all these places May include, is guaranteed to be launched.

    The Java compiler does not bother checking all the possible values ​​of each variable at different points in the method when determining this, because those variables variable - they change However, if the value can be assumed as stable , then it can safely assume that they will not make changes.

    For example, the compiler does not care if you specify a variable and never change it in your code:

      Bully Val = true; If (val) {b = 5; }   

    With the help of debuggers and things you have chosen to change the value of the value on-the-fly, so that any compiler assumptions are not here . However, if you are doing tax val continuously , with the declared last and a continuous or literal value, it is actually compiler Will behave the same as you use the value in the code.

      last boolean val = true; If (val) {// as if you had said that if (true) `B = 5; }   

    Such constants can be chained, as well, and the compiler will now have to simplify them for their continued values ​​rather than maintaining the expressions and operators:

      last int five = 5; Last four four = five - 1; // equals `4 = 5 - 1`, or 'four = 4' is the last boolean value = 5 & gt; Four; If (wal) {// `(5> 4) equals` `, or` (if true) `b = 5; }   

    To read more, check out. (Radioop the hat tip to find the right section.)

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -