- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a diamond operator be used with an anonymous inner class in Java 9?
Yes, we can use the diamond operator with an anonymous inner class since Java 9.
The purpose of using a diamond operator is to avoid redundant code and make it more readable by no longer using a generic type on the right side of an expression. The diamond operator used only for normal classes but not for anonymous inner classes in Java 7. If we try to use it for anonymous inner classes, the compiler throws an error.
In the below example, we have used a diamond operator with an anonymous inner class.
Example
import java.util.*; public class DiamondOperatorTest { public static void main(String args[]) { String[] str = {"Raja", "Adithya", "Jai", "Chaitanya", "Vamsi"}; Iterator<String> itr = new Iterator<String>() { // Anonymous inner class int i = 0; public boolean hasNext() { return i < str.length; } public String next() { if(!hasNext()) { throw new NoSuchElementException(); } return str[i++]; } }; while(itr.hasNext()) { System.out.println(itr.next()); } } }
Output
Raja Adithya Jai Chaitanya Vamsi
- Related Articles
- How can we use a diamond operator with anonymous classes in Java 9?
- How to implement an interface using an anonymous inner class in Java?
- How are anonymous (inner) classes used in Java?
- Can an anonymous class have constructors in Java?
- What are anonymous inner classes in Java?
- Can you extend a static inner class in Java?
- What is an Inner class in Java?
- Can a diamond be polished?
- Inner class in Java
- Local inner class in Java
- How to instantiate a static inner class with reflection in Java?
- How many types of anonymous inner classes are defined in Java?
- Can a method local inner class access the local final variables in Java?
- How to implement lambda expression without creating an anonymous class in Java?
- Can a final class be subclassed in Java?

Advertisements