Menu
Topics Index
...
`

How Generics Improve Type Safety2781


If you need explanation Read this topic

If you need Answer Take test on this topic

How Generics Improve Type Safety2781
What will be the output of the following program?
public class GenericTypeSafetyDemo {
    public static void main(String args[])
    {
        NonGeneric obj1 = new NonGeneric(88);
        obj1.showType();
        NonGeneric obj2 = new NonGeneric("MeritCampus");
        obj2.showType();
        obj1 = obj2;
        obj1.showType();
    }
}
class NonGeneric
{
    Object ob;
    NonGeneric(Object ob)
    {
        this.ob = ob;
    }
    void showType()
    {
        System.out.println("Type is : "+ob.getClass().getName());
    }
}

A. Type is : java.lang.Integer
Type is : java.lang.String
Type is : java.lang.String
B. Type is : java.lang.Integer
Type is : java.lang.String
Type is : java.lang.Integer
C. Compilation Error
D. Runtime Error
Topic: How Generics Improve Type Safety In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans A . first two print statements are very clear and in third we are assigning string type to the obj1

Posted by Bheema Reddy    2014-11-05 03:46:57


A

Posted by Akshay Bhatwadekar    2014-11-05 04:00:02


Answer is a.getclass.getname will print the type of the object represented by reference at runtime....first time we pass integer and it prints java.lang.integer...next we pass string and it prints java.lang.string and next we assign object reference that point a string to obj 1 and so java.lang.string is shown

Posted by Shashanka Mogaliraju    2014-11-05 04:29:53


a

Posted by Vikas Tiyagi    2014-11-05 12:10:07


Ans is A...With out generics also we can create an method which can receive any type of data...using the Object class which is parent for all classes in java...here Problems will Come when your returning an particular value..there you Explict type conversion..here we create an object fot NonGeneric class and these class have an constructor with argment as Object class so that here we can create any type of object for this class..using this we are assigning the data to ob which is Object type and next we are calling showType() here we are printing the class name with the ob..it wil return the class name which is pointing at runtime...first we are passing Integer and next String and obj1 assigned with obj2 so that it wil print String only

Posted by Uday Kumar    2014-11-05 16:36:39


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Uday Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-11-06 02:49:59


© meritcampus 2019

All Rights Reserved.

Open In App