Ans : Generics is type safety. Generics code can be written by passing type parameters either to classes, interfaces, methods or to variables. Example:
class A
Q: What are the benefits of using generics in java?
Ans: These are the benefits of using generics in java:
1.Stronger type checks at compile time. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
2.if use generics, the code does not require casting:
List
list.add("Hello World");
String str = list.get(0); // no cast
3.By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
Q: What is the difference between formal parameter and type parameter?
Ans:formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
Good for interview preparation.
ReplyDeleteThanks..
ReplyDelete