Showing posts with label Generics in Java. Show all posts
Showing posts with label Generics in Java. Show all posts

Thursday, February 7, 2008

Part 4 of 4: Continue.. (Solution of Questions)

Answer to Previous Quiz:


Answers :

1) Compilation fails

2) Yes, but with Warning.

3) True

4) True

5)Prints Hi
  bye..

6)Compilation fails.

7) A

8)Compilation fails.

9) No

10) 0

11) 1

12 ) No

Part 4 of 4 : Practice Questions for Generics in JAVA

Question No: 1

What will be the output of this program?



Question No : 2

Will this code compile?


Question No: 3
3) Generics are implemented by Type Erasure ??

True or False?


Question No: 4
4) It is legal to create an ArrayList without a type (i.e. without the < ... > ) statement.

True or false?


Question No: 5
5)What happens when you try to compile and run the following program??



Question No: 6

6)
What happens when you try to compile and run the following program??



Question No: 7
7)While writing the generic classes in Java, which of the following can be used as Generic Parameters? (Can be more than one)

a) Classes
b) Primitive Types
c) Compile time Constants.



Question No: 8

What happens when you try to compile the following code?




Question No: 9


Question No:10 
Given the following: What will be the output of the program?


Question No: 11
Given the following, What is true here? 
1) This code will compile without warning and give output equal to 89.
2) This code will compile with warning and give output equal to 89. 
3) This code will not compile. 
4) Run time exception. 

Question No: 12 
Is the following code legal?
For Answers, Please look at this page >>ANSWERS<<

Wednesday, February 6, 2008

Part 3 of 4: GENERICS in JAVA

How polymorphism works in Generic?

Lets start with a basic analogy between collection and array. Both are more or less similar in the sense that we can use both to hold objects.

Polymorphism in Array and related problems:
In arrays following statement is perfectly valid-
Number[] obj = new Integer[5];

How this statement is interpreted by JAVA Complier and Java Executor?
Java Compiler:
obj will refer to a "Number" object and Object itself can refer to 5 "Number" Object or "subclasses of Number" Objects.

Continuing the compiler behavior, below statements compile fine:
obj[1]= new Intger(123);
obj[2]= new Double(123);

As Both Double and Integer are subclasses of Number.

Java Executor:
After executing this statement one "Number" object will created onto HEAP memory and object itself can refer to 5 "Integer" Objects.But as compiler has allowed to store a "Double" object, at Runtime - Java Executor will throw "ArrayStoreException".so Executor has to suffer because of COMPILER stupidity.

THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS.

Polymorphism in GENERICS:

If we try this-
ArrayList< Object > store_room = new ArrayList< String >( );

COMPILER WILL NOT ALLOWED THIS.

Correct expression is -
ArrayList< String > store_room = new ArrayList< String >( );

As it is clear that all this is because JAVA wants to AVOID EXCEPTION in STORING the objects in STORE ROOM (COLLECTION).

How we create STORE ROOM (COLLECTION OBJ) has been given the liberty, which means-

List< String > store_room = new ArrayList< String >( );


So POLYMORPHISM is ALLOWED While creating a STORE ROOM ( COLLECTION ), but POLYMORPHISM is NOT ALLOWED while storing the objects in STORE ROOM.

Refer to the line above:
"THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS."

so its COMPILER which checks that there is no polymorphism when it comes to STORING of DATA in GENERICS.

JAVA COMPILER:

List< Object> store_room = new ArrayList< String >( );

Result : Compilation error, I am trying to avoid Object storing exceptions.

List< String > store_room = new ArrayList< String >( );

Result: OK, but as now JAVA Executor doesn't need to worry about Object storing, I should remove the unncessary things. So after compilation-

List< String > store_room = new ArrayList< String >( ) -->
                                                                                     List store_room = new ArrayList( );

This is called as TYPE ERASURE.GENERICS ARE FOR COMPILE TIME ONLY. Thats why it makes a strict check at the compile time.

Part 2 of 4: Generics in Java

GENERICS WITH LEGACY CODE :

Lets see how GENERICS work with Legacy Code. By Legacy code we mean - code which has been written with Java Version 1.4 and before.

Analogy:

In this era of digital world, everything has been digitalized so is the PASSPORT. Now a days information is stored in bar-code fashion on passport.Based on this suppose we have one List.
List< digital_Passport > passportList = new ArrayList< digital_Passport >( );

Suppose we have a Legacy Method -

public void legacy_Add_Method( List passportData ){
passportData.add( new Old_Passport() );
}


Lets say we made a call to Legacy Method-

legacy_Add_Method( passportList );



This actually means -
List passportData = new ArrayList< digital_Passport>( )


Think from another point of view, Just because you have a new passport and airport system can recognize your passport, airport authority can not reject people with old passport. Similar way, although this sound odd but JAVA has to allow an old Legacy method be called with new Generic Type Collection Object, but being good JAVA tells this unusual assignment by issuing a COMPILER WARNING.

Another point to remember is - COMPILATION and ERROR are different thing and COMPILATION WITH WARNING is a SUCCESSFUL COMPILATION.

Practice Question :
import java.util.*;
class Test {
public static void main(String [] args) {
Set vals = new TreeSet< String >();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
}

What is true about the above question:
a)Does not Compile
b)Compiles with warning and prints output [one, 1, two]
c)Compiles without warning and prints output [one, 1, two]
d)Compiles with warning and throws exception at runtime
e)Compiles without warning and throws exception at runtime


Answer :
we know that it will compile with warning, so this removes option A and C. Another point about Set
is - Its ordered and sorted collection and String/Integer can not be sorted together. So answer is D.

Part 1 of 4 : Generics in JAVA

GENERICS:

Lets start with a Question. What is GENERICS ?
As per dictionary, it means Race , or a kind. In Java world we can say that - Introduction of Races in Collections. Lets see:

WHILE PUTTING OBJECTS INTO COLLECTION :
Before Java 5:
    List list = new ArrayList( );
    list.add(new String("JOVIAL JAVA"));
    list.add(new Integer(123455)); 
   
In Simple words, we can put Object of any type (Race) in the list.

From Java 5 onwards:
    List{String} Java5list = new ArrayList{String}( );
    Java5list.add(new String("JOVIAL JAVA"));
    Java5list.add(new Integer(123455));    ==> !!! ERROR !!!

In Simple words, only object of Race Type String can reside in list. we can also say that GENERIC Type of list is String.

WHILE FETCHING OBJECTS FROM COLLECTION :
Before Java 5:
    Object object = list.get(0);
This is true as we can put Object of any race in list, so we always get Object in return. We have to explicilty check what is the RACE of object?

    if(object instanceof String){
        System.out.println( "It was a STRING OBJECT" );
    }else{
        System.out.println( "It was not a STRING OBJECT" );
    }

From Java 5 onwards:
    String str = Java5list.get(0);

Yes, here we get String in return as the list GENERIC TYPE was STRING.


PRACTICE QUESTION :


What is true about the above code?
1. compiler error
2. compiles with warning and gives some output
3. compiles without warning and gives some output
4. compiles and runs with no output


Answer : 2