Detailed Print – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  


Shop
siteicon
Code Learning#JAVA#3865

Variable Kinds – Local, Class and Instance Variables

Mainly used kinds Local, Class and Instance Variables are discussed here.

Learning Objectives

  • Understanding the three main kinds instance, class and local variables.

Source Code

		 

Click to open popup

Run Output

1
2
3

Code Understanding

class VarKinds
{
static int x=1; 
This is a class variable as it can only be defined once and all objects based on this can use it and modify it. It does need a static modifier.

int y=2;
This is an instance variable which can be used by any object (instance of the class) but it would take different memory space for different objects. So each instance will have different copy of this variable.

public static void main(String[] args)
{
int z=3;
This is a a local variable and this would be usable within the scope of given method. For e.g. the current method is main() method, so it can be used within main method.

VarKinds ob=new VarKinds();
Instance variable does need an object declaration, which is being done here.

System.out.println(x);
The class variable (static) is printed here directly. This is possible because its name does not clash with any other local variable name. If it clashes, the this keyword is to be used (provided current method is non-static).

System.out.println(ob.y);
This is instance variable reference using the reference of object.

System.out.println(z);
This is local variable reference
}
}

Notes

  • Other these kinds the method argument variable, constructor argument variables, array initialisation variables and exception indication variables are also considered as different kinds. They may however be considered as local types only.
  • The oracle documentation for variable kinds and other definitions can be seen at.
    https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html


Suggested Filename(s): VarKinds.java