Section 2: Instance and local variables

Instance variables:

1.Instance variables are those variables that are declared within the class outside the method without static. It means instance variables are non-static variables.

2.These variables are accessible throughout the class or outside the class if public by creating an object.

3.Users don’t need to initialize the instance variables its default value will be null (if a string) or 0 (if int). That default values we have already seen in Data Types.

4.Instance variables are created at the time an object is created for that class.
If we try to access instance variables from the static method directly then it will throw compile-time error saying error: non-static variable data cannot be referenced from a static context.

6.It means to access instance variables we need to create an object.

Following is the example for instance variable

Variables in Java

Local variables:

1.Local variables are declared within the method.

2.These variables are accessible only inside that particular method can not be accessed by other methods of the same class.

3.Users must initialize the variable value before its use else it will give a compile-time error saying variable data might not have been initialized.

4.Local variables are created at the time method is called and destroyed when the method’s execution ends.

Following is the example for the local variable.
In line 4: we are declaring a local variable, but not initialized. Due to which when we try to print its value we will get a compile-time error.
Delete line 5 and initialize the value before printing, this will print its value in the output.

Variables in Java

-A blog by Shwetali Khambe

Related Posts