The Handbook for Beginning Programmers with Examples in Java by Rex A. Barzee

The Handbook for Beginning Programmers with Examples in Java by Rex A. Barzee

Author:Rex A. Barzee [Barzee, Rex A.]
Language: eng
Format: azw3
Tags: COMPUTERS / Programming / General, COMPUTERS / Programming Languages / Java
Publisher: Maia LLC
Published: 2010-04-19T16:00:00+00:00


Variable Scope

The scope of a variable determines how long that variable exists and where it can be used. Within a Java program, there are several categories of scope including: local and class. A local variable is declared inside a method, exists for as long as its containing method is executing, and can be used within its containing method only. A class variable is declared outside all methods with the keyword static, exists for as long as its containing file is loaded in the computer’s memory, and can be used within all methods in its containing file. Parameters are local variables because they are declared within a method, specifically within a method’s header.

Java Variable Scope

Local Class

Where to Declare Inside a method Outside all methods, with the keyword static

Owner The method where the variable is declared The class where the variable is declared

Lifetime Only as long as its containing method is executing As long as its containing class file is loaded in the computer’s memory

Where Usable Only inside the method where it is declared In all methods in its containing class

Because local variables are visible only within the method where they are declared, you can declare two variables with the same name as long as they are declared in different methods. In the example code below there are two methods each with a local variable named length and a local variable named area. The variables are entirely separate and do not conflict in any way because the scope of each variable is within the method where it is declared.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.