In this post, we will discus the enhancement being made in Diamond operator in Java 9 release.

Diamond_Operator_Enhacement_Java9_Featured_Image_Techndeck

Check out: Iterate / ofNullable operations in Java 9 Stream

Diamond Operator Enhancement in Java 9...!!! Click To Tweet

In this article, we are going to cover below points:

  1. What is Diamond Operator?
  2. Problem with it in Java 7?
  3. How Java 9 solves that problem? 

Let’s begin:

1. What is Diamond Operator?

It was introduced in Java 7 and it’s purpose is to avoid redundant code and make it more readable by no longer using the generic type on the right side of the expression.

Before Java 7:

Generic type was required to mention on the right side of the expression

Since Java 7:

Generic type was NO LONGER required to mention on the right side of the expression. Instead, now we have ‘Diamond’ <> operator.

2.  Problem with Diamond Operator in Java 7?

Well, as you’ve seen above that how you can use diamond operator BUT it worked for ‘normal’ classes only. If you try to use it for ‘anonymous inner’ classes, then compiler will throw the error message.

Let’s run the below code in Java 7:

Java 7 Error message:

3. How Java 9 solves the problem?

Java 9 improved the diamond operator by allowing diamond operator to be used with anonymous inner classes too. Lets run the same example(Diamond_Operator_Java.java) that we have seen above in Java 9.

It will work completely fine and will generate the below output.

Java 9 Output:

This is one a truly useful addition as part of Java 9. I hope above examples could help you to get better idea on how to implement it.

Diamond Operator Enhancement in Java 9...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: