Whatis the difference between the static variable and ordinary variable?gimme an example pls!........

Showing Answers 1 - 14 of 14 Answers

MUDIAPPAN.A

  • Nov 4th, 2006
 

hi

static variable:

just it is global variable

We access this variable thourough this 

classname.variable;

where in case of local variable u can access that particular method alone

u can't access that variable where u decalere other than that method

  Was this answer useful?  Yes

swapna

  • Nov 5th, 2006
 

static variable has a single copy of the object where as an ordinary variable store a indivdual element

  Was this answer useful?  Yes

MUTHU

  • Nov 14th, 2006
 

hitake this example class B { static int i=5; //Here i is class variable as well as intsance varible int a;//But it is only instance variable. //intsance mean it can access only object static void cal() { System.out.println("hello"); } public static void main(String [ ]args) { B a1=new B(); System.out.println("i = " + B.i);//we can access by class name System.out.println("i = " + a1.i);//we access by object name System.out.println("i = " + B.i); System.out.println("a = " + a1.a); /* System.out.println("a = " + B.a); it gives compilation error */ B.cal(); a1.cal(); }}'i' variable can be accessed by class name (B.i) as well as object name(B.a1). But 'a' variable can be access only object because it is only instance vaiable.second thing, whenever static will be executed before object created during compilation. So,all object shares static variable or static methods

  Was this answer useful?  Yes

Radhakrishna

  • Nov 14th, 2006
 

hi,

The main diff is that,memory will allocated for the static variable as soon as class is loaded into the memory, but for the instance variable memory will be allocated if u try to create an object otherwise it wont be allocated..

  If u observe one thing we can't access the instance variables in the static methods(eg.. main() method),the main reason for this is that  memory allocated for those methods at the time of loading of class itself so at that time it doesn't know about any object.so it is not able find for which object this variable belongs to....

  We can access the static variable with class name as well as with the object also.Means this variable is class variable not belong to particular object, so any object of that class type can access this variable and if u made change with one object it will reflect in the other objects also(objects of same type).

this is as per my knowledge,if any thing wrong plz correct it..

  Was this answer useful?  Yes

Guest

  • Nov 29th, 2006
 

Static variable is called even before the instance of the class is created.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions