Showing posts with label Software engineer. Show all posts
Showing posts with label Software engineer. Show all posts

Sunday, August 26, 2012

Java Exception Handling Programming Questions


Q) What are the two types of Exceptions?
A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?
A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true?
A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.

Q)Can we have a try block without a catch block?
public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}
finally{
System.out.println("finally");
}
}
}

Output:
=======
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
A) Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Q)Explain try,catch and finally statements in Java ?
The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {
   
} catch (Exception e) {
   
}finally{

}

Example
======

public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}catch(Exception e)
{
System.out.println("Exception caught");
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}

Output:
======
Exception caught
java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)
finally


Q) If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort?
A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){}
4) Have you every created custom exceptions? Explain the scenario?
Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?
A)Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.

Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?
A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?
Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions.
Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?
package com.test;

//NullException is the user exception defined
class NullException extends Exception{

int a;

public NullException(int i) {
i=a;
}

public String toString(){
return "Created NullException:"+a;
}
}
public class CustomException
{

public static void Divide(int a,int b) throws NullException{

int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){

try{

CustomException c=new CustomException();
c.Divide(5, 2);
}catch(Exception e){
System.out.println("Main CustomExceptionm:" +e);
}finally{
System.out.println("Finally Exceuting");
}

}
}

Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?
A) NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.


Q) Can a catch block exist without a try block?
A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?
A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
A) ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.


Q) return statement in try,catch and finally ?
public class ExceptionDemo {

public int chkException(int arr[]){

int k=0;
int t=1,c=2,f=3;
try
{
for(k=0;k<5;k++)
System.out.println("arr Element"+arr[k]);
System.out.println("Try Catch");
return t;
}catch(Exception e){
System.out.println("Failed on exception"+e.getMessage());
System.out.println("Catch Retrun");
return c;
}finally{
System.out.println("Finally Return");
return f;
}
}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();
e.chkException(arr);

}
}

Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally Return

Tuesday, August 21, 2012

Basic String Operations in Java


public class StringOperations {

public static void main(String args[]){
String str1="Hello";
String str2="Ja va";
String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));
System.out.println("String2 at Index 2:"+str2.charAt(2));
System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));
System.out.println("Compare str1 and str3"+str1.compareTo(str3));
System.out.println("String2 contains Ja: "+str2.contains("Ja"));
System.out.println("String is empty ?"+str1.isEmpty());
System.out.println("Sting HashCode"+ str1.hashCode());
System.out.println("Substring of String1"+str1.substring(2, 3));
System.out.println("Remove whitespaces in String2"+str2.trim());
System.out.println("Convert to LowerCase"+str2.toLowerCase());
System.out.println("Replace a with A"+str3.replace('a','A'));
}
}

OutPut:
========
String1 == String3true
String2 at Index 2: 
Compare Str2 and Str32
Compare str1 and str30
String2 contains Ja: true
String is empty ?false
Sting HashCode69609650
Substring of String1l
Remove whitespaces in String2Ja va
Convert to LowerCaseja va
Replace a with AHello

Monday, August 20, 2012

Collection Java Programming Interview Questions 1


Collection API ?
Java Collections framework API is a unified architecture for representing and manipulating collections. All collections frameworks contains interface, implementations and algorithms. Following are the benefits of collection framework.
Reduces programming efforts. - 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.
Encourages & Fosters software reuse.
Collection contains six interfaces.
Set, List and SortedSet: extends collection interface
Map and SortedMap : don’t extend collection interface.a

What is HashMap and Map?
Maps stores key Value pair, and Hashmap is class that implements that using hashing technique.

Diff  HashTable Vs HashMap Vs HashSet

Hashtable
Hashtable is basically a datastructure to retain values of key-value pair. Doesnot allow null for key and values
It is synchronized. So it comes with its cost. Only one thread can access in one time
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Hashtable<Integer,String> rank= new Hashtable<Integer,String>();

rank.put(1,"A");
rank.put(1,"B");
rank.put(1,"C");

rank.put(null,"E"); NullPointerException at runtime

System.out.println(rank.get(1));
System.out.println(rank.get(2));


HashMap
Like Hashtable it also accepts key value pair.Allows null values
It is unsynchronized. So come up with better performance
By using following command Hashmap can be synchronized.
Map m = Collections.synchronizedMap(hashMap);

HashMap<Integer,String> Lang= new HashMap<Integer,String>();

Lang.put(1, "java");
Lang.put(2, null);

HashSet
HashSet does not allow duplicate values.
It can be used where you want to maintain a unique list. You also use its contain method to check whether the object is already available in HashSet.
It provides add method rather put method.

HashSet<String> str= new HashSet<String>();

str.add ("Apple");
str.add ("Boy");
str.add ("Cat");

if (str.contains("Apple"))

Iterator and implementation
An iterator is an object that enables a programmer to traverse a collection.
Iterator iter = list.iterator();
while (iter.hasNext()) {
    System.out.print(iter.next());
    if (iter.hasNext())
      System.out.print(", ");
}

Diff Iterator Vs ListIterator
Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.


Interface Implementation:


Implementations
InterfaceArrayBalanced TreeLinked ListHash table
ListArrayList LinkedList 
Map TreeMap HashMap
Set TreeSet HashSet
DequeArrayDeque LinkedList