Sunday, 15 January 2017

The Scope And Lifetime Of Variables


                                             
The scope and lifetime of variables


 All of the variables that have been used are declared in the main ()
method, However java allows the variables to be declared in any block. The block defines a scope.

In Java , there are 2 major scopes , first is defined by the class and those defined by the method. The class scope has several unique properties and attributes that do not apply to scope defined by the method.

The scope defined by the method begins with its opening curly braces . If a method has parameters , they too are included within the methods scope.

The variables declared inside the scope are not visible , i.e accessible to the code that is defined outside the scope. Thus ,when you declare a variable within a scope , you are localizing that variable and protecting it from unauthorized access and modification.

The scopes can also be nested. Ex- each time you create a block of code , you are creating a new , nested scope. When this occurs , the outer scope encloses the inner scope . This means that the objects declared in the outer scope will be visible in the inner scope but vice-versa is not possible.

The variables are created when their scope is entered and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope.

The variables declared within a method will not hold their values between calls to that method. Also a variable declared within a block will loose its value when the block is left , thus the lifetime of a variable is confined to its scope.

If a variable declaration includes an initializer , then that variable will be reinitialized each time the block in which it is declared is entered. 

No comments:

Post a Comment

Video of the Day

Contact us

Name

Email *

Message *