Syntactic Sugars in Java

Seralahthan
2 min readSep 5, 2021

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 instead of x = x + 1
x -= 1 instead of x = x - 1
  • Increment/Decrement Operators are syntactic sugars of Compound Assignment Operators
x++ instead of x += 1
x-- instead of x -= 1
  • Ternary Operator is a syntactic sugar of If-then-else statements
(condition ? satisfied : 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:

[1] https://en.wikipedia.org/wiki/Syntactic_sugar
[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ConcurrentModificationException.html

Hope this blog helped you to learn some thing new today. Thank you for reading!

Cheers!!!

Originally published at https://serantechexplore.wixsite.com on September 5, 2021.

--

--

Seralahthan

Consultant - Integration & CIAM | ATL@WSO2 | BScEng(Hons) in Computer Engineering | Interested in BigData, ML & AI