Java Arena
Step 4 of 8

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;
    }
}
What javac prints
Main.java:4: error: cannot find symbol
        System.out.println(withTax);
                           ^
  symbol:   variable withTax
  location: class Main
1 error

withTax 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;
    }
}
Output
125.0

The 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.

Your task

Challenge 1 of 3

main tries to use the method's variable total, so the program doesn't compile. Fix main by using the value calculateTotal returns. The program prints:

Total: 7

Challenge 2

main should print the square of 9, but it doesn't compile. Fix the call. The program prints:

81

Challenge 3

A ticket costs whatever ticketPrice() returns. Call it only once, store the price in a variable, and print the price of one, two and three tickets. The program prints:

One ticket: 12
Two tickets: 24
Three tickets: 36