Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Java Scope


Java Scope

In Java, the scope refers to the region of the code where a variable, method, or class is visible and accessible. Understanding scope is crucial for writing maintainable and bug-free code. Here are the different scopes in Java:

1. Class Scope (Global Scope)

        public class MyClass {
          private static int count; // Class-level variable
          public static void main(String[] args) {
              count = 10; // Accessing class-level variable
          }
      }
       

2. Method Scope

      public class MyClass {
        public void myMethod() {
            int x = 10; // Method-level variable
            System.out.println(x); // Accessing method-level variable
        }
    }
    

3. Block Scope

      public class MyClass {
        public void myMethod() {
            if (condition) {
                int y = 20; // Block-level variable
                System.out.println(y); // Accessing block-level variable
            }
        }
    }
    

4. Instance Scope

        public class MyClass {
          private int value; // Instance variable
          public void setValue(int newValue) { // Instance method
              value = newValue;
          }
      }
      

5. Local Scope

      public class MyClass {
        public void myMethod() {
            int z = 30; // Local variable
            System.out.println(z); // Accessing local variable
        }
    }
    

6. Static Scope

      public class MyClass {
        private static int value; // Static variable
        public static void setValue(int newValue) { // Static method
            value = newValue;
        }
    }
    

Notes:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java