- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Where exactly Type-Parameter need to be specified, while declaring generic method in Java?
Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.
While defining a generic method you need to specify the type parameter within the angle brackets (< T >). This should be placed before the method's return type.
You can have multiple type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
Example
public class GenericMethod { <T>void sampleMethod(T[] array) { for(int i=0; i<array.length; i++) { System.out.println(array[i]); } } public static void main(String args[]) { GenericMethod obj = new GenericMethod(); Integer intArray[] = {45, 26, 89, 96}; obj.sampleMethod(intArray); String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"}; obj.sampleMethod(stringArray); } }
Output
45 26 89 96 Krishna Raju Seema Geeta
- Related Articles
- Restrictions while declaring a generic (type) in Java
- Passing primitive values while instantiating a parameterized type (generic) in Java?
- Defining generic method inside Non-generic class in Java
- Get the declared method by name and parameter type in Java
- Is it mandatory to use T for type-parameter, while defining Generics classes/methods in Java?
- Is it possible to instantiate Type-parameter in Java?
- Guidelines to be followed while implementing equals method in Java?
- How to check generic type in Kotlin?
- Can a method throw java.lang.Exception without declaring it in java?
- Pass long parameter to an overloaded method in Java
- Func generic type in C#
- How to deserialize a JSON array to list generic type in Java?\n
- Can we have multiple type parameters in generic methods in Java?
- Non-generic Vs Generic Collection in Java
- Why is f required while declaring floats in C#?

Advertisements