JAVATM- The Beginnings

Local Variables

Variables declared inside a particular scope are called local variables. They exist  from the point of declaration to termination of the enclosing scope.

Section 1 - Variables Local to Methods

Variables can be declared inside the scope of a method. All variables we have declared so far have been local to the main method.

The variable sum below is local to method sumAndPrint. During its declaration, the Java compiler allocates four bytes to store its int value. Variable sum comes into existence and is said to be “in scope”. It can be utilized until the method’s scope terminates at the closed curly brace, where the compiler reclaims the four bytes of memory. At this point, sum no longer exists and is said to have “gone out of scope”.

 

When the main method attempts to print variable sum after it has gone out of scope, a compilation error occurs.

The lifetime of a variable refers to the time it takes to execute the statements in switch the variable is in scope. The lifetime of variable sum is the execution time of its declaration statement, the println statement, and the close curly brace.

A local variable and a method’s parameter cannot share the same identifier.

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.



Back to ralphlecessi.com