Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconScope of a Variable In Java [With Coding Example]

Scope of a Variable In Java [With Coding Example]

Last updated:
4th Feb, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Scope of a Variable In Java [With Coding Example]

Introduction

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.

What is the Scope of a Variable in Java?

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.

Ads of upGrad blog

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.

Explore our Popular Software Engineering Courses

  • Loop Scope: There are situations when we declare variables inside a loop. Such variables will have a loop scope and can be accessed from within a loop only.

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.

Explore Our Software Development Free Courses

  • Bracket Scope: Programmers can define additional scope anywhere within the program. Programmers can define this extra scope using the { and } brackets.

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– ;

    }

}

In-Demand Software Development Skills

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Ads of upGrad blog

 

Salient Points About the Scope of a Variable in Java

  •         Like other programming languages (C, C++, and C#), we have to use a set of curly brackets ({ and }) to define the scope of a variable in Java.
  •         We can access a variable from any method if we define it within a class outside any method scope.
  •         To use a variable after the termination of a loop, we have to declare it before or just above the loop’s body.
  •         But we cannot implement or access it without a constructor, Java method, and block.
  •         The scope of a static variable resides within the class only.
  •         The scope defines the region within a program from where the variables will be accessible. 

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.

Read our Popular Articles related to Software Development

Conclusion

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is a variable scope in Java?

A variable's scope is the place in your program where it can be referenced. Variable scope is specified using the 'scope' keyword in the variable declaration. A variable that can be accessed in 'any' scope can be accessed absolutely anywhere in your program. A variable that can be accessed only in a specific scope can only be accessed in that scope. The scope may be a function, a block, a method, a class, or outside of all methods, blocks and classes.

2What are the types of access modifiers in Java?

There are four types of access modifiers in Java: public, protected, default (package) and private. Public make the variable, class or function accessible to anywhere, protected makes it accessible to the class in which it is defined plus it’s sub classes, default (package) makes it accessible to any class in the same package and private makes it accessible to only the class in which it is defined.

3What is static keyword in Java?

A static keyword in a Java class denotes that the class so declared is not an instance of the class but is a class by itself. The static data members of the class are common to all the instances. A static keyword is used to access static methods and fields of a class. In Java, static keyword is used to access the static methods and fields of a class. To access static methods and fields of a class, you should use the name of the class, a dot (.), and the static method or field name.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31379
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46802
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901159
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
51394
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
908734
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34600
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902285
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
25914
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4046
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon