Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

LOCAL VARIABLE

 
Jaya Murugan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
=========================================
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic