Java Generics
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity.
Types of Java Generics
Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
Generic Functions: We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.
Java
// Java program to show working of user defined // Generic functions class Test { // A Generic method example static <T> void genericDisplay(T element) { System.out.println(element.getClass().getName() + " = " + element); } // Driver method public static void main(String[] args) { // Calling generic method with Integer argument genericDisplay( 11 ); // Calling generic method with String argument genericDisplay( "w3wiki" ); // Calling generic method with double argument genericDisplay( 1.0 ); } } |
java.lang.Integer = 11 java.lang.String = w3wiki java.lang.Double = 1.0
Java Cheat Sheet
Java is a programming language and platform that has been widely used since its development by James Gosling in 1982. It follows the Object-oriented Programming concept and can run programs written in any programming language. Java is a high-level, object-oriented, secure, robust, platform-independent, multithreaded, and portable programming language All those words are collectively called Java Buzzwords. It is commonly used for programming web-based, window, enterprise, and mobile applications. This Java Cheat Sheet article has been written by experts in Java and based on the experience of students who have recently undergone Java interviews.
This Core Java Cheat Sheet has been designed by Java experts, based on the experience of students who have recently undergone Java interviews. Whether you are a beginner or an experienced Java developer, this Java Cheat Sheet is a valuable resource for quickly accessing essential syntax, concepts, and best practices related to Java Programming.