Postby padmajaprasad » Fri Feb 08, 2013 3:44 am

How are Class variables, Instance Variables and Local variables different from each other? How are they declared in a program?
Posts: 5
Joined: Tue Jan 29, 2013 2:53 pm

Re: Variables

Postby Kishan » Fri Feb 08, 2013 3:44 pm

Local Variables:
- Declare inside method or block.
- Life time is end of the declared method/block.


if(i > 0) {
int result = j/i;
return result;

Instance Variables or Object Variables:
- Declares inside class and outside of methods.
- every instance will have its copy of these variables. Changing one object variable doesn't interfere with other object variables.
- Access these variables with object.
- Life time is till the object is Garbase Collected.

Example: public int age;

Class Variables or Global Variables:
- Declares inside class and out side of methods. Prefixed with static keyword.
- Inspite of how objects having created for that class only one memory slot applied for these variables. Every object can see same out of these variables if objects are created.
- You dont require to create object to access these variables. You can directly access with class name.
- These variables automatically available when class loaded in the memory.
- Life time is till class object available in the memory.

Example: public static String companyName = "Java/J2EE Training";
Posts: 191
Joined: Tue Jan 29, 2013 4:21 am

Return to Core Java

Who is online

Users browsing this forum: No registered users and 1 guest