Showing posts with label field. Show all posts
Showing posts with label field. Show all posts

Sunday, 15 May 2011

Difference between fields and local variables

There are few difference between fields and local variables. Fields are defined in the class, whereas local variables are local to the methods. The big difference comes in case of initialization.
You must always explicitly initialize local variables in a method. But if you don't initialize a field in a class, it is automatically initialized to a default (0, false, or null).

Default Field Initialization in java

If you don't set a field explicitly in a constructor, it is automatically set to a default value: numbers to 0, Booleans to false, and object references to null. But it is considered poor programming practice to rely on this. Certainly, it makes it harder for someone to understand your code if fields are being initialized invisibly.
See difference between field variables and local variables.