Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 593
Stef Avatar asked Sep 18 '25 19:09

Stef


1 Answers

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

like image 163
Rick van Lieshout Avatar answered Sep 20 '25 08:09

Rick van Lieshout