What are Syntactic Sugars?
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
A construct in a language is "syntactic sugar" if it can be removed from the language without any effect on what the language can do: "functionality" and "expressive" power will remain the same.
Following are some of the syntactic sugars used in JAVA programming languages,
Compound Assignment Operators are syntactic sugars of Assignment Operators ( x += 1 and x -= 1 instead of x = x + 1 and x = x - 1)
Increment/Decrement Operators are syntactic sugars of Compound Assignment Operators ( x++ and x-- instead of x += 1 and x -= 1)
Ternary Operator is a syntactic sugar of If-then-else statements (condition ? statisfied : otherwise)
Enhanced For Loop is a syntactic sugar of For Loop with an Iterator
The above for-each loop is a syntactic sugar for the following for loop with iterator
Note:
Language processors, including compilers and static analyzers, often expand sugared constructs into more fundamental constructs before processing, a process sometimes called "de-sugaring".
For example, enhanced for loop will be de-sugared to a for loop with iterator at compile time.
Syntactic Sugars and Runtime Exceptions
It is important to understand the sugaring and de-sugaring as sugared constructs throw certain runtime exceptions based on their de-sugared constructs.
Example,
Enhanced For loop throws a java.util.ConcurrentModificationException when removing an element from a Collection using the Collection remove( ) method while iterating over the Collection.
While the generic for loop with counter doesn't throw a java.util.ConcurrentModificationException when removing an element from a Collection (using the Collection remove( ) method) while iterating over the Collection.
This is because at the compile time, enhanced for loop is de-sugared into a generic for loop with fail-fast iterator. Fail-fast iterator throws a java.util.ConcurrentModificationException when removing an element from a Collection (using the Collection remove( ) method) while iterating over the Collection.
References:
Hope this blog helped you to learn some thing new today. Thank you for reading!
Cheers!!!
Thank You for sharing such an informative blog with us. I highly appreciate the information shared by you. Students looking for javascript assignment help canada then they must try My Assignment Services. Its an online assignment writing platform which give students academic support at very affordable prices. During my masters in University of Toronto. I took assistance from their experts to achieve my academic goals.