CoreJava Int Nicequestions
CoreJava Int Nicequestions
List interface extends collection interface used to store sequence of elements in collection.
The main difference between List and non list interface are methods based on position.
List contains some specific methods apart from Collection interface methods.
void add(int index, E element); This method inserts the specified element
with the index specified.
2) Vector
3) LinkedList
We use ArrayList mainly when we need faster access and fast iteration of elements in list.
From java 1.4 ArrayList implements RandomAccess interface which is a marker interface
which supports fast and random access.
Advantages :
1) Faster and easier access.
In list we can insert nulls values and list allows duplicate elements.
5) We have to manually write logic for 5) Just a method call would add or remove
inserting and removing elements. elements from list.
vector size increases or decreases when elements are added and removed .
Vector is synchronized .
2) Vector is legacy collection introduced in 1.0 and Arraylist introduced in java 2.0.
Performance wise it is recommended to use arraylist rather than vector because by default
vector is synchronized which reduces performance if only one thread accesses it.
Iterator itr=al.iterator();
2) Call hasNext() method on iterator object in loop as long as hasNext() returns true.
Ex : while(itr.hasNext())
while(itr.hasNext())
{
String str=itr.next();
Methods in iterator :
Method Description
For example : for list traversal order will be sequential, and for set the order cannot be
determined, and for sorted sorted set will sort the elements in sorted order.
List Iterator extends Iterator and all the methods in Iterator will be there in ListIterator too
with some additional methods .
List Iterator doesnt have current element .Position of List Iterator lies between two elements
i.e previous element and next element.
Features of ListIterator :
1) Traversal of List in either direction.
Signature :
public interface ListIterator<E> extends Iterator<E> {
ListIteratormethods :
Method Description
ArrayList is an ordered collection.Inarraylists order remains same in which they are inserted.
But coming to set it is an unordered collection.
2) Linked HashSet
3) TreeSet
Note : For efficiency whenever objects are added to HashSet it need to implement the
hashCode() method.
public class HashSet<E> extends AbstractSet<E>
Features of Treesetare :
2) When we retrieve the elements in treeset we will get elements in sorted order.
If we want to search for an element in collection and does not want any sorting order we go
for HashSet.
TreeSet is preferred
1) if elements are to be maintained in sorting order.
extendsHashSet<E>
Linked HashSet is similar to HashSet but in linked HashSet we maintain order but in
HashSet we dont maintain order. Maintaining order means elements will be retrieved in
order which they are inserted.
A map is an association of key-value pairs. Both keys and values in map are objects.
Features of map :
1) Maps cannot have duplicate keys but can have duplicate value objects.
2) HashMap if faster for insertion and deletion of elements when compared to linked
hashmap. Linked hashmap is preferred only for faster iteration of elements.
extends HashMap<K,V>
implements Map<K,V>
When collection framework was started Hashtable extends Dictionary class and Map
interface.
]It is similar to Hashtable and synchronized version of hashmap but with minor differences.
Concurrent HashMap does not allow null keys and values.
When iterator iterates over collection, collection should not be modified except by that
iterator. Modification means collection cannot be modified by thread when other thread is
iterating, if such modification happens a concurrent modification exception will be
thrown.Such kind of iterators are fail fast iterators.
Fail safe iterators are iterators which does not throw concurrent modification exception,
when one thread modifies collection and other thread in the process of iterating the
collection.
It does not throw concurrent modification exception because when other thread was
iterating it does not modify original list but creates a copy of list with modified contents so
that the iterator wont know the modifications made to original list.
Ex :copyOnWriteArrayList
1) Persistence:
We can write data to a file or database and can be used later by deserializing it.
2) Communication :
To pass an object over network by making remote procedure call.
3) Copying :
XML based data transfer : We can use JIBX or JAXB where we can marshall our objects
data to xml and transfer data and then unmarshall and convert to object.
Syntax:
3) We use ObjectInputStream which extends InputStream used to read objects from stream
Serial version unique identifier is a 64 bit long value .This 64 bit long value is a hash code of
the class name,super interfaces and member. Suid is a unique id no two classes will have
same suid. Whenever an object is serialized suid value will also serialize with it.
When an object is read using ObjectInputStream, the suid is also read. If the loaded class
suid does not match with suid read from object stream, readObject throws an
InvalidClassException.
If we dont define serial version UID JVM will create one suid for us. But it is recommended
to have suid rather than JVM creating because at run time JVM has to compute the
hashcode of all the properties of class. This process makes serialization low. We cant
serialize static fields one exception to this is suid where suid gets serialized along with the
object.
We cant serialize static variables in java. The reason being static variable are class
variables that belongs to a class not to object, but serialization mechanism saves only the
object state not the class state.
239) When we serialize an object does the serialization mechanism
saves its references too?
When we serialize an object even the object it refers must implement serializable then the
reference objects also get serialized. If we dont make reference objects serializable then
we get NotSerializableException.
If we dont want to serialize some fields during serialization we declare those variables as
transient. During deserialization transient variables are initialized with default values for
primitives and null for object references.
4) Iterating collection.
Collection : This is one of the core interface which provides basic functionality for collection.
Collections : Collections contains some utility static methods that operate on collections.
Signature :
public interface Collection<E> extends Iterable<E> {
}
Methods in Collection interface :
3) Queue
Encapsulation is the process of wrapping of code and behaviour in a single unit called class
and preventing from misuse is called encapsulation. Encapsulation exposes only part of
object which are safe to exposed and remaining part of object is kept secured.
Encapsulation is supported through access control in java. There are four types of access
control specifiers(public,private, protected, default) in java which supports encapsulation.
For example tv manufacturers exposes only buttons not all the thousands of electronic
components which it is made up of.
Inheritance is one of the important feature of object oriented language. Inheriting is the
process of acquiring features of others. For example a child acquires the features of their
parents.
In java inheritance is the process of inheriting member of existing classes by extending their
functionality.
The original class is called base class, parent class or super class. The new class derived
from parent is called child class, sub class, and derived class.
We use extends keyword in java to extend a class in java. All java classes extend
java.lang.Object since object class is the super class for all classes in java.
Extendability : We can add new functionality to our application without touching the existing
code.
For example if we take Ms word we came across number of versions of msword such as
word 2003,2007. Everytime they wont write new code they reuse the existing code and
some more features.
Polymorphism is combination of two greek words which mean many forms. In polymorphism
actual type of object involved in method call determines which method to call rather type of
reference variable.
In java 1.4 and earlier one method can override super class method if both methods have
same signature and return types.
From Java 1.5 , a method can override other method if argument types match exactly
though return types are different.(Return type must be subtype of other method).
Example : Class A
A doSomeThing()
Example : Class B
{
B doSomeThing()
From java 1.5 return type for doSomeThing() in Class B is valid . We get compile time error
in 1.4 and earlier.
1) Inheritance
2) Encapsulation
3) Polymorphism
4)Abstraction
If superclass and subclass have same fields subclass cannot override superclass fields. In
this case subclass fields hides the super class fields. If we want to use super class variables
in subclass we use super keyword to access super class variables
When we declare variables variables are created in stack. So when the variable is out of
scope those variables get garbage collected.
In Java we cannot copy two objects but by assigning one reference to other we can copy
objects. For example if we have a reference r1 that point to object .so when we declare
r2=r1, we are assigning reference r1 to r2 so now r2 points to the same object where r1
points. Any changes done by one reference on an object will reflect to other.
1) All the methods defined in interfaces are implicitly abstract even though abstract modifier
is not declared.
2) All the methods in interface are public whether they are declared as public or not.
3) variables declared inside interface are by default public, static and final.
8) We can define a class inside interface and the class acts like inner class to interface.
Q:Local variables are variables which are defined inside a method. When the method is
created local variables gets created in stack memory and this variable gets deleted from
memory once the method execution is done
166) Can we serialize static variables in java?
161) How many times finalize method will be invoked ?who invokes
finalize() method in java?
Finalize () method will be called only once on object. Before the object gets garbage
collected garbage collector will call finalize() method to free the resources. Finalize()
method will be called only when object is eligible for garbage collection
No.Instance variables cant be accessed in static methods. When we try to access instance
variable in static method we get compilation error.
144) Explain about method local inner classes or local inner classes in
java?
Nested classes defined inside a method are local inner classes. We can create objects of
local inner class only inside method where class is defined. A local inner classes exist only
when method is invoked and goes out of scope when method returns
A static nested class has static keyword declared before class definition.
131) Explain IllegalMonitorStateException and when it will be thrown?
IllegalMonitorStateException is thrown when wait(), notify() and notifyAll() are called in non
synchronized context. Wait(), notify(),notifyAll() must always be called in synchronized
context other wise we get this run time exception.
No sleep() method causes current thread to sleep not any other thread
yield() method makes the current running thread to move in to runnable state from running
state giving chance to remaining threads of equal priority which are in waiting state. yield()
makes current thread to sleep for a specified amount of time.There is no guarantee that
moving a current running thread from runnable to running state. It all depends on thread
scheduler it doesnt gurantee anything.
When there are several threads in waiting, thread priorities determine which thread to run.
In java programming language every thread has a priority. A thread inherits priority of its
parent thread. By default thread has normal priority of 5. Thread scheduler uses thread
priorities to decide when each thread is allowed to run. Thread scheduler runs higher
priority threads first
Synchronizing few lines of code rather than complete method with the help of synchronized
keyword are called synchronized blocks.
If we try to restart a dead thread by using start method we will get run time exception since
the thread is not alive
This is first and foremost way to create threads . By implementing runnable interface and
implementing run() method we can create new thread.
To create customized error messages we use userdefined exceptions. We can create user
defined exceptions as checked or unchecked exceptions.
We can create user defined exceptions that extend Exception class or subclasses of
checked exceptions so that userdefined exception becomes checked.
After throw statement jvm stop execution and subsequent statements are not executed. If
we try to write any statement after throw we do get compile time error saying unreachable
code
1) All the subclasses of Throwable class except error,Runtime Exception and its
subclasses are checked exceptions.
2) Checked exception should be thrown with keyword throws or should be provided try
catch block, else the program would not compile. We do get compilation error
In some cases our code may throw more than one exception. In such case we can specify
two or more catch clauses, each catch handling different type of exception. When an
exception is thrown jvm checks each catch statement in order and the first one which
matches the type of exception is execution and remaining catch blocks are skipped
1) Separating normal code from exception handling code to avoid abnormal termination of
program.2) Categorizing in to different types of Exceptions so that rather than handling all
exceptions with Exception root class we can handle with specific exceptions. It is
recommended to handle exceptions with specific Exception instead of handling with
Exception root class.
An abstract method is the method which doesnthaveany body. Abstract method is declared
with keyword abstract and semicolon in place of method body.
We can use all access modifiers public, private,protected and default for method
We cant define package statement after import statement in java. package statement must
be the first statement in source file. We can have comments before the package statement
Static blocks or static initializers are used to initalize static fields in java. we declare static
blocks when we want to intialize static fields in our class. Static blocks gets executed
exactly once when the class is loaded . Static blocks are executed even before
the constructors are executed.