Program to show Scope of Variables

Variables are a place where information can be stored while a program is running. The value can be changed at any point in the program—hence the name.

To create a variable, you must give it a name and identify what type of information it will store. You also can give a variable an initial value at the same time you create it.

There are three kinds of variables in Java:
instance variables, class variables, and local variables.

  1. Instance variables, as you learned yesterday, are used to define an object's attributes.
  2. Class variables define the attributes of an entire class of objects, and apply to all instances of it.
  3. Local variables are used inside method definitions, or even smaller blocks of statements within a method. They can be used only while the method or block is being executed by the Java interpreter, and they cease to exist afterward.
We can divide scope into
  1. method body scope Variable is accessible in method body only (local variables, parameters)
  2. class definition scope Variable is accessible i class definition (instance variables)

class TestClass
{
int i=3;
public static void main(String[] args)
{
Void method(int k)
{
System.out.println("i="+i+","+"j="+j);
// i=3, j=7
int i=4;
// int k=1; it will give compiler error

{
int j=5;
// int i=1; will give compiler error
System.out.println("i="+i+","+"j="+j);
// i=4, j=5
}

{
int j=9;
System.out.println("i="+i+","+"j="+j);
// i=4, j=9
}
}
int k=6;
int j=7;
//either stuff
}
}

Note: There are no global variables in Java?

Google Search