Broad Network


Basics of Java Variable Scope

Java Just After the Basics - Part 2

Forward: In this part of the series I briefly explain what is known as scope in Java.

By: Chrysanthus Date Published: 2 Sep 2012

Introduction

This is part 2 of my series, Java Just After the Basics. In this part of the series I briefly explain what is known as scope in Java. A block is a set of statements enclosed in curly brackets, which are { and }. The question here is: if a variable is defined outside a block, will it be seen in the block? On the other hand, if it is defined inside the block, will it be seen outside the block? Blocks do not occur arbitrarily in code. There are certain constructs that have blocks.  The following constructs have blocks: if, while, for, and method. You have seen all of these constructs.

For the rest of this tutorial, we look at the if, for and method constructs and how variable scope is applied to them. Remember, in Java coding goes inside a class construct.

The if Construct and Variable Scope
Read and try the following code (program):

class IfConstruct
    {
        public static void main(String[] args)
            {
                int myInt = 40;

                if (25 == 25)
                    {
                        System.out.println(myInt);
                        int herInt = 50;
                    }
        
                //System.out.println(herInt);
            }
    }

The if-condition is “if 25 is equal to 25”. Now this condition will always return true, and so the if-block will always be executed. Outside the if-block, the variable, myInt is declared and assigned the value, 40. Inside the if-block there is a statement to print (display) myInt. This variable was declared outside the if-block; if it is seen inside the block, it will be printed. If you tried the code you would have noticed that the value of myInt was printed.

Now, inside the block, a new variable, herInt was defined and had a value assigned to it. Outside the block, there is a comment. This comment is actually a statement preceded by the comment denotation, //. Because of this preceding sign, the statement is not executed. If you remove the comment denotation and re-try the code, the following explanation will follow:

The herInt variable is declared inside the if-block. Now, if it is seen outside the block, then the “last” statement (without the comment denotation) would print its value. Remove the // symbol and try the code if you have not already done so, and note that the last print statement would not work (the program will not even be executed), and you would receive an error message or error messages at compile time.

The Method Construct and Variable Scope
In the following program, there are two methods in a class; the variables and test (print) statement have been written in a similar way to the above. The method of interest has a print statement and a declaration statement. The second method calls the first method and has a print statement, which is initially a comment. The main method in the main class just calls the second method in the class of interest. The main class and its method are not important in this program.

class Exampl
    {
        int myInt = 40;

        void myFn()
            {
                System.out.println(myInt);
                int herInt = 50;
            }

        //int anInt = herInt;

        void yourFn()
            {
                myFn();
                //System.out.println(anInt);
            }
    }

class MainClass
    {
        public static void main(String[] args)
            {
                Exampl anObject = new Exampl();
                anObject.yourFn();
            }
    }

Now, the initialization variables are properties. There is one between the two methods that at the moment, is a comment. Read and try the code (program).

Note that the variable (myInt) declared outside the method block (but not in another block) is seen inside the method block.

Now, remove the comment denotation from the statement in-between the methods and remove that of the print line of the second method and try the code again; you will receive an error message at compile time, because the variable (herInt) declared inside a method block cannot be seen outside the method block in the assignment (initialization) statement just below the block.

The for Construct and Variable Scope
The following code has been written similar to the previous (everything is in the main method block); the variables and test (print) statements have been written in a similar way.

Read and try the following code:

class ForMain
    {
        public static void main(String[] args)
            {
                int myInt = 40;

                int i=0;
                for (i=0; i< 3; ++i)
                    {
                        System.out.println(myInt);
                        int herInt = 50;
                    }

                //System.out.println(herInt);
            }
    }

You should have tried the code. Note that the variable declared outside the for-block is seen inside the for-block. In this case the value of the variable is printed 3 times.

Now remove the comment denotation in the “last” line and try the code again; you will receive an error message at compile time, because a variable declared inside the for block cannot be seen outside the for-block.

Deduction
Blocks exist with different constructs. A variable declared outside blocks can be seen inside blocks. A variable declared inside a block cannot be seen outside the block.

Block Scope
A variable declared inside a block can be seen only inside that block. Such a variable is said to have block scope, or local scope.

A Block inside a Block
If a variable is declared inside a block, can it be seen inside a nested block? The answer is Yes and we have already come across this without being conscious of it. A variable can be seen inside a nested block and inside a nested, nested block.

Question: Can you have a variable declared outside a nested block and another declared inside the nested block with the same names? Yes, you can. Under that condition, in the nested block scope, the variable in the nested block, takes precedence.

That is it for this part of the series. We stop here and continue in the next part.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message