JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Monday 10 November 2014

Instance variable and static variable affect

Java programming language defines following 3 kinds of variables.
1.Instance variable
2.Static variable
3.Local variable.
Here we will discuss about the Instance variable and Static Variable and their effects.

Instance Variable:

a.Non-static variable are called instance variable.
b.Instance variable are the variable which are used inside a class but outside any methods,constructor or any block.
c.Individual states of object is stored in Instance variable or "non-static field".(we will see the effect in the following example).

Static variable:

a.Static variables are also known as class level variable declared in a class, but outside a method, constructor or a block.
b.Class variable or static variables are declared with "static" modifier.
c.Static variables can be accessed by calling with the class name . ClassName.VariableName.

Local Variable:

a.Local variables are declared in methods, constructors, or blocks.
b.Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
c.Local variables are visible only within the declared method, constructor or block.

Now lets see the examples to understand the effect of Instance variable and Static variable on object.
A separate copy of instance variable is available to all objects,but a single copy of static variable in memory is available for all objects,so if we change the values of instance variable in one object it does not effect other instance variable in another object,but in case of static variable it affects to all other objects too.Here is example:

Example 1:


class InstanceVariableEffect
{
int x=12; //instance variable
void show()
{
System.out.println("Value of x is : "+x);
}
}

class InstanceVariableEffectDemo
{
public static void main(String args[])
{
InstanceVariableEffect ive1=new InstanceVariableEffect();
InstanceVariableEffect ive2=new InstanceVariableEffect();
++ive1.x;
ive1.show();
ive2.show();
}
}*/
O/P:
Value of x is :13
Value of x is :12
................................................................................................................................................

Example 2:

class StaticVariableEffect
{
static int x=12; //static variable
void show()
{
System.out.println("Value of x is : "+x);
}
}

class StaticVariableEffectDemo
{
public static void main(String args[])
{
StaticVariableEffect sve1=new StaticVariableEffect();
StaticVariableEffect sve2=new StaticVariableEffect();
++sve1.x;
 sve1.show();
 sve2.show();
}
}
O/P:
Value of x is :13
Value of x is :13

No comments:

Post a Comment

Designed By Blogger Templates