Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some good java interview questions and answers regarding generics and annotations? [closed]

What are some good java interview questions and answers regarding generics and annotations?

like image 598
Daniel Honig Avatar asked May 21 '10 15:05

Daniel Honig


People also ask

What is generics in Java interview questions?

As implied by the name, a generic type parameter is when a type can be used as a parameter in a class, method or interface declaration. In this case, the method parameter type of the consume() method is String. It is not parameterized and not configurable. In this case, now we can consume integers.

Can you give an example of how generics make a program more flexible?

Can you give an example of how Generics make a program more flexible? MyList can be used to store a list of Strings only. MyList myList = new MyList();

What is the motivation for using generics in Java?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Why do we need generics explain with an example of how generics make a program more flexible?

Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically.


2 Answers

Since Java 5 came out, I have seen dozens of people not understand why, given an interface I, and classes A and B extends A you can't pass an I<B> where an I<A> is required. A lot of people find it counter-intuitive.

To test a person's ability to reason about Generics, then I would first ask them if it is possible to assign an I<B> to an I<A> reference as described above. If not, why not? If they get it wrong, tell them they're wrong and ask them to try to fill in the blanks here to show why this example would be type un-safe if it could compile:

   //...
   List<String> list = new LinkedList<String>();
   someMethod(list);
   //blank 1
}
public void someMethod(List<Object> list) {
   //blank 2
}

At this point it should be pretty easy and I would be a bit worried if they couldn't construct such an example. An example is

//blank 1
String item = list.get(0);

//blank 2
list.add(Integer.valueOf(5));
like image 147
Mark Peters Avatar answered Sep 27 '22 17:09

Mark Peters


This test:

http://tests4geeks.com/test/java

contains some questions about annotations.

It does not contain any questions about generic. But instead of it, there are some other interesting themes like:

Multi-Threading,

Memory,

Algorithms and Data Structures,

OOP,

etc.

like image 44
Vadim Avatar answered Sep 27 '22 16:09

Vadim