9th exp in java
9th exp in java
AIM:
To write a java program to find the maximum and minimum value from the given type of
elements using a generic function.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class Myclassto implement generic class and generic methods.
Step 3: Get the set of the values belonging to specific data type.
Step 4: Create the objects of the class to hold integer, character and double values.
Step 5: Create the method to compare the values and find the maximum value stored in the array.
Step 6: Invoke the method with integer, character, double and string values. The output will be
displayed based on the data type passed to the method.
Step 7:Stop the program.
PROGRAM:
GenericsDemo.java
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] obj)
{
vals = obj;
}
public T min()
{
T v = vals[0];
for(inti=1; i<vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(inti=1; i<vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class GenericsDemo
{
public static void main(String args[])
{
Integer num[]={10,2,5,4,6,1};
Character ch[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
String str[]= {"hai","how","are","you"};
MyClass<Integer>iob = new MyClass<Integer>(num);
MyClass<Character> cob = new MyClass<Character>(ch);
MyClass<Double>dob = new MyClass<Double>(d);
MyClass<String>sob=new MyClass<String>(str);
System.out.println("Max value in num: " + iob.max());
System.out.println("Min value in num: " + iob.min());
System.out.println("Max value in ch: " + cob.max());
System.out.println("Min value in ch: " + cob.min());
System.out.println("Max value in d: " + dob.max());
System.out.println("Min value in d: " + dob.min());
System.out.println("Max value in str: " + sob.max());
System.out.println("Min value in str: " + sob.min());
}
}
OUTPUT:
Max value in num: 10
Min value in num: 1
Max value in ch: v
Min value in ch: a
Max value in d: 88.3
Min value in d: 10.4
Max value in str: you
Min value in str: are
RESULT:
Thus, the Java program to find the maximum and minimum value from the given type of
elements was implemented using generics and executed successfully.