Showing posts with label Scope. Show all posts
Showing posts with label Scope. Show all posts

Monday, March 24, 2014

Variable scope and lifetime


The scope of a variable refers to how visible it is to different parts of the program. A variable which is declared inside of a method is said to have local scope - this means that it is visible only within that method. A variable which is declared at the top of a class is said to have class-level scope.

In the example below, a variable called username has been declared twice - each has a different scope. The one at the top has class-level scope and the one in the main method has local scope. The compiler will first attempt to reference the variable locally and if one cannot be found, it will look for one at class-level.

As a result, when the main method references the variable called username, it will be looking at the local declaration and therefore print "KiddThunda". When the variable called username is referenced from methodOne(), "Straven" is printed because it is referencing the variable at class-level.





In the next example, width and height variables are declared and assigned values in the initialiseValues() method. 



Because the width and height variables are local to the initialiseValues() method, they cannot be seen from the calculateArea() method - or any other method.

If you require access to a variable(s) from many methods, you can increase the scope of the variable to class-level, as below:


(In this case, because the variables are being called from static methods, the variables are declared with the static keyword - but this is just incidental and not particular to the discussion on scope.)

The scope of a variable has a direct affect on where it can be seen in the program. Additionally, the scope of a variable affects the lifetime of the variable.

Lifetime refers to the period of time that a variable stores a value before having it reset.

Consider the following method which is using the variable numberOfClicks to keep count of the number of clicks. Syntactically correct, however, the logic is incorrect. Each time the method is called, the numberOfClicks variable is being re-declared and set to zero before the variable is incremented. This results in the variable always having a value of 1. We can say that the numberOfClicks variable has a lifetime of 1 method call.



The correct logic is below:


The scope of numberOfClicks has been increased to class-level, therefore extending it's lifetime. Now, the variable is declared and initialised once. When the countClicks() method is called, numberOfClicks is actually incremented. The numberOfClicks variable now has the same lifetime as the object in which it is contained (Scope3Demo).

It is a common scenario that you declare variables locally and then realise that the scope and lifetime of some of them will need to be increased, as your project grows.

Variables may also have block scope - meaning, the are used within the block of a loop or conditional (if) block.

The loop counter in a for loop is a good example of this:


Notice that the loop counter (x) can be accessed within the loop block but not outside of it. We can say that x has a lifetime of the length of the loop.

In the example below, the error is occurring because the variable called message has block scope - that is, the variable has been declared within the conditional block and cannot be seen outside of that block.




We can increase the scope of message if we need to use it beyond the conditional block:


Monday, February 25, 2013

Variable Syntax

Every variable has a (data) type and an identifier.

Variable declaration syntax (single line):

Type identifier = value;

      or (assignment statement in 2nd line):

Type identifier;
identifier = value;

Naming variables
There are rules and conventions around how Java variables are named.

A Java variable name:
  • should begin with a lowercase letter
  • can contain numbers
  • can contain an underscore
  • must be less than 255 characters long
  • must not contain spaces
  • must not begin with a number
  • if the name consists of more than word, capitalize the first letter of each word

Case sensitive
All names in Java are case sensitive. This means that a variable named numberOfClicks is different to a variable named numberofclicks.


Variable Declaration

When we create a variable in our program, we are said to be ‘Declaring a variable’. Variables are declared in methods. Methods are named blocks of code which perform a particular task. Variables may also be declared in the body of a class - that is, within the class declaration, but not within the body of a method.




When we declare a variable, we are telling the program to remember a value. Of course, there are many different types of data so we need to select the most appropriate variable type to store that value in.


The statement below is a variable declaration for some String data called myPassword. The value it is storing is “secret’.


String myPassword = “secret”;





Assigning values - The assignment operator

When we assign a value to a variable, we use the assignment operator - the equals (=) character. 

The assignment operator takes the value on the right and assigns it to the operand on the left side to form an assignment expression.


In the example below, the value “GateKeeper99” has been assigned to the String variable called myUserName.


String myUsername = “GateKeeper99”;


The assignment operator is also used to change the value being stored by the variable, as follows:


int numberOfUsers = 100;
numberOfUsers = 101;


We are also able to declare a variable in one statement and assign a value to it, in another statement.

As follows:


int xCoordinate;
xCoordinate = 500;


This technique is often used where we need to increase the scope of a variable.


Variable scope
A variable may only be referenced from within the region where it is declared. This means that if a variable is declared within a method, it is only accessible from within that method. Also, you cannot reference a variable before it is declared. If a variable is declared in the class body, this variable can be accessed from all methods in the class.




Variable lifetime

Variable lifetime refers to the length of time that a variable stores a value. Depending on the scope, a variable may have a lifetime that lasts for the time it takes a single block of code to execute, or for the entirety of program execution (more on that later).

Sunday, June 3, 2012

Scope

A variable may only be referenced from within the region where it is declared.

"Variable Scope : Variable Scope « Language « Java Tutorial" ( http://bit.ly/KHplZ5 )