As the earlier post implements the generic function in java. This program restricts the data type as numbers. This uses <T extends Number> for restriction.
Steps:
- · Include the built in package “java.util.Scanner”.
- · Create a class with main function. A generic function printIT() with number restriction is created.
- · The input is given by the user. The first number is integer and the second number is float.
- · If it mismatches, it throws the exception. Otherwise,it prints the number.
#Program
import java.util.Scanner;
public class sampleGr {
public static
<T extends Number> void printIt(T value) {
System.out.println("The value is: " + value);
}
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("enter the first value as integer and next value
as float");
int no =
scanner.nextInt();
float a =
scanner.nextFloat();
printIt(no);
printIt(a);
}
}
Output is given below.
C:\raji\blog>javac sampleGr.java
C:\raji\blog>java sampleGr
enter the first value as integer and next value as float
23
5.6
The value is: 23
The value is: 5.6
Exceptions are given as follows….
C:\raji\blog>java sampleGr
enter the first value as integer and next value as float
3.4
Exception in thread "main"
java.util.InputMismatchException
at
java.base/java.util.Scanner.throwFor(Scanner.java:964)
at
java.base/java.util.Scanner.next(Scanner.java:1619)
at
java.base/java.util.Scanner.nextInt(Scanner.java:2284)
at
java.base/java.util.Scanner.nextInt(Scanner.java:2238)
at
sampleGr.main(sampleGr.java:10)
C:\raji\blog>java sampleGr
enter the first value as integer and next value as float
23
rt
Exception in thread "main"
java.util.InputMismatchException
at
java.base/java.util.Scanner.throwFor(Scanner.java:964)
at java.base/java.util.Scanner.next(Scanner.java:1619)
at
java.base/java.util.Scanner.nextFloat(Scanner.java:2522)
at
sampleGr.main(sampleGr.java:11)
C:\raji\blog>java sampleGr
enter the first value as integer and next value as float
rr
Exception in thread "main"
java.util.InputMismatchException
at
java.base/java.util.Scanner.throwFor(Scanner.java:964)
at
java.base/java.util.Scanner.next(Scanner.java:1619)
at
java.base/java.util.Scanner.nextInt(Scanner.java:2284)
at
java.base/java.util.Scanner.nextInt(Scanner.java:2238)
at
sampleGr.main(sampleGr.java:10)
Note :” <T extends String>”. If you are using this
keyword, this will hold only String values instead of all data types.
Thus the way of implementing Generic function in restricted mode in java in efficient way. You can use these type of restrictions based on the requirements. Keep Coding!!!
No comments:
Post a Comment