0

Is there a difference in what goes on between these two ways:

public void method() {
    String data;
    Node current = head;

    while(current != null) {
        data = current.getData();
        // Do something with data
        current = current.getNext();
    }
}

and this:

public void method() {
    Node current = head;

    while(current != null) {
        String data = current.getData();
        // Do something with data
        current = current.getNext();
     }
}

I've never had a professor explain this before, and was wondering if there is a difference between the two and which one is "better" to use.

Matthew Brzezinski
  • 1,685
  • 4
  • 29
  • 53

4 Answers4

6

The first definition you have there will make the variable available within the whole method, meaning that all elements inside will be able to access and modify its value. The second definition limits the scope of this variable to inside of the loop.

If you do not intend to use the variable outside of the loop then you might as well just declare it within the loop and keep the scope of that variable contained to that loop. While declaring it outside of the loop will also work, for your purposes, it would not be particularly useful. The benefit of containing it to the loop is that it can only be modified from within, protecting against accidental changes to it later on.

To answer your question though, syntactically speaking, either way is correct and will produce the same functional result in this case.

The Zuidz
  • 678
  • 3
  • 8
  • 18
3

The first one instantiates the variable data, and gives it scope so it can be used outside of the while loop. In the second implementation, data can be used only in the while loop. If you do not plan on using data outside of the while loop, it is suggested that you declare it in the loop. This will protect against any accidental modifications done outside of the loop.

To learn more about the different scopes then visit this link

Marco Corona
  • 812
  • 6
  • 12
0

When you declare variables inside of a loop, you cannot access them anywhere else. If they are defined outside the loop, you can use them within the proper scope. The same goes for variables defined inside of functions, and classes. It's all a matter of the proper scope.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0

If you have code after while loop you cannot acces variable data in second one. Because you declared it in while loop block.

Ugur Artun
  • 1,744
  • 2
  • 23
  • 41