aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparision" Watch "Comparision" New topic
Author

Comparision

Manish Singhal
Ranch Hand

Joined: Sep 21, 2000
Posts: 104

Please let me know what is the output of the following code (with explanation...why and how)
public class Compare {
public static void main(String args[]) {
int x = 10, y;
if(x < 10) <br /> y = 1;<br /> if(x>= 10) y = 2;
System.out.println("y is " + y);
}
}

Regards,
Manish Singhal
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Manish,
The code won't compile. 'y' is an instance variable; which are not initialized to any default values. Given the code, we know that 'y' will be initialized at some point but the compiler doesn't; hence the error.
Hope that helps.

------------------
Jane


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
It won't compile. Variables inside methods have to be initialized before you can use them. You can't initialize them inside if blocks because the compiler doesn't know whether or not that if block will execute. If this was a member variable, outside of the method (it would have to be static also since main is a static method) then it would be initialized to 0 and the code would work and give you "y is 2".
Bill
Jon Aryan
Greenhorn

Joined: Oct 06, 2000
Posts: 22
Jane ... "y" is a local variable ... not an instance variable ! ... may be a typo rite ??
Aryan.
Manish Singhal
Ranch Hand

Joined: Sep 21, 2000
Posts: 104

Thanks to all of you.
I knew that we have to initialize local variable before using it but was confused and thought that " if " construct will initialize it.
regards,
Manish
Stephen Pride
Ranch Hand

Joined: Sep 14, 2000
Posts: 121
But ... If the code were this instead:

Then it will compile without any errors. So even though "y" was not initially initialized, the compiler "knows" it will be before it is used.
Regards,
SP


SCJP
Manish Singhal
Ranch Hand

Joined: Sep 21, 2000
Posts: 104

Thanks Stephen
regards,
Manish
Bin Zhao
Ranch Hand

Joined: Oct 04, 2000
Posts: 73
So,the compiler is so smart that it can judge whether y can be
initialized.But if in another situation,how can we judge if the compiler can make correct decision?
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi John ...
You're right ... and I knew that when I posted! Thanks for correcting my mistake
------------------
Jane
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparision