You are on page 1of 38

Some questions for MidVIVA as well:

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………………..

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining


classes, interfaces and methods. Much like the more familiar 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.

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.

 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.

1. How do you declare a generic type in a class?


To update the Box class to use generics, you create a generic type
declaration by changing the code "public class Box" to "public class
Box<T>". This introduces the type variable, T, that can be used anywhere
inside the class.

2. What are the benefits of using generic types?


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.

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.

5. How to make a class re-usable and type safety?

6. Question 19.1 and 19.2 **


7. How to declare the type of a generic class?
It specifies the type parameters (also called type variables) T1, T2, ..., and
Tn. To update the Box class to use generics, you create a generic type
declaration by changing the code "public class Box" to "public class
Box<T>". This introduces the type variable, T, that can be used anywhere
inside the class.

Lists, Stacks, Queues and Priority Ques Chapter 20


1. What is a data structure?
Data Structure is a way to store and organize data so that it can be used efficiently.

2. Describe the Java Collection Framework?


The Java collections framework is a set of classes and interfaces that
implement commonly reusable collection data structures. Although
referred to as a framework, it works in a manner of a library. The
collections framework provides both interfaces that define various
collections and classes that implement them.

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:

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

Collections.addAll(list, "element 1", "element 2", "element 3");

4. How do you obtain an iterator from a collection object?


Obtain an iterator to the start of the collection by calling the collection's
iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long
as hasNext( ) returns true.
Within the loop, obtain each element by calling next( ).

5. What method do you use to obtain an element in the collection from


an iterator?
Iterator Interface is used to traverse a list in forward direction, enabling you to remove
or modify the elements of the collection. Each collection classes
provide iterator() method to return an iterator.
6. Can we use a for-each loop to traverse the elements in any instance of
Collection?
Yes. We can use for-each loop. It provides an alternative approach to traverse
the array or collection in Java. It is mainly used to traverse the array or
collection elements. The advantage of the for-each loop is that it eliminates
the possibility of bugs and makes the code more readable. It is known as the
for-each loop because it traverses each element one by one.
7. 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?

Iterator is an interface provided by collection framework to traverse a


collection and for a sequential access of items in the collection.

// Iterating over collection 'c' using iterator

for (Iterator i = c.iterator(); i.hasNext(); )

System.out.println(i.next());

For each loop is meant for traversing items in a collection.

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

what are checked and unchecked exceptions in java?

Checked exceptions are the exceptions which are known to compiler.


These exceptions are checked at compile time only. Hence the name
checked exceptions. These exceptions are also called compile time
exceptions. Because, these exceptions will be known during compile
time.

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.

Click here to see more about checked and unchecked exceptions.

Interface

1.Question: What is an Interface in Java?

An interface is a reference type in Java. It is similar to class. It is a


collection of abstract methods. A class implements an interface,
thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants,
default methods, static methods, and nested types. Method bodies
exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes
the attributes and behaviors of an object. And an interface contains
behaviors that a class implements.
Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.

2.Question: What will happen if we define a concrete method in an


interface in Java?
By default interface methods are abstract.
if we declare any concrete method in an interface compile time error
will come.
Error:Abstract methods do not specify a body.

3.Question: Can we create non static variables in an interface?

No.We can not create non static variables in an interface. If we try to


create non static variables compile time error comes.
By default members will be treated as public static final variables so it
expects some value to be initialized.

package codespaghetti.com;
interface JavaInterface{
int x, y; // compile time error
}

4.Question: What will happen if we do not initialize variables in Java


interface.

Compile time error will come because by default members will be


treated as public static final variables so it expects some value to be
initialized.
package codespaghetti.com;
interface JavaInterface{
int x, y; // compile time error: The blank final field y may not have been
initialized
}

5.Question: Can we declare interface members as private or protected?

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
}

6.Question: When we need to use extends and implements?


A class will implements an interface. A class will extends another
class. An interface extends another interface.

7.Question: Can we create object for an interface in Java?

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

9.Question:   Can we declare constructor inside an interface?

No. Interfaces does not allow constructors.The variables inside


interfaces are static final variables means constants and we can not
create object for interface.
So there is no need of constructor in interface that is the reason
interface doesn't allow us to create constructor.

10.Question: Question : What will happen if we are not implementing


all the methods of an interface in class which implements an interface?

A class which implements an interface should implement all the


methods (abstract) otherwise compiler will throw an error. The type
Example must implement the inherited abstract method
JavaInterface.show() If we declare class as abstract no need to
implement methods. No need of overriding default and static methods.

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[]){

}
}

11.Question: How can we access same variables defined in two


interfaces implemented by a class?

Yes, By Using corresponding interface.variable_name we can access


variables of corresponding interfaces.

12.Question: If Same method is defined in two interfaces can we


override this method in class implementing these interfaces.

Yes, implementing the method once is enough in class. A class cannot


implement two interfaces that have methods with same name but
different return type.

13.Question: Can we re-assign a value to a field of interfaces?


No. The fields of interfaces are static and final by default. They are just
like constants. You can’t change their value once they got.

14.Question: Can we declare an Interface with “abstract” keyword?

Yes, we can declare an interface with “abstract” keyword. But, there is


no need to write like that. All interfaces in java are abstract by default.

15.Question: For every Interface in java, .class file will be generated


after compilation. True or false?

True, .class file will be generated for every interface after compilation.

16.Question: Can we override an interface method with visibility other


than public?

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.

17.Question: Can interfaces become local members of the methods?

 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.

19.Question: Like classes, does interfaces also extend Object class by


default?

No. Interfaces don’t extend Object class.

20.Question: Can interfaces have static methods?

No. Interfaces can’t have static methods. Interfaces can have static
methods since Java 1.8.

21.Question: Advantage and disadvantages of Interfaces

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

(001) What is method overloading?

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

(67) What is method overriding?

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

22.Question: Difference between Overloading and Overriding ?

Ans. Overloading - Similar Signature but different definition , like


function overloading. 

Overriding - Overriding the Definition of base class in the derived class.

001 Polymorphism Definition: Polymorphism in Java is a concept by


which we can perform a single action in different ways. Polymorphism
is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means
many forms.

There are two types of polymorphism in Java: compile-time


polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.

23.Question: Can we override static methods ? Why ?

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. 

A static method is not associated with any instance of a class so the


concept of overriding for runtime polymorphism using static methods
is not applicable.
24.Question: What are points to consider in terms of access modifier
when we are overriding any method?

Ans. 1. Overriding method can not be more restrictive than the


overridden method.

reason : in case of polymorphism , at object creation jvm look for actual


runtime object. jvm does not look for reference type and while calling
methods it look for overridden method.

If by means subclass were allowed to change the access modifier on the


overriding method, then suddenly at runtime—when the JVM invokes
the true object's version of the method rather than the reference type's
version then it will be problematic

2. In case of subclass and superclass define in different package, we can


override only those method which have public or protected access.

3. We can not override any private method because private methods


can not be inherited and if method can not be inherited then method
can not be overridden.

25.Question: What will be the output of following code ?

class BuggyBread1 {
     public String method() {
          return "Base Class - BuggyBread1";
     }
}

class BuggyBread2 extends BuggyBread1{ 


  
     private static int counter = 0;
     public String method(int x) {
         return "Derived Class - BuggyBread2";
     }
      
     public static void main(String[] args) {
          BuggyBread1 bg = new BuggyBread2();  
          System.out.println(bg.method());
     } 
}

Ans. 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 ?

Map<String, List<String>> inventoryManagerCountMap = new


HashMap<String, ArrayList<String>>();

Ans. No. This will result in compilation error as Polymorphism cannot


be performed on Object types.  

27.Question: Which of the following is not the difference between


Singleton and Static class ( Class with static members only ) ?

 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.

Ans. Singleton class instance is initiated using new keyword whereas


static class instance is created using static method.

28.Question: Which of the following do you think is the primary reason


you would never use a static class even the application doesn't need
multiple requests or threads ?

 a. Serialization
 b. Runtime Polymorphism
 c. Lazy Loading
 d. Memory 

Ans. Runtime Polymorphism

29.Question: What is covariant return type? 

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

30.Question: How compiler handles the exceptions in overriding ?

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

3) Different exceptions in java follow some hierarchy tree(inheritance).


In this case , if superclass method throws any checked exception , then
while overriding the method in subclass we can not throw any new
checked exception or any checked exception which are higher in
hierarchy than the exception thrown in superclass method

Exception Handling
31) What is an exception?

Exception is an abnormal condition which occurs during the execution


of a program and disrupts normal flow of the program. This exception
must be handled properly. If it is not handled, program will be
terminated abruptly.

32) How the exceptions are handled in java? OR Explain exception


handling mechanism in java?

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.

finally block : This block is always executed whether exception is


occurred in the try block or not and occurred exception is caught in the
catch block or not.

33) What is the difference between error and exception in java?

Errors are mainly caused by the environment in which an application is


running. For example, OutOfMemoryError happens when JVM runs out
of memory. Where as exceptions are mainly caused by the application
itself. For example, NullPointerException occurs when an application
tries to access null object.

Click here to see more about Error Vs Exception in java.

34) Can we keep other statements in between try, catch and finally
blocks?

No. We shouldn’t write any other statements in between try, catch and


finally blocks. They form a one unit.

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?

No, It shows compilation error. The try block must be followed by


either catch or finally block. You can remove either catch block or
finally block but not both.

36) There are three statements in a try block – statement1,


statement2 and statement3. After that there is a catch block to catch
the exceptions occurred in the try block. Assume that exception has
occurred in statement2. Does statement3 get executed or not?

No. Once a try block throws an exception, remaining statements will


not be executed. control comes directly to catch block.

37) What is unreachable catch block error?


When you are keeping multiple catch blocks, the order of catch blocks
must be from most specific to most general ones. i.e sub classes of
Exception must come first and super classes later. If you keep super
classes first and sub classes later, compiler will show unreachable catch
block error.
1 public class ExceptionHandling
2 {
3     public static void main(String[] args)
4     {
5         try
6         {
7             int i = Integer.parseInt("abc");   //This statement throws NumberFormatException
8         }
9  
10         catch(Exception ex)
11         {
12             System.out.println("This block handles all exception types");
13         }
14  
15         catch(NumberFormatException ex)
16         {
17             //Compile time error
18             //This block becomes unreachable as
19             //exception is already caught by above catch block
20         }
21     }
22 }

38) Explain the hierarchy of exceptions in java?

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.

39) What are run time exceptions in java. Give example?


The exceptions which occur at run time are called as run time
exceptions. These exceptions are unknown to compiler. All sub classes
of java.lang.RunTimeException and java.lang.Error are run time
exceptions. These exceptions are unchecked type of exceptions. For
example, NumberFormatException, NullPointerException,
ClassCastException, ArrayIndexOutOfBoundException,
StackOverflowError etc.

40) What is OutOfMemoryError in java?

OutOfMemoryError is the sub class of java.lang.Error which occurs


when JVM runs out of memory

42) What is the difference between ClassNotFoundException and


NoClassDefFoundError in java?
43) Can we keep the statements after finally block If the control is
returning from the finally block itself?

No, it gives unreachable code error. Because, control is returning from


the finally block itself. Compiler will not see the statements after it.
That’s why it shows unreachable code error.

44) Does finally block get executed If either try or catch blocks are
returning the control?

Yes, finally block will be always executed no matter whether try or


catch blocks are returning the control or not.

45) Can we throw an exception manually? If yes, how?

Yes, we can throw an exception manually using throw keyword. Syntax


for throwing an exception manually is

throw InstanceOfThrowableType;

Below example shows how to use throw keyword to throw an


exception manually.
1 try
2 {
3     NumberFormatException ex = new NumberFormatException();    //Creating an object to NumberFormatExcepti
4  
5     throw ex;        //throwing NumberFormatException object explicitly using throw keyword
6 }
7 catch(NumberFormatException ex)
8 {
9     System.out.println("explicitly thrown NumberFormatException object will be caught here");
10 }

Click here to see more about throw keyword.


46) What is Re-throwing an exception in java?

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

47) What is the use of throws keyword in java?

The Java throws keyword is used to declare the exception information


that may occur during the program execution. It gives information
about the exception to the programmer. It is better to provide the
exception handling code so that the normal flow of program execution
can be maintained.
48) Why it is always recommended that clean up operations like
closing the DB resources to keep inside a finally block?

Because finally block is always executed whether exceptions are raised


in the try block or not and raised exceptions are caught in the catch
block or not. By keeping the clean up operations in finally block, you
will ensure that those operations will be always executed irrespective
of whether exception is occurred or not.

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.

4.Create a constructor with a String parameter which is the detail


message of the exception.

51) What is ClassCastException in java?

ClassCastException is a RunTimeException which occurs when JVM


unable to cast an object of one type to another type.

52) What is the difference between throw, throws and throwable in


java?

Throw: The throw keyword in Java is used to explicitly throw an


exception from a method or any block of code. We can throw either
checked or unchecked exception. The throw keyword is mainly used to
throw custom exceptions.

Syntax:

throw Instance

//Example:

throw new ArithmeticException("/ by zero");


But this exception i.e, Instance must be of type Throwable or a subclass
of Throwable. For example Exception is a sub-class of Throwable and
user defined exceptions typically extend Exception class. Unlike C++,
data types such as int, char, floats or non-throwable classes cannot be
used as exceptions.

Throws In Java :

