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 Programmer Certification (SCJP/OCPJP) and the fly likes properly initialized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "properly initialized" Watch "properly initialized" New topic
Author

properly initialized

Albertina Gonzalez
Greenhorn

Joined: Apr 23, 2002
Posts: 11
Look the code
public class a {
public static void main(String args[]) {
int x = 10, y;
if(x<10)
y = 1;
if(x>= 10)
y = 2;

System.out.println("El valor de y es" + y);
}}
I dont understand why there is compile error, if x = 10 and come in the second if and y is initialized with 2
Why don�t recognized y = 2???
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
The compiler is stupid, basically. It will not realize that all possibilities ensure that y will be initialized. However, if you replace the second if with an else, the program will compile and run.
Just to be on the safe side, make it a habit of initializing all local variables at the onset.
Chad McGowan
Ranch Hand

Joined: May 10, 2001
Posts: 265
the compiler is ensuring that y is initialized. Since the value of x could change, there is no guarantee(to the compiler) that y is initialized. If you initialize y = 0, this will compile and run.
Line 1 in main()
int x = 10, y = 0;
Albertina Gonzalez
Greenhorn

Joined: Apr 23, 2002
Posts: 11
Thanks, that sounds trip cuestion. I know, is the best way to make it a habit of initializing all local variables at the onset. But the exam have trip/traps
Thank you very much
 
GeeCON Prague 2014
 
subject: properly initialized