Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compiler not giving error

 
Danish Shaukat
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic