both may look identical.The difference is that one of them is outside the method body and one is inside. if you are required to write outside the method then make it in a single statement declaration and initialisation.This cannot be split.
the code below results in a successfull compilation.
class Test { int b=10; public static void main(String args[]){ int b; b=0; } }
Nicholas Jordan
Ranch Hand
Joined: Sep 17, 2006
Posts: 1282
posted
0
Originally posted by hlakkakula hari: hi, ... ( snip ) ... both may look identical.The difference is that one of them is outside the method body and one is inside.
Correctly, where I put it is called a constructor - same meaning as you instruct the original poster.
Dear! you can reinitialize (mind it, instance variables get default values during instantiation) instance variables only in non-static initializer block or in any method including constructor. You never ever ever ever can reinitialize them outside those scopes.
public class Test{ int i; // initialized with b = 0 in this line; float f; // initialized with f = 0.0f in this line; Test t; // initialized with t = null in this line; i = 2; // compilation fails f = 7.5f // compilation fails t = new Test() // compilation fails // no assignent can be possible here { i = 2; // Okay, inside non-static initializer block } public Test(){ i = 2; // Okay, inside constructor } public void setI(int j){ i = j; // Okay, inside method } }
[ August 09, 2008: Message edited by: ARIJIT DARIPA ] [ August 09, 2008: Message edited by: ARIJIT DARIPA ]