Skip to content
Advertisement

Can I use value of a local variable defined in a method, in other method in Java?

The method is not returning the value of the local variable.

Can I use the value of local variable index from the following method

JavaScript

in this method as the index of the array of the object that I want to remove.

JavaScript

I know the scope of a local variable is limited to the method it’s declared in. But there might be a way that I might not now yet to make this happen without using a field/instance variable.

Advertisement

Answer

No. The whole point of it being local to a method is that it only exists within that method. The options are:

  • Use an instance field, i.e. make it part of the state of the object. That’s unlikely to be appropriate.
  • Use a static field, i.e. make it part of the static of the type. That’s almost certainly inappropriate.
  • Change the existing method to return the information you want.
  • Create a new method to return the information you want.
  • Duplicate the existing code within remove so that you can get the index. That would be sad 🙁

As an example of the last two, you could write:

JavaScript

… then in your remove method, you’d use indexOf instead of contains.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement