Showing posts with label Variables. Show all posts
Showing posts with label Variables. 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:


Friday, September 20, 2013

Accumulator variables: Incrementing and decrementing

There is no actual such thing as an accumulator variable but it is a concept or rather a technique for using a normal variable to accumulate a value.

The following statement declares an int variable and assigns it a value of 0:

int num = 0;

if we then write another statement:

num = 10;

...what we have done is overwrite the value of num from 0 to 10.

But often, we want to increase the value of num with another number, rather than overwrite it's value.

In this case, we can use the add and (+=) operator, rather than the assignment operator (=):

int num = 0;
num += 10;
num += 3;

The value of num has accumulated a value of 13.

Consider the following example, which uses a for loop to accumulate a value:

int num = 0;
for (int x = 0 ; x < 10 ; x ++ ) {
   num += 10;
}

The loop runs 10 times and on each pass of the loop, num accumulates another value of 10. The end result is that num has a value of 100.

In the next example, we use the Java increment operator (++) to increase the value of num by 1:

int num = 0;
for (int x = 0 ; x < 10 ; x ++ ) {
   num ++;
}

You should also note that the loop counter itself makes use of the increment operator to add 1 to itself on each pass of the loop.

What about decrementing?

int num = 10;
num -= 5;
num -= 1;

Using the minus and (-=) operator, num now equals 4

and in a loop we might:

int num =10;
for (int x = 0 ; x < 10 ; x ++ ) {
   num --;
}

Using the decrement operator (--), num equals 0.

What about Strings?

Use the add and (+=) operator to append 1string to another:

String name = "Sabrina";
name += "Albright";


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).

What is a variable?


Variables are used to store values in a program. A value might be a name, a number, an address, and so on. These values can then be displayed or processed to create new information.

Think about a calculator. Each time you press a button, the calculator remembers what you have pressed. When you press the equals button, the calculator forms a mathematical equation using your series of key presses.

There are many types of values. Some values are made up of letters and numbers (such as an address) and some values are simply numbers. Each type of data can be stored in a program using a variable.

For instance, in a Java program, we could do the following:

String userName = “C2012000”;
String password = “monkey5000”;
String address = “30 Happy Place, Uptown”;
int numberOfLogins = 12;


The words String and int are types of Java variables - or data types.

Now we have 4 stored values that can be used again later in the program. Perhaps we need to print these values to the screen or perhaps we need to know where a letter must be mailed to. Perhaps we need to take an average of how many times a user has logged in over a particular time frame.

Alphanumeric & Numeric data.
Alphanumeric data is any collection of keyboard characters. It may contain letters, numbers & other special characters. Values such as these are stored in an variable that can hold alphanumeric values. This type of variable is called String.

String whatTheDogSaid = “Right on partner number 2!”;

A String may contain numbers, such as a house number in an address. But if we need to store a number so that we can do some kind of maths on that number, we need to use a variable type that can store numbers as numbers.

Numeric data are numbers. Generally speaking, data is considered numeric where it is being used for maths purposes - such as counting, adding, subtracting, and so on. Some numbers are whole numbers, such as the number of students on a bus. Some numbers contain a floating point, such as currency values, or body weight. For this reason, there is more than 1 type of variable that can hold numeric data. For instance, an int variable can store a whole number and a Double variable can store a floating point number.

int numOfStudentsOnBus = 22; 
double dogWeight = 12.2;

The number of students on a bus is going to be stored as a whole number, so we store it in a variable that can store whole numbers, such as int.

A number representing weight contains a floating point so we store this number in a variable type that can store floating point numbers such as double.

There are many data types in the Java language!

Here's a cat:


Sunday, May 27, 2012

What is a Constant? Final keyword

DOWNLOAD THE CODE: FinalValuePkg

We can store a value in a constant. Very similar to a variable except that a constant has a constant value. That is, the stored value is never changed as a result of processing.

Constants are used where a value should never be changed such as a maximum, minimum, number of hours in a day, days in a week, etc.

A constant begins with the keyword final. Just as with a variable, a type & identifier must be given.


The compiler will not allow any processing statements to change the values of these constants.


UML Class Diagram Notation
The UML Class Diagram notation for a constant (final) is as below:



CIRCLE_WIDTH and CIRCLE_HEIGHT are defined using uppercase and have each been assigned a value.

"Java Syntax: Declaring and Using Constants in Java" ( http://bit.ly/JmgF5S )

Here's a cat:


Friday, May 18, 2012

The 'static' keyword


Download the code


Static variables & methods are associated with the class rather than an instance of an object of that class.

Usually, the data contained within an object, belongs only to that instance.

If you want all instances of a class to share some data, use a static variable. A static variable belongs to the class, rather than an instance the class (object).

The example below uses a static variable to keep count of the number of Widget objects that have been created.

The Widget class contains a single static variable called _numberOfWidgets. No matter how many instances of Widget are created, there will be a single value associated with the _numberOfWidgets variable.

A static method is provided to set the value of _numberOfWidgets and a static method is provided to get the value of _numberOfWidgets. In this example, the constructor calls the set method and in turn, the set method increments the value.


In the TestWidgetClass below,  a number of Widget instances are created. Note that the call to the get_numberOfWidgets method is made by referencing the class directly, rather than by instance of the class.



And the output is:




"Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects)" ( http://bit.ly/KmbYd7 )

In a UML class diagram, Static variables & methods are represented with an underline.



Here's a cat to keep you calm:


Monday, March 19, 2012

Variables and Data Types

We use variables to store values in a program. Values can have be of different types - for example a value may be a String (any collection of keyboard characters) or a number such as an int.

Why would you want to store values? What kind of values?

Things like:

  • username
  • email address
  • age
  • URL
  • game stats
  • price


The format for declaring a variable is as follows:

Type identifier;

The format for assigning a value to a variable is as follows:

identifier = value;

The format for declaring a variable & assigning a value to it in one statement, is as follows:

Type identifier = value;

Here are some concrete examples:



http://www.functionx.com/java/Lesson02.htm

http://www.tutorialspoint.com/java/java_basic_datatypes.htm