Scope of Variables in Java

In Java, the scope of a variable refers to the portion of the code where the variable is accessible and can be used. There are several types of variable scopes in Java:

  1. Local Variables
  2. Instance Variables
  3. Class/ Static VariablesTypes of Variables in Java

Local Variables

A local variable is assigned a value locally. It is a variable that gets declared inside a method and can be accessed inside the same method only. For example,

int rank = 10;

Instance Variables

A variable that is declared in a class, but outside the method, is known as an instance variable. It is not declared as static. For example,

int id =5;

Class/ Static Variables

A class variable is declared static. A class variable is also known as a static variable. For example,

static int fees;

Example – Scope of Variables

Let’s see the complete example to work with local, instance, and class variables in Java:

public class StudyopediaDemo {
       int id = 5; // instance variable
       static int fees; // static variable
       
   void collegeDetails() {
       int rank = 10; // local variable
       System.out.println("College Id: " + id);
       System.out.println("College Rank: " + rank);
   }

   public static void main(String args[]) {
      StudyopediaDemo st = new StudyopediaDemo();
      fees = 3000;
      System.out.println("College Monthly Fees: " + fees);
      st.collegeDetails();
   }
}

Here’s the output for the above program, which shows the usage of Java variables:

Java Variables Output


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Data Types in Java
Java Polymorphism
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment