Local variable is redundant JetBrains IDEs (e.g. IntelliJ IDEA)

11,977

Solution 1

Any variable declared inside a method body (between { and }) will be deleted (garbage collection) at the end of that method. (unless you asign it to something which is NOT created in the method body)

You're creating the variable "amount" when you run:

 double amount;

At this point you've created the variable but never assigned a value to it. The first time you use this variable is in your return statement:

return (amount = reader.nextDouble());

What you should've done is either assign the variable on the same line as the declaration:

public static double getAmount(){
    Scanner reader = new Scanner(System.in);
    System.out.println("random text");
    double amount  = reader.nextDouble();
    return amount;
}

Or, better still, don't use the variable at all (although it may improve code readability, in which case a valid point could be made to keep it):

public static double getAmount(){
        Scanner reader = new Scanner(System.in);
        System.out.println("random text");

        return reader.nextDouble();
    }

Why is Intellij warning me?
Intellij is just telling you that in the end your variable isn't being used (it isn't) so it's safe to remove the variable declaration.

Intellij should however also provide you with a solution like I just did if you hover over the little lightbulb which appears at the start of your line of code. An example: enter image description here

Solution 2

It's telling you that you can simply return reader.nextDouble() and that you don't need the variable amount for that purpose.

Solution 3

Because you aren't doing anything with it. The code could be simplified to:

public static double getAmount(){
    Scanner reader = new Scanner(System.in);
    System.out.println("random text");
    return reader.nextDouble();
}

Solution 4

Try turning Inspection Mode off for redundant local variables. Or you can just simply do :

return reader.nextDouble();
Share:
11,977
Stef
Author by

Stef

Updated on June 04, 2022

Comments

  • Stef
    Stef almost 2 years
    public static double getAmount(){
        Scanner reader = new Scanner(System.in);
        System.out.println("random text");
        double amount;
        return (amount = reader.nextDouble());
    }
    

    IntelliJ gives me this warning on the above code:

    Local variable 'amount' is redundant

    Why?

  • gerardw
    gerardw over 5 years
    Or maybe not. Depends on what the Just in Time compiler does with it.
  • ShadyAmoeba
    ShadyAmoeba over 4 years
    Sometimes leaving the variable makes things easier to debug, but to each their own