- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
Java Variable Scope
So far, all variables have been declared at the beginning of the main() method. Java, on the other hand, allows variables to be declared within any block.
A block is formed by starting with an opening curly brace and ending with a closing curly brace. A scope is defined by a block. As a result, each time you start a new block, you create a new scope. What objects are visible to other parts of your program are determined by a scope. It also determines how long those objects will live.
Many other computer languages distinguish between global and local scopes. These traditional scopes, however, do not fit well with Java's strict, object-oriented model. While creating what amounts to a global scope is possible, it is far more the exception than the rule.
In Java, there are two types of scopes: those defined by a class and those defined by a method. Even this distinction is a little arbitrary. This distinction makes sense, however, because the class scope has several unique properties and attributes that do not apply to the scope defined by a method. In a later chapter, you will learn more about class. For the time being, we will only look at the scopes defined by or within a method.
A method's scope is defined by its opening curly brace. However, if that method has parameters, those parameters are also included in the method's scope.
As a general rule, variables declared inside a scope are not visible or accessible to the code that is defined outside the scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that the objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
Java Variable Scope Example
To understand the effect of nested scopes, consider the following program:
public class JavaProgram { public static void main(String args[]) { int x; // 'x' is known to all within the main() function. x = 10; if(x == 10) { int y = 20; // 'y' is known only to this block System.out.println("x : " + x + "\ny : " + y); x = y * 2; } System.out.println("x is " +x); } }
When the above Java program is compiled and run, it will produce the following output:
In the above program, the "int x" declaration creates an integer variable "x" within the "main()" method, and sets its initial value to 10. This variable is accessible from anywhere within the main() method, but not outside of it.
Within an "if" statement block that checks if "x" is equal to 10, a new integer variable "y" is declared and initialized to 20. This y variable is only known within the scope of the "if" block, and cannot be accessed from outside of it.
The code then prints the values of "x" and "y" using "System.out.println()" method. Since "y" is only known within the "if" block, it is not accessible outside of it, and the value of "y" cannot be printed again in the later statements.
The value of "x" is updated by setting it equal to "y * 2." Since "x" is defined outside of the "if" block, it is accessible and can be updated within the "if" block, and the new value of "x" can be printed using "System.out.println()" method outside of the "if" block.
Therefore, the variable "x" is known throughout the "main()" function, while the variable "y" is only known within the "if" block.
Advantages of variable scope in Java
- Security: It protects variables and data from being accessed by unauthorized code or accidentally modified by other parts of the program.
- Memory efficiency: It allows variables to be created only when they are needed and released when they are no longer needed, freeing up memory and making the program more efficient.
- Code readability: Because variables are only accessible within their respective scopes, it makes the code easier to read and understand.
- Name collisions are avoided because variables with the same name can exist in different scopes without causing conflicts.
Disadvantages of variable scope in Java
- Difficulty debugging: If a variable is declared in an inner scope and used outside of it, debugging the code and locating the issue can be difficult.
- Overhead: When multiple nested scopes are created, it can result in time and memory usage overhead.
- Issues with initialization: If a variable is declared in a narrow scope, it may not be initialized before it is used, potentially leading to bugs.
- Multiple nested scopes can make code more complex and difficult to read and maintain.
« Previous Tutorial Next Tutorial »