Skip to content

Q 22 - Variable Scope #26

Discussion options

You must be logged in to vote

😎 In Java, variable scope refers to the part of the program where a variable is accessible. It determines the lifespan and visibility of that variable. Here's a breakdown:

🔍 Types of Variable Scope in Java

1. Local Variables

  • Declared inside a method, constructor, or block.
  • Accessible only within that method/block.
  • Automatically destroyed once the method finishes.
  • Example:
    void greet() {
        String message = "Hello!";
        System.out.println(message); // message is accessible here
    }

2. Instance Variables

  • Declared inside a class but outside any method.
  • Belong to each object of the class.
  • Accessible by all methods of the class using this reference.
  • Example:
    class Person {
        String name; /…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by HARSHITH-MV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants