What is syntax sugar and how does it work?

10

I have seen in some blogs the use of this term and would like to know:

1) The real meaning of this expression e;

2) How does a syntax work like the example below in ?

for (Foo foo : listFoo) {
    //CÓDIGO AQUI
}
    
asked by anonymous 15.04.2014 / 03:01

2 answers

13

Syntax sugar is a type of construction made to "sweeten" the code, that is, to do something simpler.

Considering your for-each example. Before Java 5, the new "sweet" construction and the introduction of generic in language, here is an equivalent code:

for (Iterator i = listFoo.iterator(); i.hasNext(); ) {
    Foo foo = (Foo) i.next();    
    // CÓDIGO AQUI
}

The version with for-each is certainly simpler and less susceptible to crashes.

Sources:

15.04.2014 / 03:13
8
  In computer science, syntactic sugar is the syntax within a programming language that was designed to make things easier to read or express. This makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

Translated from: link

This for iterates over all elements of listFoo , placing at each iteration the current element within the foo variable.

    
15.04.2014 / 03:05