I'm just a little bit confused about instance variables and primitive variables. When we say instance variables, they are the variables which are not inside a method or shall we say "local variables". Does it mean also that those primitive variables outside a method are instance variables? such as: int i;, long l = 20L; and so on.. and primitive variables inside a method are local variables? Or instance variables are reference of a class and object but not primitive data declared either outside or inside of a method.
Denver, It is not necessarily true that a variable outside any method is an instance variable. This is because it could be a class (denoted by static) variable. Static or class variables do not belong to the instances but they belong to the whole class. An example of static variable would be a static integer that keeps a count of how many instances or objects you created in the program. Hope it helped you understand the point better.
Do not compare "primitive variables" with "instance variables". If you want to do a differentiation on variables, better to compare the following two pairs, it will give you a clear picture; - primitive variables / reference variables - class variables / instance variables
primitive variables are of type byte, short, int, long, float, double, char, boolean. Reference variables are pointing to objects in the heap, therefore the primitive variables are excluded since those are not considered as objects in java.
When comparing class and instance variables, the "static" keyword comes in to play. The variables which are marked as static are class variables and non-static variables are considered as instance variables. For a class variable there is only one copy of the variable available for all the objects(instances) of that class. So if you make any changes to the class variable all the objects of that type gets affected since all are pointing to the same memory location in the heap. (NOTE : class variables can be accessed through both class name or the instance names, but it is recommended to access through the class name.)
When considering the instance variables, each object of the class are having a separate copy of the variable. Therefore when you do a change to an instance variable through the instance name, only the copy which belongs to that particular instance is modified and the values of other objects remains the same. (NOTE : instance variable can be accessed only through instance names.)
Variables inside methods are called "local variables" and belongs only to the method scope.
Let me know if any further explanation is needed. If you are planning to do the SCJP, i recommend you to read Kathy Sierra's book. It will clear all your doubts.
"Simplicity is the ultimate sophistication..." ~Leonardo da Vinci~
subject: Instance variables and primitive variables