Object Oriented Programming (OOP)
Java
is a computer programming language that is concurrent, class-based and
object-oriented. The advantages of object oriented software development are
shown below:
- Modular development of code,
which leads to easy maintenance and modification.
- Reusability of code.
- Improved reliability and
flexibility of code.
- Increased understanding of
code.
Object-oriented
programming contains many significant features, such as encapsulation, inheritance,
polymorphism and abstraction. We analyze each feature separately in the following sections.
Encapsulation
Encapsulation
provides objects with the ability to hide their internal characteristics and
behavior. Each object provides a number of methods, which can be accessed by
other objects and change its internal data. In Java, there are three access
modifiers: public, private and protected. Each modifier imposes different
access rights to other classes, either in the same or in external packages.
Some of the advantages of using encapsulation are listed below:
- The internal state of every
objected is protected by hiding its attributes.
- It increases usability and
maintenance of code, because the behavior of an object can be
independently changed or extended.
- It improves modularity by
preventing objects to interact with each other, in an undesired way.
Polymorphism
Polymorphism
is the ability of programming languages to present the same interface for
differing underlying data types. A polymorphic type is a type whose operations
can also be applied to values of some other type.
Inheritance
Inheritance
provides an object with the ability to acquire the fields and methods of
another class, called base class. Inheritance provides re-usability of code and
can be used to add additional features to an existing class, without modifying
it.
Abstraction
Abstraction is the process of separating ideas from specific instances and
thus, develop classes in terms of their own functionality, instead of their
implementation details. Java supports the creation and existence of abstract
classes that expose interfaces, without including the actual implementation of
all methods. The abstraction technique aims to separate the implementation
details of a class from its behavior.
Differences between Abstraction and
Encapsulation
Abstraction
and encapsulation are complementary concepts. On the one hand, abstraction
focuses on the behavior of an object. On the other hand, encapsulation focuses
on the implementation of an object’s behavior. Encapsulation is usually
achieved by hiding information about the internal state of an object and thus,
can be seen as a strategy used in order to provide abstraction.
Can you access
non static variable in static context ?
A static variable in Java belongs to its class and its value remains the same
for all its instances. A static variable is initialized when the class is
loaded by the JVM. If your code tries to access a non-static variable, without
any instance, the compiler will complain, because those variables are not
created yet and they are not associated with any instance.
What is
Function Overriding and Overloading in Java ? Method overloading in Java occurs when two or more
methods in the same class have the exact same name, but different parameters.
On the other hand, method overriding is defined as the case when a child class
redefines the same method as a parent class. Overridden methods must have the
same name, argument list, and return type. The overriding method may not limit
the access of the method it overrides.
What is the difference between an Interface and an Abstract class ? Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common
characteristics, but they differ in the following features:
- All methods in an interface are
implicitly abstract. On the other hand, an abstract class may contain both
abstract and non-abstract methods.
- A class may implement a number
of Interfaces, but can extend only one abstract class.
- In order for a class to
implement an interface, it must implement all its declared methods.
However, a class may not implement all declared methods of an abstract
class. Though, in this case, the sub-class must also be declared as
abstract.
- Abstract classes can implement
interfaces without even providing the implementation of interface methods.
- Variables declared in a Java
interface is by default final. An abstract class may contain non-final
variables.
- Members of a Java interface are
public by default. A member of an abstract class can either be private,
protected or public.
- An interface is absolutely
abstract and cannot be instantiated. An abstract class also cannot be
instantiated, but can be invoked if it contains a main method.
How HashMap
works in Java ? A HashMap
in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve
elements to and from the collection respectively. When the put method is
invoked, the HashMap calculates the hash value of the key and stores the pair
in the appropriate index inside the collection. If the key exists, its value is
updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold
resizing.
What is the
importance of hashCode() and equals() methods ? In Java, a HashMap uses the hashCode and equals methods to determine the index of the key-value pair and
to detect duplicates. More specifically, the hashCode method is used in order to determine where the specified
key will be stored. Since different keys may produce the same hash value, the equals method is used, in order to determine whether the
specified key actually exists in the collection or not. Therefore, the
implementation of both methods is crucial to the accuracy and efficiency of the
HashMap.
What differences exist between HashMap and Hashtable ? Both the HashMap
and Hashtable classes implement the Map interface and thus, have very similar
characteristics. However, they differ in the following features:
- A HashMap
allows the existence of null keys and values, while a Hashtable
doesn’t allow neither null keys, nor null values.
- A Hashtable
is synchronized, while a HashMap
is not. Thus, HashMap
is preferred in single-threaded environments, while a Hashtable
is suitable for multi-threaded environments.
- A HashMap
provides its set of keys and a Java application can iterate over them.
Thus, a HashMap
is fail-fast. On the other hand, a Hashtable
provides an Enumeration of its keys.
- The Hashtable
class is considered to be a legacy class.
What is
Comparable and Comparator interface ? List their differences. Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an
order between them. Specifically, it returns a negative integer, zero, or a
positive integer to indicate that the input object is less than, equal or
greater than the existing object. Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and
imposes an order between them. It returns a negative integer, zero, or a
positive integer to indicate that the first argument is less than, equal to, or
greater than the second. The second method requires an object as a parameter
and aims to decide whether the input object is equal to the comparator. The
method returns true, only if the specified object is also a comparator and it
imposes the same ordering as the comparator
What is the
difference between HashSet and TreeSet ? The HashSet is Implemented using a hash table and thus, its elements
are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a
TreeSet is implemented using a tree structure. The elements in a
TreeSet are sorted, and thus, the add, remove, and contains
methods have time complexity of O(logn).
When is the
finalize() called ? What is the purpose of finalization ? The finalize method is called by the garbage collector,
just before releasing the object’s memory. It is normally advised to release
resources held by the object inside the finalize method.
What is the
difference between throw and throws ?
The throw keyword is used to explicitly raise a exception within the program.
On the contrary, the throws clause is used to indicate those exceptions that
are not handled by a method. Each method must explicitly specify which
exceptions does not handle, so the callers of that method can guard against
possible exceptions. Finally, multiple exceptions are separated by a comma.
What is meant by implicit objects and what are they ? JSP implicit objects are those Java objects
that the JSP Container makes available to developers in each page. A developer
can call them directly, without being explicitly declared. JSP Implicit Objects
are also called pre-defined variables.The following objects are considered
implicit in a JSP page:
- application
- page
- request
- response
- session
- exception
- out
- config
- pageContext
How is it possible for
two String objects with identical values not to be equal under the == operator?
Answer:
The == operator
compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to
have the same value, but located in different areas of memory.
== compares references
while .equals compares contents. The method public boolean equals(Object obj)
is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which
is equivalent to the equality operator == being used to compare aliases to the
object. String, BitSet, Date, and File override the equals() method. For two
String objects, value equality means that they contain the same character
sequence. For the Wrapper classes, value equality means that the primitive
values are equal.
What does it mean that a class or member is
final?
Answer:
- final – declare constant
- finally – handles exception
- finalize – helps in garbage collection
Variables
defined in an interface are implicitly final. A final class can’t be extended
i.e., final class may not be subclassed. This is done for security reasons with
basic classes like String and Integer. It also allows the compiler to make some
optimizations, and makes thread safety a little easier to achieve. A final
method can’t be overridden when its class is inherited. You can’t change value
of a final variable (is a constant). finalize() method is used just before an
object is destroyed and garbage collected. finally, a key word used in
exception handling and will be executed whether or not an exception is thrown.
For example, closing of open connections is done in the finally method.
What is the difference
between the boolean & operator and the && operator?
Answer:
If an expression
involving the boolean & operator is evaluated, both operands are evaluated,
whereas the && operator is a short cut operator. When an expression
involving the && operator is evaluated, the first operand is evaluated.
If the first operand returns a value of true then the second operand is
evaluated. If the first operand evaluates to false, the evaluation of the
second operand is skipped.
What do you understand
by Synchronization?
Answer:
Synchronization is a
process of controlling the access of shared resources by the multiple threads
in such a manner that only one thread can access one resource at a time. In non
synchronized multithreaded application, it is possible for one thread to modify
a shared object while another thread is in the process of using or updating the
object’s value. Synchronization prevents such type of data corruption.
Which two method you need to
implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it
must implements equals and hashcode method in Java.
http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html
What is immutable object? Can you
write immutable object?Immutable classes are Java
classes whose objects can not be modified once created. Any modification in
Immutable object result in new object. For example is String is immutable in
Java. Mostly Immutable are also final in Java, in order to prevent sub class
from overriding methods in Java which can compromise Immutability. You can
achieve same functionality by making member as non final but private and not
modifying them except in constructor.
What will happen if we put a key
object in a HashMap which is already there ?
if you put the same key again than it will
replace the old mapping because HashMap doesn't allow duplicate keys
Explain the different forms of Polymorphism.
There are two types of
polymorphism one is Compile time polymorphism and the other is run time
polymorphism. Compile time polymorphism is method overloading. Runtime time
polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Method overloading
Method overriding through
inheritance
Method overriding through
the Java interface
Difference between
HashSet and TreeSet ?
HashSet
|
TreeSet
|
HashSet is under set interface i.e. it does not guarantee for
either sorted order or sequence order.
|
TreeSet is under set i.e. it provides elements in a sorted
order (acceding order).
|
We can add any type of elements to hash set.
|
We can add only similar types
of elements to tree set. |
How do you decide when to use HashMap and when to use TreeMap ?
For
inserting, deleting, and locating elements in a Map, the HashMap offers the
best alternative. If, however, you need to traverse the keys in a sorted order,
then TreeMap is your better alternative. Depending upon the size of your
collection, it may be faster to add elements to a HashMap, then convert the map
to a TreeMap for sorted key traversal.
Difference between
HashMap and Hashtable ?
HashMap
|
Hashtable
|
HashMap lets you have null values as well as one null key.
|
HashTable does not allows null values as key and value.
|
The iterator in the HashMap is fail-safe (If you change the
map while iterating, you’ll know).
|
The enumerator for the Hashtable is not fail-safe.
|
HashMap is unsynchronized.
|
Hashtable is synchronized.
|
Note: Only
one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys
to be NULL. Nevertheless, it can have multiple NULL values.
What is the Comparable interface ?
The Comparable interface is used to sort collections and arrays
of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively.
The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface
in the generic form is written as follows:
interface Comparable
where T
is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be
negative.
If object1 > object2: The value of i returned will be
positive.
If object1 = object2: The value of i returned will be zero.
77.What are the differences between the Comparable and Comparator interfaces ?
Comparable
|
Comparato
|
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
|
t uses the compare() method.
int compare(ObjOne, ObjTwo) |
It is necessary to modify the class whose instance is going to
be sorted.
|
A separate class can be created in order to sort the instances.
|
Only one sort sequence can be created.
|
Many sort sequences can be created.
|
It is frequently used by the API classes.
|
It used by third-party classes to sort instances.
|
No comments:
Post a Comment