0

The question title is vague, because I don't know how to describe my it.

Given the following code:

String getLargeText() {
    // loads a large text from somewhere
    // and returns it
}

Vecor<String> tokenize(String text) {
    // seperate the text into tokens and
    // return them as a vector of strings
}


public static void main(String[] args) {
    String text = getLargeText();  
    for(String token : tokenize(text)) {
        // some action with 'token'
    }
}

Will the 'tokenize' function in the foreach-loop be called at every iteration, or just once and have its return value be re-used? It looks like the kind of thing which a good compiler would optimize, but I am not sure if java does it. And if the answer to the first question is yes, will

for(volatile String token = tokenize(text)) { ...

supress that behaviour?

Arne
  • 17,706
  • 5
  • 83
  • 99
  • 1
    Why do you think `volatile` would do that? On a local variable no less. – Sotirios Delimanolis Oct 18 '14 at 19:31
  • I haven't used it yet, I figured that that would be how it should be used from this: http://en.wikipedia.org/wiki/Volatile_variable I am currently looking for the duplicate of my question, where is that? The suggested one doesn't address my issue at all. I know how the loop itself works, I want to know how the second argument is called if it isn't a field but a function call. – Arne Oct 18 '14 at 19:40
  • The duplicate explains the equivalent `for` loop to a foreach loop. The `Iterator` is extracted as part of the `for` statement's initialization expression. That expression is evaluated once. – Sotirios Delimanolis Oct 18 '14 at 19:47
  • You are right, my bad – Arne Oct 18 '14 at 19:51

0 Answers0