This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes compiler not giving error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "compiler not giving error" Watch "compiler not giving error" New topic
Author

compiler not giving error

Danish Shaukat
Ranch Hand

Joined: Nov 16, 1999
Posts: 340
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: 59
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
 
GeeCON Prague 2014
 
subject: compiler not giving error