> For the complete documentation index, see [llms.txt](https://gyansetu-core-java-for-java.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gyansetu-core-java-for-java.gitbook.io/project/4-generics/generic-methods.md).

# Generic Methods

A generic method defines its own formal type parameters. You can define a generic method in a generic or a nongeneric class.

```java
package com.gs.corejava.collections;

public class Generic3 {

	static <T> void genericDisplay(T arg) {
		System.out.println(arg);
	}

	public static void main(String[] args) {
		genericDisplay(12);
		genericDisplay(13.4);
		genericDisplay("mohit");
	}
}
```

```
12
13.4
mohit
```

### GENERIC METHODS DEFINED IN A NONGENERIC CLASS OR INTERFACE:

A nongeneric class doesn’t define type parameters. To define a generic method in a nongeneric class or interface, you must define the type parameters with the method, in its type parameter section. A method’s type parameter list is placed just after its access and nonaccess modifiers and before its return type. Because a type parameter could be used to define the return type, it should be known before the return type is used. An example

![](/files/-LfDA2OZHdHh1R0RWmqT)

{% hint style="info" %}

#### For a generic method (defined in a nongeneric class or inter-face), its type parameter list is placed just after the access and nonaccess modifiers and before its return type.

{% endhint %}

### GENERIC METHODS DEFINED IN A GENERIC CLASS OR INTERFACE:

The following example defines a generic interface, and a generic method that defines its own type parameter.

![](/files/-LfDAPTCZovHbEb8L_BD)

![](/files/-LfDASw5pc4NMtf-nDMa)

#### Problem :

#### 1)

![](/files/-LfDAowck_hA70S6_h_p)

#### 2) What will be the output ?

```java
package com.gs.corejava.collections;

public class Generic3 {

	static <T> void genericDisplay(T arg) {
		System.out.println("int generic");
		System.out.println(arg);
	}

	static void genericDisplay(int arg) {
		System.out.println("int overloaded");
		System.out.println(arg);
	}

	public static void main(String[] args) {
		genericDisplay(12);
		genericDisplay(13.4);
		genericDisplay("mohit");
		// genericDisplay("moiht");
	}
}
```

#### 3) What will be the output ?

```java
package com.gs.corejava.generics;

interface MyMap<K, V> {
	void put(K key, V value);

	<V> void get(K key);
}

class NonGeneric implements MyMap<String, Integer> {
	public void put(String key, Integer value) {
	}

	public <V> void get(String key) {
	}
}

public class GenericClassWithGenericInterface {

}
```

### Ans:

#### 1)&#x20;

![](/files/-LfDCM0fWir6AiIO5veL)
