Net-informations.com
SiteMap  | About    

Local Variable Vs Instance Variable Vs Class Variable

What is a Local Variable?

A local variable in Java is typically used in a method, constructor, or bloc and has only local scope. So, you can use the variable only within the scope of a block. Other methods in the class aren't even aware that the variable exists.

Example

In the above case, you cannot use testLocal outside of that if block.

What is an Instance Variable?

An instance variable is a variable that's bound to the object itself. Instance variables are declared in a class , but outside a method. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class. Instance variables are available to any method bound to an object instance . As a practical matter, this generally gives it scope within some instantiated class object. When an object is allocated in the heap , there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed.

Example

Rules for Instance variable

  1. Instance variables can use any of the four access levels
  2. They can be marked final
  3. They can be marked transient
  4. They cannot be marked abstract
  5. They cannot be marked synchronized
  6. They cannot be marked native
  7. They cannot be marked static

What is a Class Variable

Class variables are declared with keyword static , but outside a method. So, they are also known as static member variables and there's only one copy of that variable is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.

Example

Class Variables are stored in static memory . It is rare to use static variables other than declared final and used as either public or private constants.







net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.