Difference between field variable and local variable
Answer :
Field variable | Local variable |
Variables that are declared within a class | Variables that are declared within a method or a specific block of statements |
It can be static or non-static | only final is permitted |
If defined as non-static then they are alive as long as the instance of that class is active If defined as static then it gets loaded when class is loaded by Class Loader, and would be removed when it is unloaded | Local variables scope is within the block in which they were defined. |
Local variable Example :
public class LocalVariableScope { public static void main(String[] args) { int x; // known to all code within main x = 10; if (x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x); } }
Instance variable example (Field variable):
public class InstatnceVariable { // member variable - a new instance // of this variable will be created for each // new instance of InstatnceVariable class. // The lifespan of this variable is equal // to the lifespan of "this" instance of InstatnceVariable. int i; }
Static variable example (Field variable):
package com.javahonk.staticTest; public class StaticVariableTest { static int a = 20; static int b; static void methodStaticForTest(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 5; } public static void main(String[] args) { methodStaticForTest(10); } }