• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » DataType » Scope of a Variable in Java
Next →
← Prev

Scope of a Variable in Java

By Dinesh Thakur

The scope of a variable specifies the region of the source program where that variable is known, accessible and can be used. In Java, the declared variable has a definite scope. When a variable is defined within a class, its scope determines whether it can be used only within the defined class or outside of the class also.

Local variables can be used only within the block in which they are defined. The scope of instance variables covers the entire class, so they can be used by any of the methods within that class.

Variables must be declared before usage within a scope. Variables that are declared in an outer scope can also be used in an inner scope. The unique way in which Java checks for the scope of a given variable makes it possible to create a variable in an inner scope such that a definition of that variable hides its original value. Program makes this point clear.

Checking the scope of a variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
class ScopeOfVariables {
 static int var = 10;
 ScopeOfVariables() {
   // variable var from outer scope is accessed here
   System.out.println(''Variable accessed from outer scope =" +var);
 }
 public static void main(String args[]) {
  int var 25;
 //variable var from current scope is accessed here
 ScopeOfVariables sc= new ScopeOfVariables();
 System.out.println("Variable accessed from current scope =" +var);
 }
}

The output of Program is given below:

Variable accessed from outer scope = 10

Variable accessed from current scope = 25

The ScopeOfVariables class has two variables defined with the same name (var). One variable (local variable) is defined within the main method, which is initialized to 25, and another variable (instance variable) is declared within the class, which is initialized to 10. When an instance of the class ScopeOfVariables is created, its constructor is invoked. As variable var is accessed inside the constructor, it will check for declaration of the variable in the current scope (that is, within braces). As the declaration is not found in its current scope, it goes to upper level and checks the variable declaration. Since it is defined in the class (outside the method), now, the variable takes the value 10 and the program displays the first line of the output. On the other hand, in the main method, the local variable var is accessed in its current scope. Here, the local variable hides the instance variable. So, this variable takes the value 25 and the println() method will print the second line of the output.

In order to avoid confusion it is better to give different names to local variables and instance variables.

Another way to get around this particular problem is to use the keyword this. The instance variable can be referred to by using this.var in the above program. By referring explicitly to the instance variable using its object, scope conflict can be avoided.

Other definitions that can cause bugs

Another situation in variable naming is when a variable that occurs in a super-class is redefined in the sub-class. This can create subtle bugs in the program. This would lead methods that were intended to change the value of an instance variable to change the wrong ones.

Another bug might occur when an object is cast from one class to another. In such cases, the value of instance variable is likely to change because it is accessing the value from the super-class instead of the child class.

It is recommended that before defining variables in a sub-class, the programmers take note of the variables in each of the super classes corresponding to that class and avoid such problems. This would help in preventing duplication of variables which can lead to bugs.

You’ll also like:

  1. Variable’s Scope and Lifetime of a Variable
  2. What is Scope of Variable
  3. Define the term Scope, Visibility And Lifetime of a Variable
  4. Scope of Java Variables
  5. Final Variable (OR Constant Variable) in Java with Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW