Methods

+1 Developer John · November 16, 2014
Lets say I had a method called Eat, and inside it would be an integer called food that would hold a value of 5:
public void Eat(){
int food = 5;
}

Lets also say that I have another method called Print, and what it would do is try to print out the integer:
public void Print(){
System.out.println(food);
}

Why can't I use a variable in a different method?

-Thanks!8-)

Post a Reply

Replies

Oldest  Newest  Rating
+2 Homer Simpson · November 16, 2014
Because variables are only visible within the code block it was declared in.
0 Developer John · November 16, 2014
Thanks!
-1 stian hjornevik · November 16, 2014
this should do the trick

class forYou {
public static void main (String [] args) {
  
  eat a = new eat();
  a.print(a.eat());
}
}
  
  
  class eat {
  public int eat() {
  int food = 5;
  return food;
  }
  
  public void print(int food) {
  System.out.println(food);
  }
}
0 Homer Simpson · November 17, 2014
No problem :D
  • 1

Java / Android Development

107,002 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator