Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

COREJAVA INTERVIEW QUESTIONS6

Collections Frame Work

Q)
Collection classes Collection Interfaces Legacy classes Legacy interface
Abstract collection Collection Dictionary Enumerator
Abstract List List Hash Table
Abstract Set Set Stack
Array List Sorted Set Vector
Linked List Map Properties
Hash set Iterator
Tree Set
Hash Map
Tree Map

Collection Classes

Abstract collection 

Abstract List 

Abstract Set 

Array List  Array List extends AbstractList and implements the List interface. ArrayList is a variable length of array of object references, ArrayList support dynamic array that grow as needed. A.L allows rapid random access to element but slow for insertion and deletion from the middle of the list.

 ArrayList is a replacement for Vector.

Linked List  Extends AbstactSequentialList and implements List interface. L.L provides optimal sequence access, in expensive insertion and deletion from the middle of the list, relatively slow for random access.

Methods>> void addFirst (Object obj), addLast (Object obj), Object getFirst (), Object getLast ().

Hash Set  HashSet extends AbstractSet implements Set interface, it creates a collection that uses HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet

Methods>> add (), remove (), size ().

Tree Set  Extends Abstract Set implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast.

Hash Map  Extends Abstract Map and implements Map interface. H.P does not guarantee the order of elements, so the order in which the elements are added to a H.P is not necessary the order in which they are ready by the iterate.

 HashMap is similar to Hashtable.

Tree Map  implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allows rapid retrieval.

Collection Interfaces

Collection  Collection is a group of objects, collection does not allow duplicate elements.

Methods>> boolean add (Object obj), boolean addAll (Collection c), Iterator iterator (),
boolean remove(Object obj), boolean removeAll(Collection c).

List  List will extend collection, List stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index.

Methods>> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index).

Set  Set will extend collection, Set cannot contain duplicate elements.

Sorted Set  Extends Set to handle Sorted Sets.
Methods>> Object last (), Object first ().

Map  Map maps unique key to value in a map for every key there is a corresponding value and you will lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map both the “key” & “value” are objects.

Methods>> Object get (Object k), Object put (Object k, Object v).

Iterator  Before accessing a collection through an iterator you must obtain one if the collection classes provide an iterator () method that returns an iterator to the start of the collection. By using iterator object you can access each element in the collection, one element at a time.
Ex: - ArayList arr = new ArrayList ();
Arr.add (“c”);
Iterator itr = arr.iterator ();
While (itr.hashNext ())
{
Object element = itr.next ();
}

List Iterator  List Iterator gives the ability to access the collection, either forward/backward direction

Legacy Classes

Dictionary  is an abstract class that represent key/value storage repository and operates much like “Map” once the value is stored you can retrieve it by using key.

Hash Table  HashTable stores key/value pairs in hash table, HashTable is Synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector.

Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key), Object put(Object key, Object value)

Stack  is a sub class of vector, stack includes all the methods defined by vector and adds several of its own.

Vector  vector holds any type of objects, it is not fixed length and vector is synchronized. We can store primitive data types as well as objects. Default length of vector is up to 10.

Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean removeElementAt(int index), final void removeAllElements().

Properties  is a subclass of HashTable, it is used to maintain the list of values in which the “key/value” is String.

Legacy Interfaces

Enumeration  Define methods by which you can enumerate the elements in a collection of objects. Enumeration is synchronized it having 2 methods hasMoreElements(), nextElement().

Q) Array
Array of fixed length of same data type, we can store primitive data types as well as class objects.
 Arrays are initialized to the default value of their type when they are created, not declared, even if they are local variables

Q) Diff Iterator & Enumeration
Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface which extends from ‘List’ interface. Enumeration is a legacy interface, Enumeration having 2 methods ‘Boolean hasMoreElements()’ & ‘Object NextElement()’. Iterator having 3 methods ‘boolean hasNext()’, ‘object next()’, ‘void remove()’.

Q) List Iterator
It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.

Q) Diff HashTable & HashMap
 Both provide key/value to access the data. The H.T is one of the original collection class in java. H.M is part of new collection frame work.
 H.T is synchronized and H.M is not.
 H.M permits null values in it while H.T does not.
 Iterator in the H.M is fail safe while the enumerator for the H.T is not.






Exception Handling

Object


Throwable

Error Exception

AWT Error Virtual Machine Error
Compile time.Ex Runtime Exception
(checked) (Unchecked)

OutOfMemory.E StackOverFlow.E EOF.E FilenotFound.E
Arithmetic.E NullPointer.E Indexoutof
Bound.E
ArrayIndexoutOfBound.E StirngIndexoutOfBound

Q) Diff Exception & Error
Exception and Error both are subclasses of the Throwable class.

ExceptionException is generated by java runtime system (or) by manually. An exception is a abnormal condition that transfer program execution from a thrower to catcher.
Error Will stop the program execution, Error is a abnormal system condition we cannot handled these.

Q) try, catch, throw, throws

Try  This is used to fix up the error, to prevent the program from automatically terminating, try-catch is used to catching an exception that are thrown by the java runtime system.

Throw  is used to throw an exception explicitly.

Throws  A Throws clause list the type of exceptions that a methods might through.

Q) Checked & UnChecked Exception :-
Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method•

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.


Checked Exceptions Un checked exception
ClassNotFoundException ArithmeticException
NoSuchMethodException ArrayIndexOutOfBoundException
NoSuchFieldException ClasscastException
InterruptedException IllegalArgumentException
IllegalAccessException IllegalMonitorSateException
CloneNotSupportedException IllegalThreadStateException
IndexOutOfBoundException
NullPointerException
NumberFormatException
StringIndexOutOfBounds

OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector is unable to claim any more free memory.
StackOverFlow --> Signals that a stack O.F in the interpreter.
ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or > or equal to the array size.
StringIndexOutOfbound --> For accessing character of a string or string buffer with index values <0 or > or equal to the array size.
Arithmetic Exception --> such as divide by zero.
ArrayStore Exception --> Assignment to an array element of incompatible types.
ClasscastException --> Invalid casting.
IllegalArgument Exception --> Illegal argument is used to invoke a method.
Nullpointer Exception --> If attempt to made to use a null object.
NumberFormat Exception --> Invalid conversition of string to numeric format.
ClassNotfound Exception --> class not found.
Instantion Exception --> Attempt to create an object of an Abstract class or Interface.
NosuchField Exception --> A request field does not exist.
NosuchMethod Exception --> A request method does not exist.

Q) Can I catch an exception and give my own error message?
A) Yes, you can catch servlet errors and give custom error pages for them, but if there are exceptional conditions you can anticipate, it would be better for your application to address these directly and try to avoid them in the first place. If a servlet relies upon system or network resources that may not be available for unexpected reasons, you can use a RequestDispatcher to forward the request to an error page.

RequestDispatcher dispatcher = null;
request.getRequestDispatcher (/err/SQL.jsp);
try {
// SQL operation
}
catch (SQLException se) {
dispatcher.forward (request, response);
}
Web.xml:-


HTTP error code


java.lang.RuntimeException


/err/RuntimeException.jsp



Q) Methods in Exceptions?
A) getMessage (), toString(), printStackTrace(), getLocalizedMessage(),

Q) Primitive multi tasking
If the thread of different priorities shifting the control depends on the priority .i.e; a thread with higher priority is executed first than the thread with lower priority. This process of shifting control is known as primitive multi tasking.


All Packages

Q) Thread Class
Methods: -

getName() run()
getPriority() Sleep()
isAlive() Start()
join()

Q) Object class
All other classes are sub classes of object class; Object class is a super class of all other class.
Methods: -
void notify() void notifyAll()
Object Clone() Sting toString()
Boolean equals(Object object) Void wait()
void finalize() void wait(long milliseconds, int nanoseconds)

Q) throwable class

Methods: -
String getMessage() Void printStackTrace()
String toString() Throwable fillInStackTrace()

Q) Javax.servlet Package

Interfaces Classes Exceptions
Servlet GenericServlet ServletException
ServletConfig ServletInputStream UnavaliableException
ServletContext ServletOutputStream
ServletRequest
ServletResponse
SingleThreadModel

GenericServlet (C) public void destroy ();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
public ServletConfig getServletConfig();
public ServletContext getServletContext();
public String getServletInfo();
public void init(ServletConfig config) throws ServletException;
public void log(String msg);
public abstract void service(ServletRequest req, ServletResponse res)

ServletInputStream (C) public int readLine (byte b [], int off, int len)

ServletOutputStream (C) public void print (String s) throws IOException;
public void println() throws IOException;

Servlet (I)  public abstract void destroy ();
public abstract ServletConfig getServletConfig();
public abstract String getServletInfo();
public abstract void init(ServletConfig config) throws ServletException;
public abstract void service(ServletRequest req, ServletResponse res)

ServletConfig (I)  public abstract String getInitParameter (String name);
public abstract Enumeration getInitParameterNames();
public abstract ServletContext getServletContext();

ServletContext (I)  public abstract Object getAttribute (String name);
public abstract String getRealPath(String path);
public abstract String getServerInfo();
public abstract Servlet getServlet(String name) throws ServletException;
public abstract Enumeration getServletNames();
public abstract Enumeration getServlets();
public abstract void log(Exception exception, String msg);

ServletRequest (I)  public abstract Object getAttribute (String name);
public abstract String getParameter(String name);
public abstract Enumeration getParameterNames();
public abstract String[] getParameterValues(String name);
public abstract String getRealPath(String path);
public abstract String getRemoteAddr();
public abstract String getRemoteHost();
public abstract String getServerName();
public abstract int getServerPort();

ServletResponse (I)  public abstract String getCharacterEncoding ();
public abstract PrintWriter getWriter() throws IOException;
public abstract void setContentLength(int len);
public abstract void setContentType(String type);


Q) Javax.servlet.Http Package

Interfaces Classes Exceptions
HttpServletRequest Cookies ServletException
HttpServletResponse HttpServlet UnavaliableException
HttpSession HttpUtils
HttpSessionContext HttpSessionbindingEvent
HttpSessionBindingListener

Cookies (C)  public Object clone ();
public int getMaxAge();
public String getName();
public String getPath();
public String getValue();
public int getVersion();
public void setMaxAge(int expiry);
public void setPath(String uri);
public void setValue(String newValue);
public void setVersion(int v);

HttpServlet (C)  public void service(ServletRequest req, ServletResponse res)
protected void doDelete (HttpServletRequest req, HttpServletResponse res)
protected void doGet (HttpServletRequest req, HttpServletResponse res)
protected void doOptions(HttpServletRequest req, HttpServletResponse res)
protected void doPost(HttpServletRequest req, HttpServletResponse res)
protected void doPut(HttpServletRequest req, HttpServletResponse res)
protected void doTrace(HttpServletRequest req, HttpServletResponse res)
protected long getLastModified(HttpServletRequest req);
protected void service(HttpServletRequest req, HttpServletResponse res)

HttpSessionbindingEvent (I)  public String getName();
public HttpSession getSession();


HttpServletRequest (I)  public abstract Cookie[] getCookies();
public abstract String getHeader(String name);
public abstract Enumeration getHeaderNames();
public abstract String getQueryString();
public abstract String getRemoteUser();
public abstract String getRequestedSessionId();
public abstract String getRequestURI();
public abstract String getServletPath();
public abstract HttpSession getSession(boolean create);
public abstract boolean isRequestedSessionIdFromCookie();
public abstract boolean isRequestedSessionIdFromUrl();
public abstract boolean isRequestedSessionIdValid();

HttpServletResponse (I)  public abstract void addCookie(Cookie cookie);
public abstract String encodeRedirectUrl(String url);
public abstract String encodeUrl(String url);
public abstract void sendError(int sc, String msg) throws IOException;
public abstract void sendRedirect(String location) throws IOException;
public abstract void setHeader(String name, String value);

HttpSession (I)  public abstract long getCreationTime();
public abstract String getId();
public abstract long getLastAccessedTime();
public abstract HttpSessionContext getSessionContext();
public abstract Object getValue(String name);
public abstract String[] getValueNames();
public abstract void invalidate();
public abstract boolean isNew();
public abstract void putValue(String name, Object value);
public abstract void removeValue(String name);

HttpSessionContext (I)  public abstract Enumeration getIds();
public abstract HttpSession getSession(String sessionId);


Q) java.sql Package

Interfaces Classes Exceptions
Statement DriverManager SQL Exception
PreparedStatement Time ClassNotFoundException
CallableStatement TimeStamp Instantiation Exception
ResultSet
ResultSetMetaData
Connection
Driver

Q) java.lang Package

Interfaces Classes Exceptions
Cloneable Double, Float, Long, Integer, Short, Byte, Boolean, Character, ArithmeticException, ArrayIndexOutOfBoundOf.E, ClassCast.E, ClassNotFound.E
Runnable Class, ClassLoader IlleAcess.E, IllegalArgument.E
Comparable Process, RunTime, Void IllegalSate.E, NullPointer.E
String, StringBuffer NoSuchField.E, NoSuchMethod.E
Thread, ThreadGroup NumberFormat.E

Q) java.IO Package

Interfaces Classes Exceptions
DataInputstream BufferInputstream, BufferOutputStream
DataOutputstream BufferReader, BufferWriter
ObjectInputStream ByteArrayInputStream, ByteArrayOutputstream
ObjectOutputstream CharacterarrayReader, CharacterArayWriter
Serializable DataInputStream, DataOutputStream
Externializable Filereader, FileWriter
ObjectInputStream, ObjectOutputStream

0 comments:

Post a Comment