Scope of Variable

 Scope of Variables

The Accessibility of the variables in a program.

These are classified into 3 types:

  1. Instance variables
  2. Class variables
  3. Local variables


Instance Variables

  • These variables are available until there is a memory allocated to the instance of the class.

Example:

class MyClass{

public MyClass(){

 message="Welcome";

}

String message;

}

public class Main{

public static void main(String gdv[]){

MyClass d =new MyClass();

System.out.print(d.message+" "+new MyClass().message);

}

}

OUTPUT:
Welcome Welcome


Class Variables 

  • These variables are available until the end of the entire program execution.
  • These can be accessed anywhere throughout the program.

Example:

class MyClass{

static String message="Hello";

public static void main(String []gdv){

System.out.print(message);

}

}

OUTPUT:

Hello


Local Variables

  • These variables are only available until the method is executed.
  • After the method finishes executes then these variables are unavailable.
  • These variables are declare inside a method.

Example:

class MyClass{

public void display(){

String msg="Welcome";

System.out.print(msg);

}

public static void main(String []gdv){

Myclass m=new MyClass();

m.display();

}

}

OUTPUT:

Welcome

Comments

Popular posts from this blog

Constructors in java