File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes initialization and if Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "initialization and if" Watch "initialization and if" New topic

initialization and if

Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
What would happen when the following is compiled and executed. Select the one correct answer
public class compare {
public static void main(String args[]) {
int X=10,y;
if(X<10) y=1;<br /> if(X>=10) y=2;
System.out.println("y is "+y);
a. the program compiles and prints y is 0 when executed
b. the program compiles and prints y is 1 when executed
c. the program compiles and prints y is 2 when executed
d. the program does not compile complaining about y not being initialized
e. the program throws a runtime exception
ans :d
I did the code and the answer is d. But y is given value for all (+ve and -ve) values of X. So why compiler complains? Is there anything that I am missing here?
Thanks in advance...
Ravindra Mohan
Ranch Hand

Joined: Mar 16, 2001
Posts: 216
Hi Jini,

Instead if you coded something like

Then the compiler does realise that variable "y" will definately be initialised no matter whatever the condition is evaluated in the if block .
Hope this clears your doubts.
Ravindra Mohan.

[This message has been edited by Ravindra Mohan (edited May 10, 2001).]
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Hi, Jini.
Java is smart to enough to figure out mutual exclusivity in this case:

but not in your case:

Micah Holroyd

Joined: Jan 22, 2001
Posts: 20
If you make the X variable final (see code below), then the compiler knows that X will always be 10 and can figure out that Y will be initialized. In the original code, the compiler can't be absolutely sure of what the value of X will be, so it can't predict whether Y will be initialized or not.
Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
Great...That really helped. Thanks a lot.
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
hi micah

i tried to compile your code with the final modifier but it still does give me a compilation error
Jini Varghese
Ranch Hand

Joined: Dec 06, 2000
Posts: 58
The second one, with final modifier still gives error.
I agree. Here's the link:
subject: initialization and if
It's not a secret anymore!