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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "LOCAL VARIABLE" Watch "LOCAL VARIABLE" New topic
Author

LOCAL VARIABLE

Jaya Murugan
Ranch Hand

Joined: Nov 18, 2000
Posts: 34
=========================================
public class test1{
public static void main(String args[]){
int x =10;
int y;
if(x > 5) y =0
System.out.println("y"+y);
}
}
==========================================
public class test2{
public static void main(String args[]){
int x =10;
int y;
if(x > 5) y =0
else y = 1;
System.out.println("y"+y);
}
}
=================================
test1 says the variable is not initialised.
test2 works fine.
i dont know why???
pls help........regards......Jaya Murugan
ppathak
Greenhorn

Joined: Jul 06, 2000
Posts: 19
Hi Jaya,
well my understanding is:

u get error during compile time, the compiler understands as follows:
variable x is present & it has some value,
variable y(which is not assigned any value).
then comes to print statement, here u r using y, which is not assigned any value, so it pops up that error. if u just declare y, but dont use it i.e put u'r print statement in comments then u will not get error
java is designed in that way, if it were c or something may be u get a segmentation fault or some junk value.
hope this helps
-Preeti Pathak
Sahir Shah
Ranch Hand

Joined: Nov 05, 2000
Posts: 158
Jaya,
Please read the comments.
</pre>
public class test1{
public static void main(String args[]){
int x =10;
int y; // this variable has not been initilaised
if(x > 5)
y =0; // this is a conditional statement
// if it evaluates to true y is initialised

System.out.println("y"+y); // Hence there is no guarantee that when this runs y has been initialised
}
}
</pre>
Local variables are not automatically initialised to a default value. And you are not allowed to use variables before they are initialised.
Rgds
Sahir


[This message has been edited by Sahir Shah (edited November 19, 2000).]


....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: LOCAL VARIABLE