Local and Instance Variables, Part 2 – Intro to Java Programming


The instance variable, form the long term memory of an object. The kind of thing that an object wants to remember for a very long time. The local variables, on the other hand, are the equivalent of the short term memory. You may remember that you had pizza today but you won’t remember it for very long. Whereas you’ll always remember your cat. Technically speaking the local variables go away when you reach the end of the method. The instance variables never go away. They stay alive as long as the object is alive. So when do you want to make a variable an instance variable? You want to do that for those values that an object needs to remember throughout multiple methods. You want to make something a local variable when you can forget about it after exiting the method. In this case here we compute the gas consumed for driving this particular distance, update the gasInTank. And then we no longer care that this was the particular amount of gas consumed. We can safely forget it when we exit the method. That’s why we put this variable inside the method and made it into a local variable.

One thought on “Local and Instance Variables, Part 2 – Intro to Java Programming

Leave a Reply

Your email address will not be published. Required fields are marked *