SlideShare a Scribd company logo
Java Generics
Handled By
Dr.T.Abirami
Associate Professor
Department of IT
Kongu Engineering College Perundurai
Generics
• Generics means parameterized data types.
• The idea is to allow data 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.
generics
• JDK 5 introduces generics, which
supports abstraction over
types (or parameterized types) on classes and
methods.
• The class or method designers can be generic
about types in the definition, while the users are
to provide the specific types (actual type) during
the object instantiation or method invocation.
• The primary usage of generics is to abstract over
types for the Collection Framework.
• Auto-Boxing/Unboxing between Primitives and
their Wrapper Objects
Generics
• Generics helps to create classes, interfaces, and
methods that can be used with different types of
objects (data). Hence, allows us to reuse our
code.
• Note: Generics does not work with primitive
types (int, float, char, etc).
• Generics is used in Java, we can use the ArrayList
class of the Java collections framework.
• ArrayList class is an example of a generics class.
We can use ArrayList to store data of any type.
Generic Programming
• Generics helps to create classes, interfaces,
and methods that can be used with different
data types of objects (data). Hence, allows us
to reuse our code.
• Note: Generics does not work with primitive
types (int, float, char, etc).
Advantages
• Type-safety : We can hold only a single type of
objects in generics. It doesn’t allow to store other
objects.
• Type casting is not required: There is no need to
typecast the object.
• Compile-Time Checking: It is checked at compile
time so problem will not occur at runtime. The
good programming strategy says it is far better to
handle the problem at compile time than
runtime.
Types of Java Generics
• Generic Type Class
• Generic Interface
• Generic Method
• Generic Constructor
Syntax for generics
Class classname <data_type_variable>
{ }
Generic class:
Generic method:
class Demo
{
<data_type_ variable> return_ data _type method_name ()
{
}
}
Generic Class
• A class is said to be Generic if it declares one or
more type variables. These variable types are
known as the type parameters of the Java Class.
• we use <> to specify parameter types in generic
class creation.
• Generics Work Only with Objects
Syntax for creating an Object of a Generic type
Class_name <data type> reference_name = new
Class_name<data type> ();
(OR)
Class_name <data type> reference_name = new
Class_name<>();
Generic Class
example
class Test<T>
{ T a;
T b;
Test(T x, T y)
{
a=x;
b=y;
}
}
public class Main
{
public static void main(String[] args) {
Test<Integer> obj=new Test<Integer>(2,3);
System.out.println(obj.a+obj.b);
}
}
//addition of two numbers using generic class
class Test <T>
{ T a;
T b;
//generic cons....
Test(T x, T y)
{
a=x;
b=y;
}
//generic method
T get()
{
return a;
}
}
class Main {
public static void main(String[] args) {
Test<Integer> obj = new Test<Integer>(34,23);
System.out.println(obj.a+obj.b);
System.out.println(obj.get());
Test<Float> obj1 = new Test<Float>(34.1f,23.3f);
System.out.println(obj1.a+obj1.b);
System.out.println(obj1.get());
}
}
class Main {
public static void main(String[] args) {
// initialize generic class with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
// initialize generic class with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
} class GenericsClass<T> {
// variable of T type
private T data;
public GenericsClass(T data) {
this.data = data;
}
// method that return T type variable
public T getData() {
return this.data;
}
}
Output
Generic Class returns: 5
Generic Class returns:
Java Programing
• T indicates the type parameter. Inside the
Main class, we have created objects of
GenericsClass named intObj and stringObj.
• While creating intObj, the type parameter T is
replaced by Integer. This means intObj uses
the GenericsClass to work with integer data.
• While creating stringObj, the type parameter T
is replaced by String. This means stringObj
uses the GenericsClass to work with string
data.
Generics Methods Rules
• In passing arguments into methods, You place the arguments inside
the round bracket () and pass them into the method.
• In generics, instead of passing arguments, we pass type
information inside the angle brackets <>.
• All generic method declarations have a data type parameter section
by angle parameter
Example: <E>
• Each type parameter section contains one or more type parameters
separated by commas
• Example: <E1,T> void disp(E1 a, T b)
Syntax:
<type-parameter> return_type method_name (parameters) {...}
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
For-each Loop
Syntax:
for(data_type variable : array | collection)
{
//body of for-each loop
}
Example:
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Generics Methods
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
demo.<String>genericsMethod("Java Programming");
}
}
class DemoClass {
// generics method
public <T> void genericsMethod(T data) {
System.out.println("This is a generics method.");
System.out.println("The data passed to method is " + data);
}
}
• public <T> void genericMethod(T data) {...} Here,
the type parameter <T> is inserted after the
modifier (public) and before the return type
(void).
• We can call the generics method by placing the
actual type <String> inside the bracket before the
method name.
• demo.<String>genericMethod("Java
Programming"); Note: In most cases, we can omit
the type parameter while calling the generics
method. It is because the compiler can match the
type parameter using the value passed to the
method. For example,
• demo.genericsMethod("Java Programming");
Generic Constructor
class sample
{
Object a;
<T> sample(T b)
{
a=b;
}
void disp(){
System.out.println(a);
}
}
public class Generic1 {
public static void main(String ar[]){
sample s=new sample(“Hi");
sample s=new sample(‘A’);
sample s=new sample(4);
sample s=new sample(5.4);
s.disp();
}
}
Generic Constructor
class sample
{
<T> sample(T x,T y)
{
System.out.println(x);
System.out.println(y);
}
}
public class Generic2 {
public static void main(String ar[]){
sample s=new sample(2,4);
}
}
Generic Type with more than one parameter
public class Generic4 {
<E,T> void disp(E a, T b){
System.out.println(a);
System.out.println(b);
}
public static void main(String ar[]){
Generic4 g=new Generic4();
g.disp(4,6.5);
g.disp(4.5,5);
}
}
Generic Method
Generic Method
class sample{
< E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
}
}
public class Generic3{
public static void main( String args[] ) {
sample s=new sample();
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'E', 'N', 'G', 'I', 'N','E','E','R','I','N','G' };
System.out.println( "Printing Integer Array" );
s.printArray(intArray);
System.out.println( "Printing Character Array" );
s.printArray(charArray);
}
}
class sample<G>
{
G obj;
sample(G a){
obj=a;
}
void disp(){
System.out.println(obj);
}
}
public class Generic7{
public static void main(String ar[]){
sample <Integer> s=new sample<Integer>(15);
s.disp();
sample <String> s1=new sample<String>(“Fox");
s1.disp();
}
Generic Class
class sample<G, T>{
G obj1;
T obj2;
sample(G a, T b){
obj1=a;
obj2=b;
}
void disp(){
System.out.println(obj1+" "+obj2);
}
}
public class Generic8{
public static void main(String ar[]){
sample <Integer, String> s=new sample<Integer, String> (15,“Kongu");
s.disp();
sample <String,Integer> s1=new sample<String,Integer>(“Kongu
eng",20);
s1.disp();
Generic Class
class twogen<T,V>{
T obj1;
V obj2;
twogen(T o1,V o2) {
obj1=o1;
obj2=o2;
}
T getobj1() {
return obj1;
}
V getobj2() {
return obj2;
}
void showType() {
System.out.println("type is" + obj1.getClass().getName());
System.out.println("type is" + obj2.getClass().getName());
}}
public class Generic11{
public static void main(String args[]) {
twogen<Integer,String> tobj=new twogen<Integer,String>(99,"kec");
tobj.showType();
int v=tobj.getobj1();
String u=tobj.getobj2();
System.out.println("u="+u+" "+"v="+v);
}}
Generic Class
Ans:
type isjava.lang.Integer
type isjava.lang.String
u=kec v=99
class constructors{
<T extends Number>int showval(T a, T b){
return (a.intValue()+b.intValue());
}}
class Generic15{
public static void main(String r[]){
constructors s=new constructors();
int sum=s.showval(10,20);
System.out.println(sum);
}}
Generic Type addition
class constructors{
int a;
<T extends Number>constructors(T x){
a=x.intValue();
}
void showval(int b){
int sum=a+b;
System.out.println("sum:"+sum);
}}
class Generic14{
public static void main(String r[]){
constructors s1=new constructors(10);
constructors s2=new constructors(12.3F);
s1.showval(9);
s2.showval(10);
}}
Generic Type
addition
class sample
{
static <T extends Number>
void add (T a, T b)
{
System.out.println(b.doubleValue()+a.doubleValue());
}
public static void main(String aa[])
{
Integer a=8, b=10;
add(a,b);
Float c=12.5f,d=45.5f;
add(c,d);
Double e=12.5,f=45.5;
add(e,f);
}}
Generic Type addition
Generic Interface
interface I1<T>
{
void disp(T a);
}
class sample <T>implements I1<T>
{
public void disp(T a)
{
System.out.println(a);
}}
public class Generic5 {
public static void main(String ar[])
{
sample <Integer>s=new sample<Integer>();
s.disp(5);
sample <Double>s1=new sample<Double>();
s1.disp(5.4);
If we using 2 parameter in the
inherited class
class sam <T,U> implements I1<T>
class sample1<T>{
void disp(T a){
System.out.println(a);
}
}
class sample2<T> extends sample1<T>{
void disp(T a){
System.out.println("Derived"+a);
}
}
public class Generic10 {
public static void main(String ar[]){
sample1<Integer> s1=new sample1<Integer>();
s1.disp(4);
sample1<Double> s2=new sample2<Double>();
s2.disp(5.2);
}
}
class general{
int num;
general(int i){
num=i;
}
int get(){
return num;
}}
class Gen<T>extends general{
T obj;
Gen(T o,int i){
super(i);
obj=o;
}
T getobj(){
return obj;
}
void show(){
System.out.println("base class...");
}}
Generic Class Hierarchies
Contd…
class gen2<T,V> extends Gen<T>{
V obj1;
gen2(T o, V s,int i){
super(o,i);
obj1=s;
}
V getobj2(){
return obj1;
}
void show(){
super.show();
System.out.println("subclass...");
}}
public class Generic16{
public static void main(String r[]) {
gen2<Integer,String> is=new gen2<Integer,String>(100,"java",100);
System.out.println("String:"+is.getobj2());
System.out.println("value:"+is.getobj());
System.out.println("nongeneric value:"+is.get());
is.show();
}}
Generic Class Hierarchies
Wildcards in Java
• The ? (question mark) symbol represents the
wildcard element.
• It means any type.
• If we write <? extends Number>, it means any
child class of Number, e.g., Integer, Float, and
double.
• Now we can call the method of Number class
through any child class object.
Wildcards in Java
• The question mark (?) is known as the wildcard
in generic programming .
• It represents an unknown type.
• We can use a wildcard as a type of a parameter,
field, return type, or local variable.
• However, it is not allowed to use a wildcard as a
type argument for a generic method invocation,
a generic class instance creation, or a
supertype.
class Gen<T>{
T obj;
Gen(T o) {
obj=o;
}
T getobj() {
return obj;
}}
class rawtype{
public static void main(String r[]){
Gen<Integer>o1=new Gen<Integer>(100);
Gen<String>o2=new Gen<String>("java");
//int v=o1.getobj();
System.out.println("Value:"+o1.getobj());
//String s=o2.getobj();
System.out.println("String:"+o2.getobj());
Gen raw=new Gen(new Double(100.0));
double d=(Double)raw.getobj();
System.out.println("raw value:"+d);

More Related Content

What's hot

5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
java collections
java collectionsjava collections
java collections
javeed_mhd
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
André Faria Gomes
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 

What's hot (20)

5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
07 java collection
07 java collection07 java collection
07 java collection
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
java collections
java collectionsjava collections
java collections
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Java collections
Java collectionsJava collections
Java collections
 

Similar to Generics

GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
Virat10366
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
anshu_atri
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
cbeproject centercoimbatore
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
 
Wrapper classes
Wrapper classes Wrapper classes
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
Muhammad Alhalaby
 
core java
 core java core java
core java
dssreenath
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
MSohaib24
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 
Templates
TemplatesTemplates
Java
Java Java
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
jagriti srivastava
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 

Similar to Generics (20)

GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
core java
 core java core java
core java
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Templates
TemplatesTemplates
Templates
 
Java
Java Java
Java
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 

More from Kongu Engineering College, Perundurai, Erode

Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
Kongu Engineering College, Perundurai, Erode
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
Kongu Engineering College, Perundurai, Erode
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
Kongu Engineering College, Perundurai, Erode
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
Kongu Engineering College, Perundurai, Erode
 
Dimensions of elements.pdf
Dimensions of elements.pdfDimensions of elements.pdf
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
Kongu Engineering College, Perundurai, Erode
 
Random number generation_upload.pdf
Random number generation_upload.pdfRandom number generation_upload.pdf
Random number generation_upload.pdf
Kongu Engineering College, Perundurai, Erode
 
JavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdfJavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdf
Kongu Engineering College, Perundurai, Erode
 
Computer Networks: Quality of service
Computer Networks: Quality of serviceComputer Networks: Quality of service
Computer Networks: Quality of service
Kongu Engineering College, Perundurai, Erode
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Kongu Engineering College, Perundurai, Erode
 
Transport layer services
Transport layer servicesTransport layer services

More from Kongu Engineering College, Perundurai, Erode (20)

Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Chapter 3.pdf
 
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
 
Dropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdfDropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdf
 
div tag.pdf
div tag.pdfdiv tag.pdf
div tag.pdf
 
Dimensions of elements.pdf
Dimensions of elements.pdfDimensions of elements.pdf
Dimensions of elements.pdf
 
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
 
Random number generation_upload.pdf
Random number generation_upload.pdfRandom number generation_upload.pdf
Random number generation_upload.pdf
 
JavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdfJavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdf
 
Computer Networks: Quality of service
Computer Networks: Quality of serviceComputer Networks: Quality of service
Computer Networks: Quality of service
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 

Recently uploaded

Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
ssuser9bd3ba
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

Generics

  • 1. Java Generics Handled By Dr.T.Abirami Associate Professor Department of IT Kongu Engineering College Perundurai
  • 2. Generics • Generics means parameterized data types. • The idea is to allow data 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.
  • 3. generics • JDK 5 introduces generics, which supports abstraction over types (or parameterized types) on classes and methods. • The class or method designers can be generic about types in the definition, while the users are to provide the specific types (actual type) during the object instantiation or method invocation.
  • 4. • The primary usage of generics is to abstract over types for the Collection Framework. • Auto-Boxing/Unboxing between Primitives and their Wrapper Objects
  • 5. Generics • Generics helps to create classes, interfaces, and methods that can be used with different types of objects (data). Hence, allows us to reuse our code. • Note: Generics does not work with primitive types (int, float, char, etc). • Generics is used in Java, we can use the ArrayList class of the Java collections framework. • ArrayList class is an example of a generics class. We can use ArrayList to store data of any type.
  • 6. Generic Programming • Generics helps to create classes, interfaces, and methods that can be used with different data types of objects (data). Hence, allows us to reuse our code. • Note: Generics does not work with primitive types (int, float, char, etc).
  • 7. Advantages • Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects. • Type casting is not required: There is no need to typecast the object. • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
  • 8. Types of Java Generics • Generic Type Class • Generic Interface • Generic Method • Generic Constructor
  • 9. Syntax for generics Class classname <data_type_variable> { } Generic class: Generic method: class Demo { <data_type_ variable> return_ data _type method_name () { } }
  • 10. Generic Class • A class is said to be Generic if it declares one or more type variables. These variable types are known as the type parameters of the Java Class. • we use <> to specify parameter types in generic class creation. • Generics Work Only with Objects
  • 11. Syntax for creating an Object of a Generic type Class_name <data type> reference_name = new Class_name<data type> (); (OR) Class_name <data type> reference_name = new Class_name<>(); Generic Class
  • 12. example class Test<T> { T a; T b; Test(T x, T y) { a=x; b=y; } } public class Main { public static void main(String[] args) { Test<Integer> obj=new Test<Integer>(2,3); System.out.println(obj.a+obj.b); } }
  • 13. //addition of two numbers using generic class class Test <T> { T a; T b; //generic cons.... Test(T x, T y) { a=x; b=y; } //generic method T get() { return a; } } class Main { public static void main(String[] args) { Test<Integer> obj = new Test<Integer>(34,23); System.out.println(obj.a+obj.b); System.out.println(obj.get()); Test<Float> obj1 = new Test<Float>(34.1f,23.3f); System.out.println(obj1.a+obj1.b); System.out.println(obj1.get()); } }
  • 14. class Main { public static void main(String[] args) { // initialize generic class with Integer data GenericsClass<Integer> intObj = new GenericsClass<>(5); System.out.println("Generic Class returns: " + intObj.getData()); // initialize generic class with String data GenericsClass<String> stringObj = new GenericsClass<>("Java Programming"); System.out.println("Generic Class returns: " + stringObj.getData()); } } class GenericsClass<T> { // variable of T type private T data; public GenericsClass(T data) { this.data = data; } // method that return T type variable public T getData() { return this.data; } } Output Generic Class returns: 5 Generic Class returns: Java Programing
  • 15. • T indicates the type parameter. Inside the Main class, we have created objects of GenericsClass named intObj and stringObj. • While creating intObj, the type parameter T is replaced by Integer. This means intObj uses the GenericsClass to work with integer data. • While creating stringObj, the type parameter T is replaced by String. This means stringObj uses the GenericsClass to work with string data.
  • 16. Generics Methods Rules • In passing arguments into methods, You place the arguments inside the round bracket () and pass them into the method. • In generics, instead of passing arguments, we pass type information inside the angle brackets <>. • All generic method declarations have a data type parameter section by angle parameter Example: <E> • Each type parameter section contains one or more type parameters separated by commas • Example: <E1,T> void disp(E1 a, T b) Syntax: <type-parameter> return_type method_name (parameters) {...}
  • 17. public class TestGenerics4{ public static < E > void printArray(E[] elements) { for ( E element : elements){ System.out.println(element ); } System.out.println(); } public static void main( String args[] ) { Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' }; System.out.println( "Printing Integer Array" ); printArray( intArray ); System.out.println( "Printing Character Array" ); printArray( charArray ); } }
  • 18. For-each Loop Syntax: for(data_type variable : array | collection) { //body of for-each loop } Example: class ForEachExample1{ public static void main(String args[]){ //declaring an array int arr[]={12,13,14,44}; //traversing the array with for-each loop for(int i:arr){ System.out.println(i); } } }
  • 19. Generics Methods class Main { public static void main(String[] args) { // initialize the class with Integer data DemoClass demo = new DemoClass(); demo.<String>genericsMethod("Java Programming"); } } class DemoClass { // generics method public <T> void genericsMethod(T data) { System.out.println("This is a generics method."); System.out.println("The data passed to method is " + data); } }
  • 20. • public <T> void genericMethod(T data) {...} Here, the type parameter <T> is inserted after the modifier (public) and before the return type (void). • We can call the generics method by placing the actual type <String> inside the bracket before the method name. • demo.<String>genericMethod("Java Programming"); Note: In most cases, we can omit the type parameter while calling the generics method. It is because the compiler can match the type parameter using the value passed to the method. For example, • demo.genericsMethod("Java Programming");
  • 21. Generic Constructor class sample { Object a; <T> sample(T b) { a=b; } void disp(){ System.out.println(a); } } public class Generic1 { public static void main(String ar[]){ sample s=new sample(“Hi"); sample s=new sample(‘A’); sample s=new sample(4); sample s=new sample(5.4); s.disp(); } }
  • 22. Generic Constructor class sample { <T> sample(T x,T y) { System.out.println(x); System.out.println(y); } } public class Generic2 { public static void main(String ar[]){ sample s=new sample(2,4); } } Generic Type with more than one parameter
  • 23. public class Generic4 { <E,T> void disp(E a, T b){ System.out.println(a); System.out.println(b); } public static void main(String ar[]){ Generic4 g=new Generic4(); g.disp(4,6.5); g.disp(4.5,5); } } Generic Method
  • 24. Generic Method class sample{ < E > void printArray(E[] elements) { for ( E element : elements){ System.out.println(element ); } } } public class Generic3{ public static void main( String args[] ) { sample s=new sample(); Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'E', 'N', 'G', 'I', 'N','E','E','R','I','N','G' }; System.out.println( "Printing Integer Array" ); s.printArray(intArray); System.out.println( "Printing Character Array" ); s.printArray(charArray); } }
  • 25. class sample<G> { G obj; sample(G a){ obj=a; } void disp(){ System.out.println(obj); } } public class Generic7{ public static void main(String ar[]){ sample <Integer> s=new sample<Integer>(15); s.disp(); sample <String> s1=new sample<String>(“Fox"); s1.disp(); } Generic Class
  • 26. class sample<G, T>{ G obj1; T obj2; sample(G a, T b){ obj1=a; obj2=b; } void disp(){ System.out.println(obj1+" "+obj2); } } public class Generic8{ public static void main(String ar[]){ sample <Integer, String> s=new sample<Integer, String> (15,“Kongu"); s.disp(); sample <String,Integer> s1=new sample<String,Integer>(“Kongu eng",20); s1.disp(); Generic Class
  • 27. class twogen<T,V>{ T obj1; V obj2; twogen(T o1,V o2) { obj1=o1; obj2=o2; } T getobj1() { return obj1; } V getobj2() { return obj2; } void showType() { System.out.println("type is" + obj1.getClass().getName()); System.out.println("type is" + obj2.getClass().getName()); }} public class Generic11{ public static void main(String args[]) { twogen<Integer,String> tobj=new twogen<Integer,String>(99,"kec"); tobj.showType(); int v=tobj.getobj1(); String u=tobj.getobj2(); System.out.println("u="+u+" "+"v="+v); }} Generic Class Ans: type isjava.lang.Integer type isjava.lang.String u=kec v=99
  • 28. class constructors{ <T extends Number>int showval(T a, T b){ return (a.intValue()+b.intValue()); }} class Generic15{ public static void main(String r[]){ constructors s=new constructors(); int sum=s.showval(10,20); System.out.println(sum); }} Generic Type addition
  • 29. class constructors{ int a; <T extends Number>constructors(T x){ a=x.intValue(); } void showval(int b){ int sum=a+b; System.out.println("sum:"+sum); }} class Generic14{ public static void main(String r[]){ constructors s1=new constructors(10); constructors s2=new constructors(12.3F); s1.showval(9); s2.showval(10); }} Generic Type addition
  • 30. class sample { static <T extends Number> void add (T a, T b) { System.out.println(b.doubleValue()+a.doubleValue()); } public static void main(String aa[]) { Integer a=8, b=10; add(a,b); Float c=12.5f,d=45.5f; add(c,d); Double e=12.5,f=45.5; add(e,f); }} Generic Type addition
  • 31. Generic Interface interface I1<T> { void disp(T a); } class sample <T>implements I1<T> { public void disp(T a) { System.out.println(a); }} public class Generic5 { public static void main(String ar[]) { sample <Integer>s=new sample<Integer>(); s.disp(5); sample <Double>s1=new sample<Double>(); s1.disp(5.4); If we using 2 parameter in the inherited class class sam <T,U> implements I1<T>
  • 32. class sample1<T>{ void disp(T a){ System.out.println(a); } } class sample2<T> extends sample1<T>{ void disp(T a){ System.out.println("Derived"+a); } } public class Generic10 { public static void main(String ar[]){ sample1<Integer> s1=new sample1<Integer>(); s1.disp(4); sample1<Double> s2=new sample2<Double>(); s2.disp(5.2); } }
  • 33. class general{ int num; general(int i){ num=i; } int get(){ return num; }} class Gen<T>extends general{ T obj; Gen(T o,int i){ super(i); obj=o; } T getobj(){ return obj; } void show(){ System.out.println("base class..."); }} Generic Class Hierarchies Contd…
  • 34. class gen2<T,V> extends Gen<T>{ V obj1; gen2(T o, V s,int i){ super(o,i); obj1=s; } V getobj2(){ return obj1; } void show(){ super.show(); System.out.println("subclass..."); }} public class Generic16{ public static void main(String r[]) { gen2<Integer,String> is=new gen2<Integer,String>(100,"java",100); System.out.println("String:"+is.getobj2()); System.out.println("value:"+is.getobj()); System.out.println("nongeneric value:"+is.get()); is.show(); }} Generic Class Hierarchies
  • 35. Wildcards in Java • The ? (question mark) symbol represents the wildcard element. • It means any type. • If we write <? extends Number>, it means any child class of Number, e.g., Integer, Float, and double. • Now we can call the method of Number class through any child class object.
  • 36. Wildcards in Java • The question mark (?) is known as the wildcard in generic programming . • It represents an unknown type. • We can use a wildcard as a type of a parameter, field, return type, or local variable. • However, it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
  • 37. class Gen<T>{ T obj; Gen(T o) { obj=o; } T getobj() { return obj; }} class rawtype{ public static void main(String r[]){ Gen<Integer>o1=new Gen<Integer>(100); Gen<String>o2=new Gen<String>("java"); //int v=o1.getobj(); System.out.println("Value:"+o1.getobj()); //String s=o2.getobj(); System.out.println("String:"+o2.getobj()); Gen raw=new Gen(new Double(100.0)); double d=(Double)raw.getobj(); System.out.println("raw value:"+d);