File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

initialization and if

 
Jini Varghese
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 216
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 241
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Jini.
Java is smart to enough to figure out mutual exclusivity in this case:

but not in your case:

Art
 
Micah Holroyd
Greenhorn
Posts: 20
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great...That really helped. Thanks a lot.
 
Samith Nambiar
Ranch Hand
Posts: 147
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi micah

i tried to compile your code with the final modifier but it still does give me a compilation error
regards
Samith.P.Nambiar
 
Jini Varghese
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second one, with final modifier still gives error.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic