| Author |
compiler not giving error
|
Danish Shaukat
Ranch Hand
Joined: Nov 16, 1999
Posts: 337
|
|
Hi folks ! I read that if variables are not initialized and used in a calculation the compiler gives an error, but when i run the program i get answer 55. why i'm not getting an error ??? The variables a and c do have junk values but i did not assign them values. public class Foo { private static int a,b=55,c; public static void main(String[] ards) { c=a+b; System.out.println("Answer is..."+c); } } Danish.
|
 |
Aniruddha Mukhopadhyay
Ranch Hand
Joined: Nov 15, 2000
Posts: 58
|
|
You are not getting error because a and c are intialised with default value "0". Automatic initialization will happen for object variables but not for local variables (i.e. variables declared inside a method). I have changed your code to illustrate the above: public class Foo { private static int a,b=55,c; public static void main(String[] ards) { c=a+b; System.out.println("Answer is..."+c); Foo newFoo = new Foo(); newFoo.methodTest(); } void methodTest(){ //int a1,b1=555,c1; commented out as wont compile with this int a1=0,b1=555,c1=0; // // these are local variables, so need initialization c1=a1+b1; System.out.println("Answer is..."+c1); } } [ October 24, 2002: Message edited by: aniruddha mukhopadhyay ]
|
Aniruddha
|
 |
 |
|
|
subject: compiler not giving error
|
|
|