-->

Thursday, February 13, 2014

What is the Scope of Variable in Java Programming?

What is the Scope of Variable in Java Programming?

In Java Programming, an important thing that you must know about variable is their scope. Scope generally refers to the program-region within which a variable is accessible. The board rule is: a variable is accessible with in the set of braces it is declared in e.g.

{
int a ;
:  /* a would be accessible as long as its block (a block is marked with a pair of matching brace) is not closed. Variable a is said to have block scope*/
}

Constants

Often in a program you want to give a name to a constant value. For example you might have fixed tax rate of 0.030 for goods and tax rate of 0.020 for services. These are constants, because their value is not going to change when the program is executed. It is convenient to given these constant a name.

This can be done as follows:

final double TAXRATE = 0.25;
The keyword final makes a variable as constant i.e. whose value cannot be changed during program execution.

Consider the following program that declare and uses two constants.

class calculateTax {
:  {
            final double GOODS_TAX =0.030 ;  
            final double SERVICE_TAX = 0.020 ;
                         …………
         }
     }

The reserved word final tells the compiler that the value will not change in the program. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of language).      

Once declared constants, their value cannot be modified e.g.; after declaring constant GOODS_TAX, if you issue a statement like:

GOODS_TAX =0.050 ;  //error
It will cause an error, as the value of constants cannot be modified.

Advantage of Constants

They make your program easier to read and check for correctness.
If a constant needs to be changed (for instance a new tax law changes the rates) all you need to do is change the declaration. You don’t have to search through your program for every occurrence of a specific number.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved