Question

Java generics Write a program that calls a method to multiply two integers and return the...

Java generics

Write a program that calls a method to multiply two integers and return the integer result. Modify the program to make the method generic, calling it with two generic data types and then returning the result in the same type which also has to be generic. Call the method two times, once with an integer and once with a double in your main program and display the results

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Java code

public class Multiply {
    public static void main(String[] args)
    {
        int z = getMultiply(5,6);
        System.out.println("The result: "+z);
    }
    public static int getMultiply(int x , int y)
    {
        return x*y;
    }
}

//Output

//Generic version

//Java code

public class Multiply<T> {
    public static void main(String[] args)
    {
        int z = getMultiply(5,6);
        System.out.println("The result: "+z);
        // for double
       double z1=  getMultiply(55.6, 67.8);
       System.out.println("The result: "+z1);
    }
    @SuppressWarnings("unchecked")
    public static  <T extends Number> T getMultiply(T x ,  T y)
    {
        T t;
        if (x instanceof Integer && y instanceof Integer)
          return (T) (Integer)(x.intValue()*y.intValue());
        else
            return (T) (Double)(x.doubleValue()*y.doubleValue());
    }
}

//Output

//If you need any help regarding this solution .......... please leave a comment ....... thanks

Add a comment
Know the answer?
Add Answer to:
Java generics Write a program that calls a method to multiply two integers and return the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT