Variables inside methods
A variable made inside a method belongs to that method: it's a local variable. It exists while the method runs and disappears when the method ends. Other methods can't see it, not even main. The same goes for parameters.
public class Main {
public static void main(String[] args) {
addTax(100);
System.out.println(withTax);
}
public static double addTax(double price) {
double withTax = price * 1.25;
return withTax;
}
}
Main.java:4: error: cannot find symbol
System.out.println(withTax);
^
symbol: variable withTax
location: class Main
1 errorwithTax lives only inside addTax. To get its value out, use the return value: store what the call returns in a variable of main's own.
public class Main {
public static void main(String[] args) {
double withTax = addTax(100);
System.out.println(withTax);
}
public static double addTax(double price) {
double withTax = price * 1.25;
return withTax;
}
}
125.0The two withTax variables are different variables that happen to share a name, one in each method.
Another mistake gives the same cannot find symbol error: using a method's name without the parentheses and arguments, as square instead of square(5). Without them, Java looks for a variable called square.