CodesJava

Easy learning with example program codes

Generics methods in java example


Generics method in java example:

The methods which can handle different types of arguments are known as generic methods. Types of the argument are specified on method call.

Syntax: generic method includes a type parameter, inside angle brackets and appears before the method’s return type.

public static <T> T identical(T obj){
        return returnValue;
 }

Example:

GenericsTest.java

/**
 * This class is used to show the use of generics method.
 * @author codesjava
 */
class Test {
  //Generics method
  public <T> void showItemDetails(T item){
	  System.out.println("Value of the item: " + item);
	  System.out.println("Type of the item: " 
			  + item.getClass().getName());
  }
}
 
public class GenericsTest {	
	public static void main(String args[]){
		//String type test
		Test test = new Test();
		test.showItemDetails("Test String.");
		test.showItemDetails(100);
	}
}

Output:

Value of the item: Test String.
Type of the item: java.lang.String
Value of the item: 100
Type of the item: java.lang.Integer

Download this example.
 
Next Topic: Generics method example with two parameters.
Previous Topic: Generics class example with two parameters.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki