Scope of a Variable In Java [With Coding Example]
Updated on Nov 25, 2024 | 7 min read | 16.7k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 25, 2024 | 7 min read | 16.7k views
Share:
Table of Contents
Programmers define the scope of a Variable in Java that tells the compiler about the region from where a variable is accessible or visible. The scope of a variable in Java is static by nature. It means we have to declare it at compile time only. In this article, you will learn about the scope of a Java variable along with its types.
Check out our free courses to get an edge over the competition.
Every variable used in a programming language holds a scope. The scope tells the compiler about the segment within a program where the variable is accessible or used. Programmers can scope the variables lexically or statically in the case of Java variables.
The static scope variable means the programmers have to determine the scope of a variable in Java at compile-time rather than at run-time. Also, note that every class is a part of a Java package. That boils down to two different categories of scopes of a variable in Java.
Check out upGrad’s Advanced Certification in DevOps
1. Member variables with class scope: Member variables are members of a class and hence declared inside a class but not inside any method or function. Thus, we can address such variable scope as class scope or class-level scope. Programmers declare such variables within the class’s curly braces ({}) along with an access modifier. Programmers can use such variables anywhere within the Java class but not outside it.
Example:
public class EgOfClassScope {
private Integer amt = 10;
public void egMethod() {
amt += 10;
}
public void anotherExampleMethod() {
Integer AmtIncr = amt + 6;
}
}
Check out upGrad’s Advanced Certification in Cloud Computing
We can see that the ‘amt’ variable is accessible within all the methods of the class. If we use the public access modifier instead of private, the variable will become accessible from anywhere within the package.
Modifier Package Subclass World
public Yes Yes Yes
protected Yes Yes No
Default (no
modifier) Yes No No
Private No No No
2. Local Scope or Method Scope: Programmers can declare local variables in a local scope having a lesser range (let suppose, within the method). Programmers cannot access such variables from outside the Java method, even in the same class. They have limits in the accessibility, and their visibility ends when the scope of the Java method finishes.
Example 1:
public class EgOfMethodScope {
public void FirstMethod() {
Integer salary = 6000;
}
public void SecondMethod() {
// This will encounter a compile-time error saying: area cannot be resolved to a variable
salary = salary + 2000;
}
}
It is an example of a method scope. Here I have created the variable ‘salary’ within the FirstMethod(){….}. Therefore, its scope ends at the end of the FirstMethod(). So, utilizing this variable in the SecondMethod() will create an error as the variable ‘salary’ is out of scope.
Example 2:
class EgOfMethodScope2
{
private int g;
public void setG(int g)
{
this.g = g;
}
}
Here, we use the ‘this’ keyword to distinguish between local scope and class variable’s scope. Programmers use this keyword to point to the current object as a reference variable. Here the programmer passes the variable as a parameter to the method.
Note that the local variables will not exist once the method execution is over. There are other forms of local scope used within the Java method but at a specific portion inside it.
Example:
public class EgOfLoopScope {
List<String> listOfEmp = Arrays.asList ( “Karlos”, “Gaurav”, “Sue”, “Dee”);
public void iterateEmpName() {
String all = “”;
for (String names: listOfEmp)
{ // The scope of the loop starts from here
all = all + ” ” + names;
} // the loop scope ends here
// You will encounter a compile-time error saying: name cannot be resolved to a variable – if you try to access the variable in the next line
String lastEmpName = names;
}
}
In this method iterateEmpName(), the variable ‘names’ have a loop scope (as it is a counter variable) and is accessible within the { and } of the ‘for’ statement.
Example:
public class EgOfBracketScope {
public void EgAddOp() {
Integer tot = 0;
{ // The bracket starts from here
Integer no = 6;
tot = tot + no;
} // the bracket scope ends here
// It will create a compile-time error saying: number cannot be solved as a variable – if used in the next line
no– ;
}
}
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
This article shows how programmers use Java scopes to write different programs. It also tells us about the area within a program where the variable is visible. Both accessibility and visibility play a significant role in programming because of the concept of scope. Any single mistake in scoping the variable can lead a programmer to a compile-time error.
If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources