1

This is a question about java local variables (Following code in the same method)

boolean userWantsToSave;
userWantsToSave = true;

Eclipse throws The value of the local variable userWantsToSave is not used, my question is why?

Since the variable is assigned true, why is it still not used?

4
  • 5
    Assigning a variable and never reading it is not using it. Eclipse is correct. Commented Nov 25, 2014 at 22:47
  • you'd have to use the variable if you wanted that to go away. like if(userWantsToSave){//doSomeCrazyStuff} Commented Nov 25, 2014 at 22:48
  • add a System.out.println(userWantsToSave); for example and the warning will disappear, i.e. use the variable, in this case just printing its value to the console. Commented Nov 25, 2014 at 22:49
  • 1
    Think of a variable as a parking space for a value of some kind. The assignment says what should be in the parking space. But even if you've got a car in your parking space, you haven't used it yet. Commented Nov 25, 2014 at 23:46

3 Answers 3

2

You assigned a value to it, but you never used the value of usertWantsToSave

if(usertWantsToSave){ // You read the value of usertWantsToSave. You used it
   save();
}
Sign up to request clarification or add additional context in comments.

Comments

2

Just use it in a if (userWantsToSave) or something else. Using is reading the variable somewhere. Assigning a value is just that, it is not used because of that.

3 Comments

Why is if (userWantsToSave = true) not a use of the variable?
Because if you removed it the program would still be the same. That line makes no difference to the program at all.
@user2177940 userWantsToSave = true is assignment, use == to compaire.
1

Let me give you a real world example: lets say a parent x have two kids names a and b and x had got two sweets from market. Now x will give one sweet each to his/her kids. "This is just assignment" but both of these a and b have not eaten those sweets. "That's where it's not used"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.