Hi I would really appreciate it if someone could briefly describe what the differences are between local variables and instance variables.
Thank you.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Hi I would really appreciate it if someone could briefly describe what the differences are between local variables and instance variables.
Thank you.
Consider the following code:Here a is an instance variable. Every object created from this class will have its own copy of a. Instance variables are properties of an object. On the other hand, the variable v is a local variable that isn't a property of an object created from this class. Local variables are created whenever the method that declared them is invoked. Once control moves to the end of the method, local variables are destroyed.class a { int a; void b() { int v; }}
Now, consider the following test class
class Test { public static void main(String args[]) { a a1=new a1(); a a2=new a2(); a1.a=1; a2.a=2; System.out.println(a1.a+" "+a2.a); //the two objects a1 and a2 have their own values of a i.e a is the property of the instance of class a // This statement would give an error since v is a local variable and isn't a property of the object a1: System.out.println(a2.v); } }
Thank you I really appreciate your comments.