(Translated by https://www.hiragana.jp/)
Scope of Variables In Java - GeeksforGeeks
Open In App

Scope of Variables In Java

Last Updated : 13 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of function call stack. 
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories.
 

Member Variables (Class Level Scope)


These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example: 

public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}
  • We can declare class variables anywhere in class, but outside methods.
  • Access specified of member variables doesn’t affect scope of them within a class.
  • Member variables can be accessed outside a class with following rules
Modifier      Package  Subclass  World

public Yes Yes Yes

protected Yes Yes No

Default (no
modifier) Yes No No

private No No No

Local Variables (Method Level Scope)


Variables declared inside a method have method level scope and can’t be accessed outside the method. 

public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}


Note : Local variables don’t exist after method’s execution is over. 

Here’s another example of method scope, except this time the variable got passed in as a parameter to the method: 

class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}

The above code uses this keyword to differentiate between the local and class variables.

As an exercise, predict the output of following Java program.  

Java
public class Test
{
    static int x = 11;
    private int y = 33;
    public void method1(int x)
    {
        Test t = new Test();
        this.x = 22;
        y = 44;

        System.out.println("Test.x: " + Test.x);
        System.out.println("t.x: " + t.x);
        System.out.println("t.y: " + t.y);
        System.out.println("y: " + y);
    }

    public static void main(String args[])
    {
        Test t = new Test();
        t.method1(5);
    }
}

Output: 

Test.x: 22
t.x: 22
t.y: 33
y: 44


Loop Variables (Block Scope) 
A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only.

Java
public class Test
{
    public static void main(String args[])
    {
        {
            // The variable x has scope within
            // brackets
            int x = 10;
            System.out.println(x);
        }
        
        // Uncommenting below line would produce
        // error since variable x is out of scope.

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

Output: 

10


As another example, consider following program with a for loop. 

Java
class Test
{
    public static void main(String args[])
    {
        for (int x = 0; x < 4; x++)
        {
            System.out.println(x);
        }

        // Will produce error
        System.out.println(x);
    }
}

Output: 

11: error: cannot find symbol
System.out.println(x);


The right way of doing above is, 

Java
// Above program after correcting the error
class Test
{
    public static void main(String args[])
    {
        int x;
        for (x = 0; x < 4; x++)
        {
            System.out.println(x);
        }

       System.out.println(x);
    }
}

Output: 

0
1
2
3
4


Let’s look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are regular C/C++ programmer. 

Java
class Test
{
    public static void main(String args[])
    {
        int a = 5;
        for (int a = 0; a < 5; a++)
        {
            System.out.println(a);
        }
    }
}

Output :

6: error: variable a is already defined in method go(int)
for (int a = 0; a < 5; a++)
^
1 error


Note:- In C++, it will run. But in java it is an error because in java, the name of the variable of inner and outer loop must be different.
A similar program in C++ works. See this.

As an exercise, predict the output of the following Java program. 

Java
class Test
{
    public static void main(String args[])
    {
        {
            int x = 5;
            {
                int x = 10;
                System.out.println(x);
            }
        }
    }
}

Q. From the above knowledge, tell whether the below code will run or not.

Java
class Test {
    public static void main(String args[])
    {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
        int i = 20;
        System.out.println(i);
    }
}

Output : 

1
2
3
4
5
6
7
8
9
10
20


Yes, it will run! 
See the program carefully, inner loop will terminate before the outer loop variable is declared.So the inner loop variable is destroyed first and then the new variable of same name has been created.

Some Important Points about Variable scope in Java:  

  • In general, a set of curly brackets { } defines a scope.
  • In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined.
  • Any variable defined in a class outside of any method can be used by all member methods.
  • When a method has the same local variable as a member, “this” keyword can be used to reference the current class variable.
  • For a variable to be read after the termination of a loop, It must be declared before the body of the loop.


 



 



Previous Article
Next Article

Similar Reads

Java Spring - Using @Scope Annotation to Set a POJO's Scope
In the Spring framework, when we declare a POJO instance, what we are actually creating is a template for bean definition. It means, just like a class, we can have many object instances created from a single template. When a bean definition is created, we can control not only the various dependencies and configuration values that are to be plugged
6 min read
Custom Bean Scope in Spring
Prerequisite: Singleton and Prototype Bean Scopes in Java Spring In this article, we are going to discuss the custom bean scope in Spring. I presume that you guys know about Spring bean and its scopes provided by Spring framework. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Spring provides t
5 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Using Static Variables in Java
Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now
3 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Local Variables in Java
The variables declared inside the body of the method are termed local variables. A function is a collection of statements that are designed to perform a specific task. Functions take certain input(s) and its parameter and give output or return value. A function is created that one can not have to write the same code, again and again, we call to use
6 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Environment Variables in Java
In Java, Environment variables are widely used by operating systems to deliver configuration data to applications. Environment variables are key/value pairs with both the key and the value being strings, similar to properties in the Java platform. What are Environment Variables in Java?In Java, Environment variables are values that are stored outsi
5 min read
Are static local variables allowed in Java?
Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error "Static local variables are not allowed" C/C++ Code class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 10; //Error: Static local variables are not allowed
1 min read
Assigning values to static final variables in Java
Assigning values to static final variables in Java: In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.For example, following program works fine. Java Code class Test { //
1 min read
Final local variables in Java
Prerequisite : final keyword, Variables, Scope of Variables A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the blo
2 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
final variables in Java
In Java, we can use final keyword with variables, methods, and classes. When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed.  Example 1: Usage of final with primitive datatype Java Code // Java Program to illustrate Use of Final Keyword // With Primitive Dataty
2 min read
Static Variables in Java with Examples
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. Important points for static variables: We can create static variables at class-level only. See herestati
1 min read
Unnamed Patterns and Variables in Java
Java programming language offers multiple features that allow developers to write rich and concise code. Among these features, there are unnamed patterns and variables which enables developers to work with data in a more flexible and elegant way. In this article, we will study about unnamed patterns and variables in Java and how they can be used ef
4 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Java Variables
In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory location name for the data. Variables in JavaJava variable is a name given to a memory location. It is the basic unit of
8 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
MATLAB - Variables
Prerequisite: Getting Started with MATLAB A variable in simple terms is a storage place that has some memory allocated to it. Basically, a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations that can be applied to them. The Matlab workspace store all the
3 min read
Variables in Scratch Programming
Scratch is a high-level visual programming language tool that interacts with users through diagrams and blocks that have the basics of a program inbuilt in it. Scratch is used to make interactive programs especially for kids using the block kind of interfaces so that they can easily learn languages and it is free to use. In this article, we will di
7 min read
Spring MVC Matrix Variables
In this article, we will learn about Spring MVC Matrix Variables. Matrix Variable is used to parse and bind name-value pairs inside a path segment to method parameters. A semicolon separates many pairs. Matrix variables must first be enabled. XML Matrix VariableBelow are the necessary dependencies and maven plugins added to the pom.xml file. C/C++
3 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
Assigning Values to Variables
In this article, we will learn how to assign values to variables in Python and other languages also. Assigning Values to Variables in PythonBelow are the steps and methods by which we can assign values to variables in Python and other languages: Direct Initialization MethodUsing Conditional OperatorAssign Values to Variables Direct Initialisation M
4 min read
Python Variables
Python Variable is containers that store values. Python is not "statically typed". We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. In this article, we will
9 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg