Вы находитесь на странице: 1из 48

The documents contain important Core

Java Topics and brief description of each


for easy understanding. The highlight of the
document is that it is designed in question
answer format .This is done keeping in
mind all doubts and concern related to the
key topics .This will also act as a handbook
to brush up your java knowledge before
going for client interview!
Understanding
Core Java
Concepts
Summarizing Core Java Key
Topics
Afrina Alam Rahman
1

Prepared by Afrina Alam
Table of Contents
Introduction ............................................................................................................................................ 2
Static ....................................................................................................................................................... 3
String ...................................................................................................................................................... 7
Collection .............................................................................................................................................. 10
Exception .............................................................................................................................................. 23
Memory Management........................................................................................................................... 28
Key Guidelines ....................................................................................................................................... 35
References ............................................................................................................................................ 47


2

Prepared by Afrina Alam
Introduction

This document highlights key concepts and features of java programming language .From any java
programmer point of view ,the topics covered here we all know and are familiar with but do we really
understand it ? This document will help all java programmers to learn and understand the essential topics
for better coding .The document is designed in Question Answer format such that all question and
confusion related to understanding of the topic is highlighted and made it clear. The various topics
covered here are as follows:
Static
String
Collection
Exception
Memory Management
Generics
Key Guidelines


3

Prepared by Afrina Alam
Static

Explain static and its usage?

In java world the static word is basically used as
o static blocks of code
o static variables
o static methods

Static blocks of code
Block of statement within a Java class that is enclosed in braces { } and preceded by the static
keyword is called as static block of code .These statements will be executed as soon as class is
loaded first time into the JVM .This in turn helps to initialize all static members , similar to the
work of constructors which initialize instance members. A Java Class can have any number of
such blocks and they can be written anywhere within the class body. During the runtime all
static blocks are called in the same order as they appear in the class.
Given a scenario, one class has a Static block along with Public static void main method
which one will get executed first?
Static block
How to handle Exceptions in static blocks?

In a normal scenario exception are taken care via Exception Class or handling it via try-catch
block .But the above two are not applicable in terms of static blocks so other options available
for exception handling within static block are as follows :

Throw Runtime Exception
Call System.exit(1)
Set Failure flag

Write a piece of code to print the Class Name of any class while loading the class ?

import java.lang.Class;

public class GetClassName
{
public GetClassName (){
System.out.println("Constructor Called");
}
public static void main(String args[])
{
static{
String className = this.getClass().getName();
System.out.println( Class name Before loading the class+ className);
}
4

Prepared by Afrina Alam
}
}

What are the advantages and dis-advanatges of a static block?

Advantages
If youre loading drivers and other items into the namespace. For ex, Class has a
static block where it registers the natives.
If you need to do computation in order to initialize your static variables,you can
declare a static block which gets executed exactly once,when the class is first loaded.
Security related issues or logging related tasks
DisAdvanatges
There is a limitation of JVM that a static initializer block should not exceed 64K.
You cannot throw Checked Exceptions.
You cannot use this keyword since there is no instance.
You shouldnt try to access super since there is no such a thing for static blocks.
You should not return anything from this block.
Static blocks make testing a nightmare.


Static Variables
Any variable declared with static keyword is called static variables and popularly known as class
variables .This is because all instances share the same copy of the variable and we can directly
access these variables without creating an instance .Variables without static key word are called
as instance variables as each instance of the class has its own copy of the variable. Key
characteristics of static variables are below:
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution . These variables
will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesnt need any object
Syntax : <class-name>.<variable-name>
Java does not support global variables but can something closest to it can be implemented
and how ?
The closest to global variables can be implemented via static variables .This in turn will share the
same variable even if we create multiple objects of that class . That implies that the given
variable will reside in the same memory location irrespective of how many objects are created
.And on top we can declare this static variable to be final so that it has only one instance of a
variable that is shared among all objects.

Static Method
5

Prepared by Afrina Alam
Any method declared with static keyword is called static and popularly known as class methods.
This is because all instances share the same copy of the method and can be used directly without
creating object . Methods without static key word are called as instance methods. Static methods
cannot access variables declared without static. Key characteristics of static methods are below:
It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data (instance
variables)
A static method can call only other static methods and can not call a non-static method
from it.
A static method can be accessed directly by the class name and doesnt need any object
Syntax : <class-name>.<method-name>
A static method cannot refer to this or super keywords in anyway.
What is the use of static methods in java?

When you want to be able to access the method without an instance of the class
If there is some code that can easily be shared by all the instance methods, extract that
code into a static method
If you are sure that the definition of the method will never be changed or overridden. As
static methods can not be overridden
What is Static Impact on method overriding?
Sub class Method Action Super Class Method
InstanceMethod() Overrides InstanceMethod()
InstanceMethod() Complies Error StaticMethod()
StaticMethod() Complies Error InstanceMethod()
StaticMethod() Hides StaticMethod()

Can a class be static ?
What does it mean to have a static inner class?
Only Inner class can be declared static and not the top class. Static inner classes imply that the
object of the inner class is not dependent upon the outer class object and can exist indepenently.
Nested classes are divided into two categories: static and non-static. Nested classes that are
declared static are simply called static nested classes. Non-static nested classes are called inner
casses.A static java inner class cannot have instances. A non-static java inner class can have
instances that belong to the outer class. Non static inner class cannot have static data member
and static member method whereas Static Inner class can have static and non static data member
and member method.



6

Prepared by Afrina Alam
class OuterClass{
static class staticInnerClass{} // static-member class
class innerClass{} // non-static member class
}
class testClass{
public static void main(String st[]){
OuterClass obj = new OuterClass ();
OuterClass.innerClass obj1 = obj.new innerClass (); //obj is enclosing instance
//OuterClass.innerClass obj1 = new OuterClass ().new innerClass ();
OuterClass.staticInnerClass obj2= new OuterClass.staticInnerClass (); //No enclosing
}
}

Can we use This moderator inside Static Method?
class Sub {
static int x = 0;
int y;
public void mehtod1() {
this.y = 10;
}
public static void method2() {
this.y = 10;
}
}
Above gives compile time error as "this" represents the object invoking the method. Static
methods are not bound to any object, they are class level methods, hence, "this" cannot be used.
Hence Java static methods cannot use the this keyword.

7

Prepared by Afrina Alam
String

Strings in java are designed as an object that represents a sequence of characters. String is read
only that implies once created the contents cannot be modified at any time.
What are the different ways to create a String in java ?
String s1=Java String;
String s2=new String();
String s3=new String(Java String);
String s4 =new String(s3);
Char data[]={ j, a, v, a)}; String s5 =new String(data);
Where string is stored on Heap or Stack in java?

A String in java is dealt as an object and since all objects resides over heap hence even string
object is on the heap. But in addition to it the variables we define for String is pointer to the
object and hence reside on stack.
What is the difference between String s = Java; and String s= new String(Java);
String str = new String(Java);
In the above case two objects will be created
One which will reside on heap
Other in String Constant Pool
Here str will always point to the heap object and not to the String Constant Pool.
String str = Java;
In the above case only one object will be created and that would reside in String Constant Pool
Here str will always point to the to the object in String Constant Pool.
In String Constant Pool to create objects always is not mandatory. At first stage JVM checks if
there is any object that exist in Pool with the same content, if the object is present there then it
will use the same else create new object. Hence the pool does not allow any creation of duplicate
objects .JVM does not allow to do any clean up by Garbage collector within the String Constant
Pool but as soon as the JVM shut down automatically everything gets flushed out from the pool.
The benefit of the second approach is in terms of memory utilization that in turn improves the
performance .Because we reduce object creation and as we know object creation is costly in java

Explain the concept of String objects as immutable with an example
8

Prepared by Afrina Alam
String s1 = "Java";
String s2 = s1;

// s1 and s2 now refer to the same string - "Java".

In the above case even if we make any changes to string s1 it will never affect the s2 .Though
they refer to the same value Java but since they are immutable thus cannot be altered.
Now lets check if we do a change like this :

s1 = "Java Modified ";
System.out.println(s2); // still prints "Java"

Here we see the difference between mutating an object, and changing a reference. s2 still points
to the same object as we initially set s1 to point to. Setting s1 to "Java Modified" only changes
the reference, while the String object it originally referred to remains unchanged. That
summarized the first String Java will always exist .Hence by changing string s1 we do not
actually modify the string but create one more thereby signifying the concept of immutable .

Explain the difference between == and equals with respect to string in java with example
equals( ) method and the == operator perform two different operations.
The equals( ) method compares the characters inside a String object. It considers the content of
string for comparison
The == operator compares two object references to see whether they refer to the same instance. It
considers the memory space.

String s1 =new String("Java");
String s2 = new String(Java);
String s3=s1;
System.out.println("String s1+s1);
System.out.println("String s2+s2);
System.out.println("String s3+s3);
System.out.println(" s1 equals s2" +s1.equals(s2));
System.out.println(" s1 == s2 " + (s1 == s2));
System.out.println(" s1 == s3 " + (s1 == s3));

Output of above program is

String s1:Java
String s2:Java
String s3:Java

s1 equals s2 :true
s1 == s2 :false
s1 == s3 :true

9

Prepared by Afrina Alam
Memory reference of above String values

Reference











If new is not used to assign values to String object then all Strings with same literal values will
refer to the same object in memory .

String s4 = "Java";
String s5 = "Java";
System.out.println(" s4 equals s5:" +s4.equals(s5));
System.out.println(" s4 == s5 :" + (s4 == s5));

Output for above will be

s4 equals s5 : true
s4 == s5 : true

When JVM find two string object with the same content, in order to save memory, instead of
creating two new objects, they check whether the object already exist and if exits they just point
ot it .That implies if the string "Java" already created say s4 and when a new string is created
with the same word "Java" say s5 JVM detect that already exist this string and then did not create
a new object, JVM just make a reference the two objects to the same "Java", so s4 and s5 are
"pointing" to the same place in the memory, and s4==s5 are true.





S1
S2
S3
2
nd
Object reference in Memory
Java
1
st
Object reference in Memory
Java
10

Prepared by Afrina Alam
Collection

What is Collection and Collections in java referred to ?
Collection is a base interface for most collection classes, whereas Collections is a utility class.

Collections class is a utility class having static methods for doing operations on objects of classes
which implement the Collection interface. For example, Collections has methods for finding the
max element in a Collection.
Collection is the root interface in the collection hierarchy. A collection represents a group of
objects, known as its elements. Some collections allow duplicate elements and others do not.
Some are ordered and others unordered
Why is collection important in java ?
The Java Collections API's provide Java developers with a set of classes and interfaces that
makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays,
except their size can change dynamically, and they have more advanced behaviour than arrays.
What Is a Collections Framework?

A collections framework is nothing but an architecture for representing and manipulating
collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation.
Implementations: These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of
the appropriate collection interface

What are advantages of Collection Framework ?

The Java Collections Framework provides the following Advantages:
Reduces programming effort
Increases program speed and quality
Allows interoperability among unrelated APIs
Reduces effort to learn and to use new APIs
Reduces effort to design new APIs
Fosters software reuse



11

Prepared by Afrina Alam

Explain all Core Collection Interface?

The core collection interfaces are:


Collection the root of the collection hierarchy. A collection represents a group of
objects known as its elements. The Collection interface is the least common denominator
that all collections implement and is used to pass collections around and to manipulate
them when maximum generality is desired. Some types of collections allow duplicate
elements, and others do not. Some are ordered and others are unordered. The Java
platform doesn't provide any direct implementations of this interface but provides
implementations of more specific subinterfaces, such as Set and List.
Set a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the cards comprising a
poker hand, the courses making up a student's schedule, or the processes running on a
machine.
List an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the list each
element is inserted and can access elements by their integer index (position).
Queue a collection used to hold multiple elements prior to processing. Besides basic
Collection operations, a Queue provides additional insertion, extraction, and inspection
operations.
Map an object that maps keys to values. A Map cannot contain duplicate keys; each
key can map to at most one value. If you've used Hashtable, you're already familiar with
the basics of Map.

The last two core collection interfaces are merely sorted versions of Set and Map:
Collection
List
Set
Sorted Set
Queue
Map
Sorted Map
12

Prepared by Afrina Alam
SortedSet a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. Sorted sets are used for
naturally ordered sets, such as word lists and membership rolls.
SortedMap a Map that maintains its mappings in ascending key order. This is the
Map analog of SortedSet. Sorted maps are used for naturally ordered collections of
key/value pairs, such as dictionaries and telephone directories.

What do generics do in Collections?

The motivation for adding generics to the Java programming language stems from the lack of
information about a collection's element type, the need for developers to keep track of what type
of elements collections contain, and the need for casts all over the place. Using generics, a
collection is no longer treated as a list of Object references, but you would be able to
differentiate between a collection of references to Integers and
collection of references to Bytes. A collection with a generic type has a type parameter that
specifies the element type to be stored in the collection.
E.g., consider the following segment of code that creates a linked list and adds an element to the
list:

LinkedList list = new LinkedList();
list.add(new Integer(1));
Integer num = (Integer) list.get(0);

So, when an element is extracted from the list it must be cast. The casting is safe as it will be
checked at runtime, but if you cast to a type that is different from, and not a supertype of, the
extracted type then a runtime exception, ClassCastException will be thrown.

Using generic types, the previous segment of code can be written as follows:

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(new Integer(1));
Integer num = list.get(0);

Here we say that LinkedList is a generic class that takes a type parameter, Integer in this case.
With generics, you achieve polymorphic behavior similar to the example above, but with strong
static typechecking; the compiler knows that the two lists are different because they contain
different elements, and these lists are guaranteed to contain only a homogeneous set of elements.
The sample code below is a translation of the previous example, using generics this time. As you
can see from comments in the code, all the errors are caught at compile time. Don't worry about
the syntax for now -- we'll cover that shortly.






13

Prepared by Afrina Alam

Draw the hierarchical diagram of collection framework

Collection Interface























Queue
Linked List
Stack
Array List Vector HashSet Tree Set
Linked HashSet Concrete
Classes
14

Prepared by Afrina Alam
Map Interface
























Is there a collection interface above all the collection classes

Collection is a base interface for most collection classes, whereas Collections is a utility
class.Hence Collection is the root interface in the collection hierarchy. A collection represents a
group of objects, known as its elements. Some collections allow duplicate elements and others do
not. Some are ordered and others unordered. The SDK does not provide any direct
implementations of this interface: it provides implementations of more specific subinterfaces like
Set and List. This interface is typically used to pass collections around and manipulate them
where maximum generality is desired.









MAP
SortedMap
Abstarct
Classes
AbstarctMap
HashMap
TreeMap
Interfaces
LinkedHashMap
Concrete
Classes
15

Prepared by Afrina Alam
Explain Collections Framework and the business scenarios where each of them will be
used?

Collection
type
Functionality Typical uses
List Essentially a variable-size
array;
You can usually add/remove
items at any arbitrary
position;
The order of the items is
well defined (i.e. you can
say what position a given
item goes in in the list).
Most cases where you just need to store or
iterate through a "bunch of things" and later
iterate through them.
Set Things can be "there or
not" when you add items
to a set, there's no notion of
how many times the item
was added, and usually no
notion of ordering.
Remembering "which items you've
already processed", e.g. when doing a
web crawl;
Making other yes-no decisions about an
item, e.g. "is the item a word of
English", "is the item in the database?"
, "is the item in this category?" etc.
Map Stores an association or
mapping between "keys" and
"values"
Used in cases where you need to say "for a
given X, what is the Y"? It is often useful for
implementing in-memory caches or indexes.
For example:
For a given user ID, what is their
cached name/User object?
For a given IP address, what is the
cached country code?
For a given string, how many instances
have I seen?
Queue Like a list, but where you
only ever access the ends of
the list (typically, you add to
one end and remove from
the other).
Often used in managing tasks
performed by different threads in an
application (e.g. one thread receives
incomming connections and puts them
on a queue; other "worker" threads take
connections off the queue for
processing);
For traversing hierarchical
structures such as a filing system, or
in general where you need to remember
16

Prepared by Afrina Alam
"what data to process next", whilst
also adding to that list of data;
Related to the previous point, queues
crop up in various algorithms, e.g.
build the encoding tree for Huffman
compression.


Advantage of using java.util.iterator as compared to the for loop for traversing collections
In the case of ArrayList the difference, like said, is minimal. Both options above are not thread-
safe and roughly equal in performance. The difference lies in the Iterator's remove() method
which allows to "safely" remove items while iterating. for loop can not (easily) remove the
element of the current iteration correctly .Generally , we can get the collection object in iterator
object using iterator also when there are no more entries to be fetched the loop automatically
closes.

How does ArrayList work internally

Arraylist.java file has an array internally If the array is full and you add an element, it creates a
new array and copies the entries over. If you insert in the middle, it shifts the entries down and
inserts.
There are performance problems with such a structure, which is why there's such a thing as
Linked List, which is more efficient for insert operations

How does LinkedList work internally

A LinkedList in Java works as collection of element linked to each other . If you use the official
Collections LinkedList then it will indeed be a a bunch of object connected to each other by
having a 'next' and sometimes 'previous'. It has a get(int index) method which is surprising
because it would not be very efficient as we would need to start at the beginning and count our
way up the list to find the indexth entry and this is not what LinkedLists are good at. The reason
it is there is because LinkedList implements the List interface. However, we should avoid using a
LinkedList when most of your access to it is through the get(int index) method as that would
clearly be most inefficient. We should use an ArrayList.

What is hashSet ?

A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine
whether an object is already in the set or not. It does so by internally managing an array and
storing the object using an index which is calculated from the hashcode of the object.

17

Prepared by Afrina Alam
Difference between hashMap and hashSet
HashMap is not collection inteface where as HashSet is Collection interface.
HashMap class implements Map interface where as HashSet class implements Set
interface.
HashMap is prints the elements orderly where as HashSet has no order
Which container is better for the storage Arraylist/Linked list?
Both are similar, though slightly different in terms of goal and implementation. In a LinkedList,
each element is linked to its previous and next element making it easier to delete or insert in the
middle of the list. An ArrayList is more as its name subjects used as an array.Performance is
similar, though LinkedList is optimized when inserting elements before the end of the list, where
ArrayList is optimized when adding elements at the end. If you frequently add elements to the
beginning of the List or iterate over the List to delete elements from its interior, you should
consider using LinkedList. These operations require constant-time in a LinkedList and linear-
time in an ArrayList. But you pay a big price in performance. Positional access requires
lineartime in a LinkedList and constant-time in an ArrayList.

Difference between linkedhashmap and hashmap

Both implement the Map interface and offer mostly the same functionality. Both represent
mapping from unique keys to values, and therefore implement the Map interface The most
important difference is the order in which iteration through the entries will happen:
HashMap is a map based on hashing of the keys. It supports O(1) get/put operations.
Keys must have consistent implementations of hashCode() and equals() for this to work.
LinkedHashMap is very similar to HashMap, but it adds awareness to the order at which
items are added (or accessed), so the iteration order is the same as insertion order (or
access order, depending on construction parameters).
HashMap makes absolutely not guarantees about the iteration order. It can (and will)
even change completely when new elements are added.
LinkedHashMap will iterate in the order in which the entries were put into the map
HASH MAP has pair values(keys,values) NO duplication key values unordered
unsortered it allows one null key and more than one null values HASH TABLE: same as
hash map it does not allows null keys and null values
LINKED HASH MAP: It is ordered version of map implementation Based on linked list
and hashing data structures TREE MAP: Ordered and sortered version based on hashing
data structures

Difference between Hash Map and Tree Map
HashMap will not store the elements in order.Whereas TreeMap stores in order.so while
retrieving we will get in a particular order.But for HashMap we won't.
HashMap provides the implementation of Map Interface by using hashtable where as
TreeMap provides the implementation of Map Interface by using Tree.
18

Prepared by Afrina Alam
HashMap does not guarntee any order TreeMap provides sorted order.
Difference between a vector and array?
The basic difference between those two are:
Vector and Arraylist are grownable or shinkable where are array is not.
Vector and Arraylist are implemented from List interface where as array is a primitive
data type
Vector is Synchrnized where as arraylist is not
For best performance better to use arraylist than vector

Difference between a hashmap and a hashtable?

A HashMap is unsynchronized whereas a Hashtable is synchronized. In other words,
Hashtable can only be manipulated by a single thread at a time, use it only in
multithreaded environment.
HashMap allows null values in both key and value whereas Hashtable doesn't allow that.
HashMap allows you to iterate over keys, values, or key-value pairs whereas a Hashtable
does not provide the third option
HashMap is the best if your program is not involved with synchronization concept.
HashMap is not synchronized and faster access.
HashpTable is synchronized and slower performace.

Explain Internal implementation of interfaces which extend Set
Set contains no duplicate elements i.e., no pair of elements e1 and e2 such that e1.equals(e2), and
at most one null element. But the question is how set maintains unique elements?. Internally set
maintains a Map when a Set (HashSet/Treeset/etc) is instantiated
Constructor of HashSet
public HashSet() {
map = new HashMap();
}
So HashSet creates an instance of HashMap when HashSet is instantiated, TreeSet creates an
instance of TreeMap when TreeSet is instantiated and so on. The keys in the map are the
elements you add to Set. Then what are values? Values are dummy objects. When you add an
element to the Set, the element will be added as key and "new Object()" (dummy Object
instance) will be added as value which is a dummay value. What will happen if you add a
duplicate object to Set? If the set already contains the element, the call to add method leaves the
set unchanged and returns false. If the set does not contain the element, the call to add method
adds the element and returns true.
19

Prepared by Afrina Alam
HashSet:

HashSet is backed by a HashMap instance and hence it allows the null element. It makes no
guarantees as to the iteration order of the set; in particular, it does not guarantee that the order
will remain constant over time.
When do you use HashSet?
When you are looking for performance, use HashSet. Since this class uses the hash function
when retrieving the elements, it allows fast retrieval. This class offers constant time performance
for the basic operations add, remove, contains and size, assuming the hash function disperses the
elements properly among the buckets. Iterating over this set requires time proportional to the
sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing
HashMap instance the number of buckets. Thus, it's very important not to set the initial capacity
too high (or the load factor too low) if iteration performance is important
LinkedHashSet:

LinkedHashSet is backed by LinkedHashMap. So all the elements in LinkedHashSet are actually
the keys in the LinkedHashMap. It maintains a doubly-linked list running through all of its
entries. This linked list defines the iteration ordering, which is the order in which elements were
inserted into the set (insertion-order). This class provides all of the optional Set operations, and
permits null elements.
When do you use LinkedHashSet?
When you are looking to produce a copy of a set that has the same order as the original,
regardless of the original set's implementation without incurring the increased cost (associated
with TreeSet).
This technique is particularly useful if a module takes a set on input, copies it, and later returns
results whose order is determined by that of the copy. Like HashSet, it provides constant-time
performance for the basic operations add, contains and remove), assuming the hash function
disperses elements properly among the buckets. Performance is likely to be just slightly below
that of HashSet, due to the added expense of maintaining the linked list, with one exception:
Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its
capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to
its capacity A linked hash set has two parameters that affect its performance: initial capacity and
load factor. They are defined precisely as for HashSet. Note, however, that the penalty for
choosing an excessively high value for initial capacity is less severe for this class than for
HashSet, as iteration times for this class are unaffected by capacity
TreeSet:

20

Prepared by Afrina Alam
TreeSet is backed by TreeMap instance and TreeSet wont permit null elements. As opposing to
HashSet, TreeSet provides a total ordering on its elements and especially when you need a sorted
order. The elements are ordered either by using their plain Comparable natural ordering (if you
dont pass any parameter for the TreeSet constructor) or by a Comparator typically provided at
sorted set creation time as a parameter to the constructor. All elements inserted into this set must
either implement the Comparable interface or atleast be accepted by the specified comparator. So
all such elements must be mutually comparable i.e., e1.compareTo(e2) (or
comparator.compare(e1, e2)) must not throw a ClassCastException.
When do you use TreeSet?
Its very well explained above that TreeSet will be used when the sorted order of inserted
elements is required.
What about the performance? The performance obviously will be low compared to HashSet. A
TreeSet may be accessed and traversed in either ascending or descending order. The
descendingSet method returns a view of the set with the senses of all relational and directional
methods inverted. The performance of ascending operations and views is likely to be faster than
that of descending ones.
What is a hashcode?
Any Java programmer must be familiar with the word hashcode but what does it actually implies
and where does it get used? In a brief perspective Hash code is a 32-bit integer that locates an
object in the memory. We all know java considers everything as an object and an any object
when loaded into memory must have it location and that is specified as hashcode .And hence the
root of all classes Object has a method called int hashcode() that signifies the above. Since all
class is inherited fromt his root class Object hene the method hashcode() is available to all the
objects in java.
How will you make sure that key returns unique hashcode in hashmap?

The default hashCode() method uses the 32-bit internal Java Virtual Machine address of the
Object as its hashCode. However, if the Object is moved in memory during garbage collection,
the hashCode stays constant. This default hashCode is not very useful, since to look up an Object
in a HashMap, you need the exact same key Object by which the key/value pair was originally
filed. Normally, when you go to look up, you dont have the original key Object itself, just some
data for a key. So, unless your key is a String, nearly always you will need to implement a
hashCode and equals method on your key class. Object.hashCode in a native method.

Explain equals method and its dependability on hash code ?
Let us consider two String object :
String str=String Object;
String str1=String Object;
21

Prepared by Afrina Alam
Now let us compare them str.equals(str1); This return true as equal method compares the value
for string Object .
Now let us take two new object :
Person obj=new Person ();
Person obj1=new Person ();
Now let us compare them obj.equals(obj1); This return false as equal method compares the
hashcode for two Objects.
Hence to make comparison of two Objects more meaningful we should always override Equals
as well as hashcode methodas belwo
public class Person{
private String empName;
public Person(String name){
this. empName= name;
}
public boolean equals( Object obj ){
boolean flag = false;
Person perObj = (Person)obj;
if(perObj. empName .equals( empName))
flag = true;
return flag;
}
public int hashCode(){
return empName;
}
How does hashmap works
It has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique
number - that's what identifies the bucket. When you put a key-value pair into the map, the
hashmap will look at the hash code of the key, and store the pair in the bucket of which the
identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is
stored in bucket number 235. (Note that one bucket can store more then one key-value pair).
When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of
the key that you gave. The hashmap will then look into the corresponding bucket, and then it will
compare the key that you gave with the keys of all pairs in the bucket, by comparing them with
equals().
22

Prepared by Afrina Alam
Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash
code of the key the hashmap immediately knows in which bucket to look, so that it only has to
test against what's in that bucket.
Looking at the above mechanism, you can also see what requirements are necessary on the
hashCode() and equals() methods of keys:
If two keys are the same (equals() returns true when you compare them), their
hashCode() method must return the same number. If keys violate this, then keys that are
equal might be stored in different buckets, and the hashmap would not be able to find
key-value pairs (because it's going to look in the same bucket).
If two keys are different, then it doesn't matter if their hash codes are the same or not.
They will be stored in the same bucket, but the hashmap will use equals() to tell them
apart



23

Prepared by Afrina Alam
Exception

What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This
includes the Error and Exception types.
How can you customize your exception?
Create a custom exception class that will extends the Exception class, for example
class myException extends Exception{
public myException () { }
public myException(String message) {
super(message);
}
Usage :
try{
if(word.coantains( )){
throw new myException();
}
}
Catch(myException ex){

}

Describe the different blocks involved in a typical exception handling scenario. what does
the "finally" block do?
try{
<code to be monitored for exceptions>
} catch (<ExceptionType1 <onjName>){
<handler if ExceptionType1 occurs>
24

Prepared by Afrina Alam
} .
}finally {
<code to be executed before the try blocks ends>
}
Finally:
A finally block is always executed, regardless of the cause of exit from the try block, or whether
any catch block was executed. Generally finally block is used for freeing resources, cleaning up,
closing connections etc. If the finally clock executes a control transfer statement such as a return
or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control
statement present in the try or catch
What is the "throws" statement? when is it required?
Java allows you to throw exceptions (generate exceptions)
throw <exceptionObject>;
An exception thrown is always an object same as any other object except it extend Exception
Class or RuntimeException Class
What are the different types of exceptions, and examples
In Java, exceptions are objects. When you throw an exception, you throw an object. You can't
throw just any object as an exception, however -- only those objects whose classes descend from
Throwable.
Throwable serves as the base class for an entire family of classes, declared in java.lang, that your
program can instantiate and throw.
Throwable has two direct subclasses, Exception and Error.

Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can
often be handled by some catcher, though it's possible they may not be caught and therefore
could result in a dead thread. Exception subclasses represent errors that a program can
reasonably recover from. Except for RuntimeException and its subclasses (see below), they
generally represent errors that a program will expect to occur in the normal course of duty

Example:
Division by Zero
Array out of Bound

RuntimeException is a further subclass of Exception. RuntimeException and its subclasses are
slightly different: they represent exceptions that a program shouldn't generally expect to occur,
but could potentially recover from. They represent what are likely to be programming errors
rather than errors due to invalid user input or a
25

Prepared by Afrina Alam
badly configured environment.

Errors (members of the Error family) are usually thrown for more serious problems, such as
OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw
only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the
Java virtual machine itself. Error subclasses represent "serious" errors that a program generally
shouldn't expect to catch and recover from. These include conditions such as an expected class
file being missing, or an OutOfMemoryError.
Example:
Out of Memory
Hard Disk error

Exception Class Hierarchy
Throwable Error Linkage Error ,.
Virtual Machine Error, ..
Exception Class Not Found Exception
Clone Not Supported Exception
IllegalAccessException
InstantiationException
InterruptedException
IOException EOFException
FileNotFoundException

RunTimeException ArithemticException
ArrayStoreException
IllegalArgumentException
(IllegalThreadStateException &
NumberFormatException as subclass)
IllegalMonitorStateException
IndexOutOFBoundException
NegativeArraySizeException
NullPointerException

What are Checked/unchecked exceptions?

Unchecked exceptions :
Represent defects in the program (bugs) - often invalid arguments passed to a non-private
method. To quote from The Java Programming Language, by Gosling, Arnold, and
Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking,
reflect errors in your program's logic and cannot be reasonably recovered from at run
time."
Are subclasses of RuntimeException, and are usually implemented using
IllegalArgumentException,NullPointerException, or IllegalStateException
26

Prepared by Afrina Alam
A method is not obliged to establish a policy for the unchecked exceptions thrown by its
implementation (and they almost always do not do so)
Checked exceptions :
Represent invalid conditions in areas outside the immediate control of the program
(invalid user input,database problems, network outages, absent files)
Are subclasses of Exception
A method is obliged to establish a policy for all checked exceptions thrown by its
implementation (either pass the checked exception further up the stack, or handle it
somehow) It is somewhat confusing, but note as well that RuntimeException (unchecked)
is itself a subclass of Exception (checked).

"What are Runtime Exceptions?
Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g
NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling
any method, NullPointerException would never occur. Similarly
ArrayIndexOutOfBoundException would never occur if you check the index first.
RuntimeException are not checked by the compiler, so it is clean code.
What is an Error?"
Errors (members of the Error family) are usually thrown for more serious problems, such as
OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw
only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the
Java virtual machine itself. Error subclasses represent "serious" errors that a program generally
shouldn't expect to catch and recover from. These include conditions such as an expected class
file being missing, or an OutOfMemoryError.
Example:
Out of Memory
Hard Disk error

Can a method return an exception

Yes itcan return exceptions since they descend from Object class and are a type of Object.
public class Test {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
Exception ex = test();
System.out.println(ex.getMessage());
}

static Exception test() {
return new IndexOutOfBoundsException("Returning Exception!!!");
}
}
27

Prepared by Afrina Alam
Can a subclass throw a narrower Exception ?

An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method
28

Prepared by Afrina Alam
Memory Management

What you know about Garbage collector in Java?

In the Java programming language, dynamic allocation of objects is achieved using the new
operator. An object once created uses some memory and the memory remains allocated till there
are references for the use of the object. When there are no references for an object, it is assumed
to be no longer needed and the memory occupied by the object can be reclaimed.There is no
explicit need to destroy an object as java handles the de-allocation automatically. The technique
that accomplishes this is known as Garbage Collection.Programs that do not de-allocate
memory can eventually crash when there is no memory left in the system to allocate. These
programs are said to have memory leaks
In Java,Garbage collection happens automatically during the lifetime of a java program,
eliminating the need to de-allocate memory and avoiding memory leaks.
Garbage mechanism in java
class GarabageTestObject{
private int a;
private int b;

public void setMethod(int c,int d){
a=c;
b=d;
}
public void showMethod(){
System.out.println("Value of a = "+a);
System.out.println("Value of a = "+b);
}
public static void main(String args[]){
GarabageTestObject firstObj = new GarabageTestObject ();
GarabageTestObject secondObj = new GarabageTestObject ();
firstObj.setMethod(1,2);
secondObj.setMethod(3,4);
29

Prepared by Afrina Alam
firstObj.showMethod();
secondObj.showMethod();
}
}
Now let us see what happens in the memory after we run the above program :
Two Object with values a=1,b=2 and a=3 ,b=4 are created with two reference variables firstObj
and secondObj created
Heap Memory
a=1 a=3
b=2 b=4





Now lets us add few lines to the above code:
GarabageTestObject thirdObj;
thirdObj = secondObj;
thirdObj.showMethod();
Now we see two reference variables secondObj and thirdObj are pointing to the same object
a=3,b=4.
Heap Memory
a=1 a=3
b=2 b=4






firstObj
secondObj
firstObj secondObj
thirdObj
30

Prepared by Afrina Alam
Now let us make the below changes in above code
secondObj =null;
thirdObj.showMethod();
We see secondObj becomes null but the reference thirdObj still exist and hence the object is not
eligible for garabge collection
Heap Memory
a=1 a=3
b=2 b=4





Now let us add following lines of code to the above code
thirdObj =null;
thirdObj.showMethod();
Now to the second object no reference variables are pointing and hence become eligible
candidate for garbage collection.
Heap Memory
a=1 a=3
b=2 b=4





Note :
If you want to make your object eligible for Garbage Collection , assign its reference
variable to null.
Primitive types are not objects. They cannot be assigned null.

firstObj
secondObj
thirdObj
Pointing to null
firstObj secondObj thirdObj
31

Prepared by Afrina Alam
Which part of the memory is involved in Garbage Collection? Stack or Heap?

Heap

What is responsiblity of Garbage Collector?

Garbage collector frees the memory occupied by the unreachable objects during the java
program by deleting these unreachable objects.It ensures that the available memory will be used
efficiently, but does not guarantee that there will be sufficient memory for the program to run.

Is garbage collector a dameon thread?

Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM.
The thread stops when all non-dameon threads stop.

Garbage Collector is controlled by whom?

The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM
runs the Garbage Collector when it realizes that the memory is running low, but this behavior of
jvm can not be guaranteed.One can request the Garbage Collection to happen from within the
java program but there is no guarantee that this request will be taken care of by jvm.

When does an object become eligible for garbage collection?

An object becomes eligible for Garbage Collection when no live thread can access it.

What are the different ways to make an object eligible for Garbage Collection when it is no
longer needed?

a. Set all available object references to null once the purpose of creating the object is served :


public class GarbageCollnTest1 {

public static void main (String [] args){

String str = "Set the object ref to null";
//String object referenced by variable str is not eligible for GC yet

str = null;
/*String object referenced by variable str becomes eligible for GC */

}

}

32

Prepared by Afrina Alam
b. Make the reference variable to refer to another object : Decouple the reference variable from
the object and set it refer to another object, so the object which it was referring to before
reassigning is eligible for Garbage Collection.


publc class GarbageCollnTest2 {

public static void main(String [] args){

String str1 = "Garbage collected after use";
String str2 = "Another String";
System.out.println(str1);
//String object referred by str1 is not eligible for GC yet

str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and the object "Garbage
collected after use" is not referred by any variable and hence is eligible for GC */

}

}

c. Creating Islands of Isolation : If you have two instance reference variables which are
referring to the instances of the same class, and these two reference variables refer to each
other and the objects referred by these reference variables do not have any other valid
reference then these two objects are said to form an Island of Isolation and are eligible for
Garbage Collection.

public class GCTest3 {
GCTest3 g;

public static void main(String [] str){

GCTest3 gc1 = new GCTest3();
GCTest3 gc2 = new GCTest3();
gc1.g = gc2; //gc1 refers to gc2
gc2.g = gc1; //gc2 refers to gc1
gc1 = null;
gc2 = null;
//gc1 and gc2 refer to each other and have no other valid //references
//gc1 and gc2 form Island of Isolation
//gc1 and gc2 are eligible for Garbage collection here

}

}
33

Prepared by Afrina Alam

Can the Garbage Collection be forced by any means?

No. The Garbage Collection can not be forced, though there are few ways by which it can be
requested there is no guarantee that these requests will be taken care of by JVM.

What is the purpose of overriding finalize() method?

The finalize() method should be overridden for an object to include the clean up code or to
dispose of the system resources that should to be done before the object is garbage collected.

If an object becomes eligible for Garbage Collection and its finalize() method has been
called and inside this method the object becomes accessible by a live thread of execution
and is not garbage collected. Later at some point the same object becomes eligible for
Garbage collection, will the finalize() method be called again?

No

How many times does the garbage collector calls the finalize() method for an object?

Only once.

What happens if an uncaught exception is thrown from during the execution of the
finalize() method of an object?

The exception will be ignored and the garbage collection (finalization) of that object terminates.

What are different ways to call garbage collector?

Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().

What is Garbage collection algorithms
Any garbage collection algorithm must do two basic things.
First, it must detect garbage objects.
Second, it must reclaim the heap space used by the garbage objects and make it available to the
program.
Garbage detection is ordinarily accomplished by defining a set of roots and determining
reachability from the roots. An object is reachable if there is some path of references from the
roots by which the executing program can access the object. The roots are always accessible to
the program. Any objects that are reachable from the roots are considered live. Objects that are
not reachable are considered garbage, because they can no longer affect the future course of
program execution.


34

Prepared by Afrina Alam
How does the Garbage Collector know what resource to de-allocate?
An object typically goes through most of the following states between the time it is allocated and
the time its resources are finally returned to the system for reuse.
1. Created
2. In use (strongly reachable) : Objects that are held by at least one strong reference are
considered to be in use
3. Invisible : An object is in the invisible state when there are no longer any strong
references that are accessible to the program, even though there might still be references.
public void run() {
try {
Object foo = new Object();
foo.doSomething();
} catch (Exception e) {
// whatever
}
while (true) { // do stuff } // loop forever
}
the object foo falls out of scope when the try block finishes
4. Unreachable : An object enters an unreachable state when no more strong references to
it exist. When an object is unreachable, it is a candidate for collection
5. Collected : An object is in the collected state when the garbage collector has recognized
an object as unreachable and readies it for final processing as a precursor to deallocation.
If the object has a finalize method, then it is marked for finalization. If it does not have a
finalizer then it moves straight to the finalized state.
6. Finalized : An object is in the finalized state if it is still unreachable after its finalize
method, if any, has been run. A finalized object is awaiting deallocation
7. Deallocated : The deallocated state is the final step in garbage collection. If an object is
still unreachable after all the above work has occurred, then it is a candidate for
deallocation. Again, when and how deallocation occurs is up to the JVM.
What is the impact of the GC on Performance of apps?
GC is automatic in Java and it is low priority task and it runs when there are CPU cycles
available or JVM runs short of memory .But If JVM runs short on memory GC runs
continuously till memory is available , this takes almost 5-15 % of CPU.Two techniques to
reduce GC:
a. Write applications that reuse existing objects [reduce the overheads of creating and
destroying objects but extra work on programmer coz values will need to be reinitialized
prior to use]
b. Use appropriate objects that meet requiremtns [For example for string concatenation use
String Buffer instead of String else every time new string object will be created ]
35

Prepared by Afrina Alam
Key Guidelines

What are the best practice for java programming
Best Practices to improve Java program are as follows :
Avoiding garbage Collection:
GC is automatic in Java and it is low priority task and it runs when there are CPU cycles
available or JVM runs short of memory .But If JVM runs short on memory GC runs
continuously till memory is available , this takes almost 5-15 % of CPU.Two techniques
to reduce GC:
a. Write applications that reuse existing objects [reduce the overheads of creating
and destroying objects but extra work on programmer coz values will need to be
reinitialized prior to use]
b. Use appropriate objects that meet requiremtns [For example for string
concatenation use String Buffer instead of String else every time new string object
will be created ]
Loop Optimization :
Java programs spends maximum time in loop hence we must optimize them
a. Avoid using method call for termination of loop
String str=sdsdsddssdsddffd;
for(j=0;j<str.length;j++) { ----------------------------Avoid

int len=str.length;
for(j=0;j<len;j++) { -------------------------------Use instead
b. Changing the Loop to backwards.JVM is optimized to compare to integers
between -1 and +5.So re writing a loop to compare against 0 will produce faster
loops
for(int j=len-1;j>=0j--) { -----------------------------Better
c. Once processing requirement of loop has completed use break to terminate the
loop .This saves JVM from iterating through loop and evaluating termination
criteria .
d. Using local variables within loop requires less processing than instance variables
as it is a part of object .
Data Structures :
Data structure usage is more common with collection , hence most care should be taken
what collection to be used and where
a. HashSet is faster than TreeSet as TreeSet provides iteration of keys in order
b. Implementation of sets are slower than all other collection hence careful
considerations should be given prior to use.
c. HasTable and HashMap are faster than TreeMap as TreeMap provides iteration of
keys in order
d. Among ArrayList ,Vector, Stack and LinkedList , ArrayList is fastest of the list
classes with Vector and Stack being equal .Vector is slow because it uses
synchronization.Stack uses additional method to for push & pop entries.
e. Arrays provides fastest data structure for storing data.
36

Prepared by Afrina Alam
f. Proper sizing of the collection object is very important with respect to
performance .For eg if number of elements exceed capacity of HashTable
program will end up with multiple nodes that reduces HashTables efficiency , in
addition a larger hashcode will ensure more even distribution within Hashtable &
that improves performance
Synchronization :
Java allows multithreading so that independent operations can overlap . Excessive
synchronization defeats the performance improvements mad possible by multithreading
.Hence design your applications to use minimum amount of synchronization .As
Synchronization involves two major costs :
a. Overheads associated with management of locks by JVM .
b. Defeats the purpose of building multi threaded applications that provide better
performance through parallelism where threads end up waiting up on
synchronized process.
Exception Handling :
a. Simple performance improvement is achieved by placing try-catch block outside
any loops .
b. The other one throw a self defined exception


Explain use of final keyword in java.
A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.
A variable that is declared as final and not initialized is called a blank final variable. A blank
final variable forces the constructors to initialise it.
Java classes declared as final cannot be extended. Restricting inheritance!
Methods declared as final cannot be overridden. In methods private is equal to final, but in
variables it is not.
final parameters values of the parameters cannot be changed after initialization. Do a small
java exercise to find out the implications of final parameters in method overriding.
Java local classes can only reference local variables and parameters that are declared as final.
A visible advantage of declaring a java variable as static final is, the compiled java class
results in faster performance.
final should not be called as constants. Because when an array is declared as final, the state of
the object stored in the array can be modified. You need to make it immutable in order not to
allow modifcations. In general context constants will not allow to modify. In C++, an array
declared as const will not allow the above scenario but java allows. So javas final is not the
general constant used across in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You
must instantiate the variable when you declare it static final.
37

Prepared by Afrina Alam
Definition as per java language specification (third edition) 4.12.4 is A final variable may
only be assigned to onceJava language specification tries to redefine the meaning of constant in
the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-
time constant expression a constant variable. Whether a variable is a constant variable or not may
have implications with respect to class initialization ,binary compatibility and definite
assignment
Static binding vs. Dynamic binding - how can you have dynamic/ static binding in Java?

Dynamic binding is runtime polymorphism and static binding is compile time polymorphism
right

Dynamic binding example would be overriding (Methods are invoked based on object of a class)
Static binding example would be overloading (Methods are invoked based on reference type of a
class)

Dynamic binding means the runtime finds the type of an object (probably from its Class<T>
object) and uses that type to look for the types of methods invoked. As imply, that applies to
overridden class members. And the only kind of class member you can override is an instance
method.

Static binding means the compiler finds the type of an object from the declaration of its reference
and uses that type to look for the types of members. That applies to non-overridden class
members, ie static fields and methods.
Dynamic Binding
In Java, we can assign derived class object to a base class variable. For example, if you have a
class named Vehicle from which you derived the class Car,
Vehicle myVehicle = new Car();
The variable on the left is an object of class Vehicle, but the object on the right is type Car. It
will compile and run successfully but reverse is not possible.
If the Car class has a method that is the same as a method in the Vehicle, then the method in the
derived Car class will be called.
For instance, if both classes define a method called show(), and you do this:
myVehicle.show();
In this case,the method of show() in the Car class will be called.Even though you are using an
Vehicle variable type to call the method show(), the method of show() in the method of Vehicle
class wont be executed. Instead, it is the method of show() in the Car class that will be executed.
38

Prepared by Afrina Alam
The type of the object that is assigned to the Vehicle variable determines the method that is
called. So, when the compiler scans the program and sees a statement like this:
myVehicle.show();

It knows that myVehicle is of type Vehicle, but the compiler also knows that myVehicle can be a
reference to any class derived from Vehicle. Therefore, the compiler doesnt know what version
of show() that statement is calling. Its not until the assignment:
Vehicle myVehicle = new Car();
After executing the method of show() is determined. Since the assignment doesnt occur until
runtime, its not until runtime that the correct method of show() is known. That is known as
dynamic binding or late binding: its not until your program performs some operation at
runtime that the correct version of a method can be determined. In Java, most uses of inheritance
involve dynamic binding.
Static Binding
It occurs when the compiler determines the correct method called from superclass or subclass
something during compile time ,i.e. before the program is executed.
If both the Vehicle class and the Car class have a member variable with the same name, its the
base class version that is used.
Vehicle myVehicle = new Car();
Both the Vehicle and Car classes have a String member variable type, then if you do this:
String str = myVehicle.type;
The value of type can be fully determined by the compiler. Because polymorphism is not
allowed for member variables, that statement is referring to the value of type in the Vehicle
classnot the Cars value for type. The result is: with member variables, its the type of the
variable (e.g. myVehicle) that determines which version is callednot the type of the object the
variable refers to (e.g. Car).
That means if both the Vehicle class and the Car class have a member variable with the same
name, its the base class version that is used.
When the compiler is able to find out the correct version of something during compilation, that is
known as static binding or early binding.


39

Prepared by Afrina Alam
Difference between abstract class and interface, when to go abstract class ?

Java Abstract classes are used to declare common characteristics of subclasses. An abstract
class cannot be instantiated. It can only be used as a superclass for other classes that extend the
abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used
to provide a template or design for concrete subclasses down the inheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics and
methods that describe the actions that a class can perform. An abstract class can include methods
that contain no implementation. These are called abstract methods. The abstract method
declaration must then end with a semicolon rather than a block. If a class has any abstract
methods, whether declared or inherited, the entire class must be declared abstract. Abstract
methods are used to provide a template for the classes that inherit the abstract methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual implementations
must be provided for the abstract methods. Any implementation specified can, of course, be
overridden by additional subclasses. An object must have an implementation for all of its
methods. You need to create a subclass that provides an implementation for the abstract method.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the
sense, when a class extends an abstract class, it cant extend any other class.

Interface In Java, this multiple inheritance problem is solved with a powerful construct called
interfaces. Interface can be used to define a generic template and then one or more abstract
classes to define partial implementations of the interface. Interfaces just specify the method
declaration (implicitly public and abstract) and can only contain fields (which are implicitly
public static final). Interface definition begins with a keyword interface. An interface like that of
an abstract class cannot be instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one
or more interfaces. Java does not support multiple inheritance, but it allows you to extend one
class and implement many interfaces.
If a class that implements an interface does not define all the methods of the interface, then it
must be declared abstract and the method definitions must be provided by the subclass that
extends the abstract class.
When a given interface method is invoked on a given reference, the behavior that results will be
appropriate to the class from which that particular object was instantiated. This is runtime
polymorphism based on interfaces and overridden methods

Differences
1. Abstract class is a class which contain one or more abstract methods, which has to be
implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract
class may contain concrete methods. A Java Interface can contain only method declarations and
public static final constants and doesn't contain their implementation. The classes which
implement the Interface must provide the method definition for all the methods present.

2. Abstract class definition begins with the keyword "abstract" keyword followed by Class
definition. An Interface definition begins with the keyword "interface".

40

Prepared by Afrina Alam
3. Abstract classes are useful in a situation when some general methods should be implemented
and specialization behavior should be implemented by subclasses. Interfaces are useful in a
situation when all its properties need to be implemented by subclasses

4. All variables in an Interface are by default - public static final while an abstract class can have
instance variables.

5. An interface is also used in situations when a class needs to extend an other class apart from
the abstract class. In such situations its not possible to have multiple inheritance of classes. An
interface on the other hand can be used when it is required to implement one or more interfaces.
Abstract class does not support Multiple Inheritance whereas an Interface supports multiple
Inheritances.

6. An Interface can only have public members whereas an abstract class can contain private as
well as protected members.

7. A class implementing an interface must implement all of the methods defined in the interface,
while a class extending an abstract class need not implement any of the methods defined in the
abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract,
then you MUST implement those method in all of the classes which implement that interface.
However, in the case of an abstract class, the method can be simply implemented in the abstract
class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the
actual class. Abstract classes are fast

10.Interfaces are often used to describe the peripheral abilities of a class, and not its central
identity, E.g. an Automobile class might
implement the Recyclable interface, which could apply to many otherwise totally unrelated
objects.

Note: There is no difference between a fully abstract class (all methods declared as abstract and
all fields are public static final) and an interface.

Note: If the various objects are all of-a-kind, and share a common state and behavior, then tend
towards a common base class. If all they
share is a set of method signatures, then tend towards an interface.

Similarities:
Neither Abstract classes nor Interface can be instantiated.


41

Prepared by Afrina Alam
Difference between overriding and overloading, significance of return type wrt the same.?
Overloading is having two methods with the same name but different parameter types in the
same class (different "signatures"). To overload, changing the return type is only not sufficient,
the (number or type of the) input parameters should change.

Overiding method redefines an existing method in a super class, to specify a new behavior in the
sub class. Return type, Parameter type, Parameter Number all must be same. Only body of
method can change.

What is the reason to make a constructor 'private'?
Yes, a constructor can be private. It can still be called within the class, or any enclosing class.
This is common for things like singletons
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
// Prevent instantiation from the outside world (assuming this isn't a nested class)
}
public static Singleton getInstance() {
return instance;
}
}
Private constructors are also used to prevent any instantiation, if you have a utility class which
just has static methods
Advantages and disadvantages with Java - in terms of performance.
Advantages of JAVA

Java is simple: Java was designed to be easy to use and is therefore easy to write, compile,
debug, and learn than other programming languages. The reason that why Java is much simpler
than C++ is because Java uses automatic memory allocation and garbage collection where else
C++ requires the programmer to allocate memory and to collect garbage.

Java is object-oriented: Java is object-oriented because programming in Java is centered on
creating objects, manipulating objects, and making objects work together. This allows you to
create modular programs and reusable code.

Java is platform-independent: One of the most significant advantages of Java is its ability to
move easily from one computer system to another.
42

Prepared by Afrina Alam
The ability to run the same program on many different systems is crucial to World Wide Web
software, and Java succeeds at this by being platform-independent at both the source and binary
levels.

Java is distributed: Distributed computing involves several computers on a network working
together. Java is designed to make distributed computing easy with the networking capability
that is inherently integrated into it.
Writing network programs in Java is like sending and receiving data to and from a file. For
example, the diagram below shows three programs running on three different systems,
communicating with each other to perform a joint task.

Java is interpreted: An interpreter is needed in order to run Java programs. The programs are
compiled into Java Virtual Machine code called bytecode.
The bytecode is machine independent and is able to run on any machine that has a Java
interpreter. With Java, the program need only be compiled once, and the bytecode generated by
the Java compiler can run on any platform.

Java is secure: Java is one of the first programming languages to consider security as part of its
design. The Java language, compiler, interpreter, and runtime environment were each developed
with security in mind.

Java is robust: Robust means reliable and no programming language can really assure reliability.
Java puts a lot of emphasis on early checking for possible errors, as Java compilers are able to
detect many problems that would first show up during execution time in other languages.

Java is multithreaded: Multithreaded is the capability for a program to perform several tasks
simultaneously within a program. In Java, multithreaded programming has been smoothly
integrated into it, while in other languages, operating system-specific procedures have to be
called in order to enable multithreading. Multithreading is a necessity in visual and network
programming.

Disadvantages of JAVA

Performance: Java can be perceived as significantly slower and more memory-consuming than
natively compiled languages such as C or C++.

Look and feel: The default look and feel of GUI applications written in Java using the Swing
toolkit is very different from native applications. It is possible to specify a different look and feel
through the pluggable look and feel system of Swing.

Single-paradigm language: Java is predominantly a single-paradigm language. However, with
the addition of static imports in Java 5.0 the procedural paradigm is better accommodated than in
earlier versions of Java.

43

Prepared by Afrina Alam
How to write efficient program in Java
Write code that is as readable and maintainable as possible.
Have performance goals and benchmarks so you can always measure performance
Put effort into making your architecture perform; it's hard to change that later (compared
with changing implementation)
Think about performance more in terms of complexity of algorithms than "make it 10%
faster": a change from O(n^2) to O(n) is (generally) much more important. (It very much
depends on what the real world usage will be though - if you're only going to be dealing
with small values of n, the "theoretically better" algorithm can easily end up being slower
due to constant factors.)
Use a profiler to determine where your bottlenecks are
Only micro-optimise at the cost of readability when the profiler suggests it's worth doing.
Best Practices
Use shorthand for evaluating Boolean conditions.
Make classes final.
Use int instead of long.
Avoid garbage collection.
Use static variables for Strings.
Avoid the String(String) constructor.
Write efficient loops.
Optimize subexpressions.
Optimize division operations.
Avoid java.util.Enumeration.
Perform casts using instanceof.
Evaluate conditions using instanceof.
Avoid using StringBuffer.append (StringBuffer).
Avoid returning null.
Avoid passing null into methods.
Use caution when passing null into a constructor.
Use long for unique identifiers.
Exit applications correctly.
Print the stack trace.
Using local variables
Using shorthand for evaluating Boolean conditions
Making classes final
Using int instead of long
Avoiding garbage collection
Using static variables for Strings
Avoiding the String(String) constructor
Writing efficient loops
Optimizing subexpressions
Optimizing division operations
44

Prepared by Afrina Alam
Avoiding java.util.Enumeration
Performing casts using instanceof
Evaluating conditions using instanceof
Avoiding StringBuffer.append (StringBuffer)
Avoiding returning null
Avoiding passing null into methods
Using caution when passing null into a constructor
Using longs for unique identifiers
Exiting applications correctly
Printing the stack trace

What is meant by Heap, Constant Pool and Stack?
Java has only two types of memory when it comes to JVM. Heap memory and Non-heap
memory. All the other memory jargons you hear are logical part of either of these two.
Heap Memory : Class instances and arrays are stored in heap memory. Heap memory is also
called as shared memory. As this is the place where multiple threads will share the same data
Non-heap Memory: It comprises of Method Area and other memory required for internal
processing. It stores per-class structures, code for methods and constructors. Per-class structure
means runtime constants and static fields
Memory Pool : Memory pools are created by JVM memory managers during runtime. Memory
pool may belong to either heap or non-heap memory.

Runtime Constant Pool : A run time constant pool is a per-class or per-interface run time
representation of the constant_pool table in a class file. Each runtime constant pool is allocated
from the Java virtual machines method area.
Java Stacks or Frames : Java stacks are created private to a thread. Every thread will have a
program counter (PC) and a java stack. PC will use the java stack to store the intermediate
values, dynamic linking, return values for methods and dispatch exceptions. This is used in the
place of registers

Where are objects stored in memory? Where are the local variables used in the instance
methods stored?
When Each time an object is created in java it goes to area of memory known as heap.
The primitive variables like int and double are allocated in the stack If they are local method
variables.
45

Prepared by Afrina Alam
The primitive variables like int and double are allocated in the heap if they are member variables
like fields of a class
In a multi-threaded application each thread will have its own stack but will share the same heap.
This is why care should be taken in your code to avoid any concurrent access issue in the heap
space. The stack is thread-safe because each thread will have its own stack, but the heap is not
thread safe unless guarded with synchronization through your code

How can you have memory leaks in Java
An object is only counted as being unused when it is no longer referenced. And only objects
which are unused will be recycled by the garbage collector. But there may be an object which is
referenced yet not in use. Under such circumstances the GC cannot recycle that object. If the
programming is not careful and there are many such objects, in that case there can be a
considerable memory leak.
Few examples are below :
Static field holding object reference [esp final field]
class MemorableClass {
static final ArrayList list = new ArrayList(100);
}
(Unclosed) open streams ( file , network etc..)
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
...
...
} catch (Exception e) {
e.printStacktrace();
}

Unclosed connections
try {
Connection conn = ConnectionFactory.getConnection();
...
...
} catch (Exception e) {
e.printStacktrace();
}


46

Prepared by Afrina Alam
How can you make a class immutable ?
Do not provide any methods such as setters or any methods that may alter the properties
of that object. If you do, make sure they return a new instance of your object.
All properties and methods of that object are to be marked as final. Marking the methods
as final is extremely important. We dont want anyone carelessly overridding our
functions that may compromise our immutable behavior.
All properties of that object are to be marked as private.

47

Prepared by Afrina Alam
References

http://www.tutorialspoint.com/java
http://www.javabeginner.com/
http://docs.oracle.com/javase/1.5.0/docs/api/java

Вам также может понравиться