Generics Definition:: Some Questions For Midviva As Well: Generics Chapter 19
Generics Definition:: Some Questions For Midviva As Well: Generics Chapter 19
Generics Definition:: Some Questions For Midviva As Well: Generics Chapter 19
Generics Chapter 19
Generics Definition: Java Generic methods and generic classes enable
programmers to specify, with a single method declaration, a set of related methods, or
with a single class declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch
invalid types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array of
objects, then invoke the generic method with Integer arrays, Double arrays, String
arrays and so on, to sort the array elements.
………………….Benefits………………..
Code that uses generics has many benefits over non-generic code:
Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast
Enabling programmers to implement generic algorithms.
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.
3. What is a type safety?
Type safety means that programs are prevented from accessing memory in
inappropriate ways. Type safety means that a program cannot perform an
operation on an object unless that operation is valid for that object.
4. How to make a class re-usable?
you simply create objects of your existing class inside the new class. This is
called composition, because the new class is composed of objects of
existing classes. You're simply reusing the functionality of the code, not its
form.
3. What method do you use to add all the elements from one collection
to another collection?
The Java Collections addAll() method can add a variable number of
elements to a Collection (typically either a List or a Set . Here is a java code
example of calling the Collections addAll() method:
System.out.println(i.next());
So When we are using a for each loop to traverse all elements in a collection
we need to use the next() or hasNext() methods in an iterator
Unchecked exceptions are those exceptions which are not at all known
to compiler. These exceptions occur only at run time. These exceptions
are also called as run time exceptions. All sub classes of
java.lang.RunTimeException and java.lang.Error are unchecked
exceptions.
Interface
package codespaghetti.com;
interface JavaInterface{
int x, y; // compile time error
}
No.
package codespaghetti.com;
interface JavaInterface{
private int x; // compile time error: Illegal modifier for the interface
field Sample.x; only
public, static & final are permitted
protected int a; // compile time error: Illegal modifier for the interface
field Sample.a; only
public, static & final are permitted
}
NO. We can not create object for interface. We can create a variable for
an interface
package codespaghetti.com;
interface JavaInterface{
void show();
package com.instanceofjava;
interface A implements JavaInterface {
void show(){
// code
}
public static void main(String args[]){
JavaInterface obj= new JavaInterface(); // Error: Cannot instantiate the
type JavaInterface
}
}
8.Question: Can we declare interface as final?
No. Compile time error will come. Error: Illegal modifier for the
interface Sample; only public & abstract are permitted
package codespaghetti.com;
interface JavaInterface{
void show();
}
package com.instanceofjava;
interface A implements JavaInterface { // The type Example must
implement the inherited
abstract method JavaInterface.show()
public static void main(String args[]){
}
}
True, .class file will be generated for every interface after compilation.
No. While overriding any interface methods, we should use public only.
Because, all interface methods are public by default and you should not
reduce the visibility while overriding them.
No. You can’t define interfaces as local members of methods like local
inner classes. They can be a part of top level class or interface.
18.Question: Can an interface extend a class?
No, a class can not become super interface to any interface. Super
interface must be an interface. That means, interfaces don’t extend
classes but can extend other interfaces.
No. Interfaces can’t have static methods. Interfaces can have static
methods since Java 1.8.
Advantages
Interfaces are mainly used to provide polymorphic behavior.
Interfaces function to break up the complex designs and clear the
dependencies between objects.
Disadvantages
Java interfaces are slower and more limited than other ones.
Interface should be used multiple number of times else there is
hardly any use of having them.
Polymorphism
Whenever we have more than one same name method but a different
number of arguments or different data types in the same class is known
as method overloading in java. Method overloading the example of
compile-time polymorphism.
For example:
class Addition
{
void add(int a, int b)//with 2 arguments
{
System.out.println(a+b);
}
void add(int a, int b, int c)//change no of arguments i.e 3
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition a = new Addition();
a.add(10,20);
a.add(20,5,6);
}
}
Output: 30
31
In java, whenever we have same name method in parent and child class
with the same number of arguments and same data types is known as
method overriding in java. Method overriding is the example of
dynamic polymorphism.
For example:
class Parent
{
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{
void show()
{
System.out.println("Child");
}
public static void main(String args[])
{
Parent p =new Child();
p.show();
}
}
Output: Child
Ans. No.
Static methods belong to the class and not the objects. They belong to
the class and hence doesn't fit properly for the polymorphic behavior.
class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}
Though Base Class handler is having the object of Derived Class but its
not overriding as now with a definition having an argument ,derived
class will have both method () and method (int) and hence its
overloading.
26.Question: Is this Polymorphism ?
a. Only one object can be created for Singleton class whereas No
objects are created for static class.
b. Singleton class instance is initiated using new keyword whereas
static class instance is created using static method.
c. Singleton class can be serialized whereas Static class cannot be.
d. Singleton Class can participate in runtime Polymorphism whereas
Static class cannot.
a. Serialization
b. Runtime Polymorphism
c. Lazy Loading
d. Memory
Ans. Runtime Polymorphism
Ans. co-variant return type states that return type of overriding method
can be subtype of the return type declared in method of superclass. it
has been introduced since jdk 1.5
Ans.
1)The overriding methods can throw any runtime Exception , here in
the case of runtime exception overriding method (subclass method)
should not worry about exception being thrown by superclass method.
2)If superclass method does not throw any exception then while
overriding, the subclass method can not throw any new checked
exception but it can throw any runtime exception
Exception Handling
31) What is an exception?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for
exception are kept in this block.
catch block : This block catches the exceptions occurred in the try block.
34) Can we keep other statements in between try, catch and finally
blocks?
1 try
2 {
3 // Statements to be monitored for exceptions
4 }
5
6 //You can't keep statements here
7
8 catch(Exception ex)
9 {
10 //Cathcing the exceptions here
11 }
12
13 //You can't keep statements here
14
15 finally
16 {
17 // This block is always executed
18 }
35) Can we write only try block without catch and finally blocks?
All objects within the Java exception class hierarchy extend from the
Throwable superclass. Only instances of Throwable (or an inherited
subclass) are indirectly thrown by the Java Virtual Machine (JVM), or
can be directly thrown via a throw statement. Additionally, only
Throwables (or an inherited subclass) can be caught via a catch
statement.
44) Does finally block get executed If either try or catch blocks are
returning the control?
throw InstanceOfThrowableType;
Exceptions raised in the try block are handled in the catch block. If it is
unable to handle that exception, it can re-throw that exception using
throw keyword. It is called re-throwing an exception.
1
2
try
3 {
4 String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
5 }
6 catch(NullPointerException ex)
{
7 System.out.println("NullPointerException is caught here");
8
throw ex; //Re-throwing NullPointerException
9 }
10
11
49) What is the difference between final, finally and finalize in java?
50) How do you create customized exceptions in java?
Here are the steps:
1.Create a new class whose name should end with Exception like
ClassNameException.
3.Make the class extends one of the exceptions which are subtypes of
the java.
Syntax:
throw Instance
//Example:
Throws In Java :
{ //some statements
throws:
import java.io.IOException;
throws IOException
{
}
Throwable:
Throwable is a super class for all types of errors and exceptions in java.
This class is a member of java.lang package. Only instances of this class
or it’s sub classes are thrown by the java virtual machine or by the
throw statement. The only argument of catch block must be of this type
or it’s sub classes. If you want to create your own customized
exceptions, then your class must extend this class.
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
try {
...
} catch (IOException e) {
}
In this example, when an IOException is caught, a new SampleException
exception is created with the original cause attached and the chain of
exceptions is thrown up to the next higher level exception handler.
56) Which class is the super class for all types of errors and exceptions
in java?
57) What are the legal combinations of try, catch and finally blocks?
1)
1 try
2 {
3 //try block
4 }
5 catch(Exception ex)
6 {
7 //catch block
8 }
2)
1 try
2 {
3 //try block
4 }
5 finally
6 {
7 //finally block
8 }
3)
1 try
2 {
3 //try block
4 }
5 catch(Exception ex)
6 {
7 //catch block
8 }
9 finally
10 {
11 //finally block
12 }
NullPointerException, ArrayIndexOutOfBoundsException,
NumberFormatException
Polymorphism
1) Related to person
Suppose you are in the classroom that time you will behave like a
student.
Suppose when you at home you behave like son or daughter.
Suppose you are in the market at that time you behave like a
customer.
2) Related to product
There are two types of polymorphism in java and these are given
below.
Compile-Time polymorphism or Static polymorphism.
Run-time polymorphism or Dynamic polymorphism.
Compile-Time Polymorphism
Run-Time Polymorphism
The best example of run-time or dynamic polymorphism is the method
overriding. Whenever an object is bound with their functionality at run-
time is know as run-time or dynamic polymorphism in java.
For example:
Generics Chapter 19
85. What method do you use to add all the elements from one
collection to another collection?
88. Can we use a for-each loop to traverse the elements in any instance
of Collection?
89. When using a for each loop to traverse all elements in a collection,
do you need to use the next() or hasNext() methods in an iterator?
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: