What is Scope of Variables in Java - onlyxcodes

Thursday 29 June 2023

What is Scope of Variables in Java

Any programming language uses variables, which are categorized according to their range of use.


All Java learners will understand the scope of variables in this article. 


Additionally, comprehend what are variables in Java and how to declare them. 


scope of variables in java

first, see the fundamentals of Java variables.


What is a Variable in Java?

A variable in Java is a named storage area that keeps a value of a certain type. It is utilized to manipulate and save data while a program is being run.


How to Declare Variables?

In Java, you give a variable a name and a data type when you declare it. The type of values that can be kept in a variable such as integers, floating-point numbers, characters, or objects depends on the data type.


As an illustration, you may declare the integer variable "age" as follows:


int age;

This declares an integer-capable variable with the name "age" of type int. Using the assignment operator (=), you can give a variable a value after declaring it. 


For instance:


age = 25;

As an alternative, you can define and initialize a variable in one procedure, like in the following:


int age = 25;

Variables can be supplied to methods as arguments, utilized in expressions, and have their values changed while the program is executing.


Let's explore the Java variable scope.


Scope of variables in Java

The area of a Java program where a variable is accessible and usable is referred to as the variable's scope. The scope controls where and how long a variable exists while a program is being executed.


In Java, there are different kinds of variable scopes:


Local scope:


Local scope refers to variables defined inside a method, constructor, or block. They can only be accessed via that particular block or function. The variable is destroyed after the block or method execution is finished. 


Here's an illustration:


In this example, the method of the exampleMethod() has a declaration of the local variable x.


In the main function, we call the exampleMethod() method to print the value of the x variable using an object of the Test class.


class Test 
{
	public void exampleMethod() 
	{
		int x = 10; // local variable with local scope
		System.out.println(x);
	}

    public static void main(String[] args) 
	{
        Test obj = new Test();
        obj.exampleMethod();
    }
}

Output:


10

Instance scope: 


Within a class, but outside of any methods, constructors, or blocks, instance variables are declared. All of that class's constructors, blocks, and methods have access to them. As long as the class object is alive, the instance variables continue to exist. 


Here's an illustration:


The Java program below creates a class called "Test" that contains an instance variable by the name of x. 


The "this" keyword can be used to access the instance members of the class in its methods. This keyword is related to the class's current object.


The "this" keyword is used to initialize the instance variable's value in the class' setter method.


The instance variable of x value is printed using the getter function.


Next, we create an object of the Test class called "obj" inside the main method.


Finally, we invoke the setter method with the parameter "obj" and set a value of 100. We also invoke the getter function with the parameter "obj" to display the output.


class Test 
{
	int x; // instance variable with instance scope

    public void setX(int value) {
        this.x = value;
    }

    public void getX() {
        System.out.println(x);
    }

    public static void main(String[] args) 
	{
        Test obj = new Test();
        obj.setX(100);
		obj.getX();
    }
}

Output:


100

Class scope (static scope): 


In Java programming, when a variable is declared static, it indicates that the variable is class-scoped.


They can be accessed using the class name or objects and are shared by all instances of the class. As long as the class is loaded into memory, class variables are present.  


Here's an illustration:


A static variable named "count" belongs to the Test class in this Java program. 


Within the incrementCount() method, we declare and increment the static variable. 


We create two objects for the same class, named obj1 and obj2, in the main method. 


In the end, the result will include the same values if you execute the incrementCount() method with distinct "obj1" and "obj2" objects.  


This indicates that no matter how many instances of the class are produced, there is only one copy of the variable in memory.


public class Test 
{
    static int count; // class variable with class scope

    public void incrementCount() {
        count++;
    }

	public static void main(String[] args) 
	{
        Test obj1 = new Test();
        obj1.incrementCount();
		
		Test obj2 = new Test();
        obj2.incrementCount();
		
		System.out.println("Obj1: count is="+obj1.count);
		System.out.println("Obj2: count is="+obj2.count);
		
    }
}

Output:


Obj1: count is=2
Obj2: count is=2

Block scope: 


Block scope refers to variables declared inside a block and enclosed in curly braces. They can only be reached from that block.


Control structures like loops and conditional expressions frequently employ block scope. 


Here's an illustration:


We initialized and printed the value of the y variable inside the block in this Java program.


public class Test 
{
	public void exampleMethod() 
	{
		int x = 10;

		if (x > 5) 
		{
			int y = 20; // block variable with block scope
			System.out.println(y);
		}

		System.out.println(x);
		//System.out.println(y); // This would result in an error since y is not accessible here
	}
	
	public static void main(String[] args) 
	{
		Test obj = new Test();
		obj.exampleMethod();
	}
}

Output:


20
10

You will get a compile-time error if you attempt to access the value of the "y" variable outside of the block.


System.out.println(y); // This would result in an error since y is not accessible here

It's important to note that variables with the same name can have different scopes, and the scope of a variable determines its visibility and lifetime within a program.

No comments:

Post a Comment

Post Bottom Ad