Throw is also a keyword in java which is used in the method signature


to indicate that this method may throw mentioned exceptions. The
caller to such methods must handle the mentioned exceptions either
using try-catch blocks or using throws keyword. Below is the syntax for
using throws keyword.

return_type method_name(parameter_list) throws exception_list

{ //some statements

throws:

import java.io.IOException;

public class UseOfThrowAndThrows {

public static void main(String[] args)

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.

53) What is StackOverflowError in java?

StackOverflowError is an error which is thrown by the JVM when stack


overflows.

54) Can we override a super class method which is throwing an


unchecked exception with checked exception in the sub class?

No. If a super class method is throwing an unchecked exception, then it


can be overridden in the sub class with same exception or any other
unchecked exceptions but can not be overridden with checked
exceptions.

55) What are chained exceptions in java?

Chained exceptions allow you to rethrow an exception, providing


additional information without losing the original cause of the
exception. The chained exception API was introduced in 1.4 by adding a
cause property of type Throwable to exceptions. Two methods and two
constructors were added to Throwable, the class from which all
exceptions inherit. Since every Throwable can have a cause, each
exception can have a cause, which itself can have a cause, and so on.

The methods and constructors in Throwable that support chained


exceptions are:

Throwable getCause()

Throwable initCause(Throwable)

Throwable(String, Throwable)

Throwable(Throwable)

The Throwable argument to initCause and the Throwable constructors


is the exception that caused the current exception. getCause returns
the exception that caused the current exception, and initCause returns
the current exception.

The following example shows how to use a chained exception:

try {

...

} catch (IOException e) {

throw new SampleException("Other 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?

java.lang.Throwable 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 }

58) What is the use of printStackTrace() method?

printStackTrace() method is used to print the detailed information


about the exception occurred.

59) Give some examples to checked exceptions?

ClassNotFoundException, SQLException, IOException

60) Give some examples to unchecked exceptions?

NullPointerException, ArrayIndexOutOfBoundsException,
NumberFormatException
Polymorphism

(61) What is polymorphism in java?

In java, Polymorphism means "one name many forms". In other words,


you can say whenever an object producing different-different behavior
in different-different circumstances is called polymorphism in java.

(62) Give real-life examples of polymorphism

Let's understand real-time example of 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

Let's take an example of an Air conditioner which produces hot air in


winter and cold air in summer.

So there is one name but it producing different - different output


according to the situation.

(63) How many types are of polymorphism in java?

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.

(64) Can we achieve polymorphism through data member?

No, Polymorphism is always achieved via behavior of an object only


properties of an object do not play any role in case of polymorphism.

(65) What are compile-time and run-time polymorphism?

Compile-Time Polymorphism

The best example of compile-time or static polymorphism is the


method overloading. Whenever an object is bound with their
functionality at compile time is known as compile-time or static
polymorphism in java.

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.

(68) How to achieve static polymorphism?

Compile - time polymorphism is also known as static polymorphism. We


can achieve static polymorphism through method overloading in java.

(69) How to achieve dynamic polymorphism?

Run-time polymorphism is also known as dynamic polymorphism. We


can achieve d polymorphism through method overriding.

(70) Difference between method overloading and method overriding?

(71) What is up-casting in java?


Whenever we put the reference id of a child class object into the parent
class reference variable is known as upcasting in java.

For example:

Parent p = new Child();//upcasting declaration

(72) What is static binding?

Static binding is also known as compile - time polymorphism. Method


overloading is the example of static binding.

In static binding, The type of object is determined at compile-time.

Static binding is also known as early binding.

(73) What is dynamic binding?

Dynamic binding is also known as run-time polymorphism. Method


overriding is the example of dynamic binding.

In dynamic binding, The type of object is determined at run-time.

Dynamic binding is also known as late binding.

(74) Can we achieve method overloading by changing the return type?

No, We cannot achieve method overloading through return type in


java.

(75) What is runtime polymorphism?


Runtime polymorphism is also known as method overriding and it is
achieved at run-time.

Generics Chapter 19

76. How do you declare a generic type in a class?

77. What are the benefits of using generic types?

78. 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.

79. How to make a class re-usable?

80. How to make a class re-usable and type safety?

81. Question 19.1 and 19.2 **

82. How to declare the type of a generic class?


Lists, Stacks, Queues and Priority Ques Chapter 20

83. What is a data structure?

84. Describe the Java Collection Framework?

85. What method do you use to add all the elements from one
collection to another collection?

86. How do you obtain an iterator from a collection object?

87. What method do you use to obtain an element in the collection


from an iterator?

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?

You might also like