Sunday, October 24, 2010

Exception in Java

point 1 : For each and every logical error there is a corresponding exception class  in
 java.lang.package.


Question : How Exception Handling Works ?
Ans : Whenever a logical error occurs, the JVM creates corresponding object for that Exception class, and these objects are not explicitly handled, these objects will 
reach back to JVM. JVM accepts these objects and terminates the Program.


Question : What is JVM?
Ans : Java Virtual Machine is a set of Programs.


Question : Define Exception Handling ?
Definition 1 : Concept of Handling the exception class objects by avoiding them to reach 
back to JVM is called to Exception Handling.


Definition 2 :  Exception Handling is a mechanism for handling the exceptions by 
detecting and responding to exceptions in a uniform and reliable manner.


Question : What is the Difference between the throw and throws ?
Answer:
Throws: is used to mention or indicate that to the compiler as well as the end user, 
that a particular function is proven to generate exception class object and those 
 objects are not handled in the function itself.


In Simple Words, we can use the throws clause on the method instead of try and catch
Exception handler.


Throw: is used to explictly transfer the use defined exception class object
 from the function to the calling place.


 The throw keyword (note the singular form) is used to force an exception. 
 Moreover throw keyword can also be used to pass a custom message to the 
  exception handling module.


Question : How to Handle these Exception class objects?
Ans : By assigning them to corresponding exception class.


Question: What are simple logical Errors and Serious logical errors?
Simple logical Errors : can be neglected by the JVM.
Example : Divided by Zero.
Serious logical Errors: cannot be neglected by the JVM.
Example: Out of Heap Memory.


Note: Throwable Class is the super class of Exception and Error Classes.
Note: All classes under Error class are Serious logical errors.
All classes under the Exception class are simple logical errors.


Question: Why cant we write the catch statement like this catch(Throwable t)?
Ans: Throwable class is super class of Error class,and by using the above statement
 we are indirectly handling the Error class Objects,which is not Possible. 
Because  we are not allowed  to handle Serious logical errors.


Question: what is Checked Exception ?
Ans : The Exception Objects for which the compiler compels to handle them are knowns
as checked Exception.
Other Definition : The Exceptions which are checked by the compiler for smooth
execution of program at run time is called Checked Exception.


Example : ClassNotFoundException , IOException,  FilenotFoundException
SQLException.


Question : What is unchecked Exception?
Ans: The Exception Objects for which the compiler does not compels to handle them 
are  known as Un-checked Exception.
Other Definition : The Exceptions which are unable to check by the compiler are 
called UnChecked Exceptions.


Example: ArrayIndexOutOfBound, Divided by Zero. IllegalStateException.
ClassCastException.Arithmetic Exception.


Observation 1: unchecked Exception must extend the Run time Exception class (or)
    Arithmetic Exception (or) Null Pointer Exception Class.
Observation 2: Exception which extends the RunTime Exception class are called 
  unChecked Exception.


Checked Exception :
Observation 1  : Checked exception does not extends the runtimeException class.
Observation 2  : Used to avoid the compile time errors.  


Note: If a method throws an exception then it is may or may not be mandatory to
 call that function from the try and catch Block.


Question: What is the calling function of main method?
Ans : JVM.


Note: If an Exception object reaches the JVM, then program will terminates.


Question : If a Code written outside of the finally block , will that code get executed?
Answer :   try{
                        System.out.println("sekhar");
                 }catch(Exception e ){
                      e.printStackTrace();
               }finally{
                     System.out.println(" i am in Finally Block");
              } System.out.println(" I am Out of the Finally Block");


O/p: :
                    sekhar
                    i am in Finally Block
                    i am out of finally block


Observation : After the finally block the code will execute as usual.


Question : I have written an throw statement and followed by the finally block and
                   a set of statements, will that statements get executed?


Consider this example :
  public static int divideByZero(int first,int second) throws MyException{
try{
if(second == 0){
   throw new MyException("can't divided by Zero ");     
}else{
   System.out.println(" in Else ");
   return first/second;
}finally {     
   System.out.println(" i am in Finally Class");
}
System.out.println(" I am Not Reachable ");


Observation : Finally block will get executed irrespective of the throw statement,
             and after finally block no code is going to execute.


Question : Observe the below code :

public static int divideByZero(int first,int second) throws MyException{
try{
if(second == 0){
   throw new MyException("can't divided by Zero ");     
}else{
   System.out.println(" in Else ");
   return first/second;
}
}catch(Exception e){
   System.out.println("  i am in Exception Class");
}finally {    
   System.out.println(" i am in Finally Class");
}
System.out.println(" I am Out of Finally ");
return 8;
    }


Here the output is :

U Throwed the Exception :can't divided by Zero 
  i am in Exception Class
 i am in Finally Class
 I am Out of Finally 
 Value : 8
Observation :
once we thrown-ed the exception we are catching it in exception block, so the once after
exception is caught, that exception will dead. so here followed by finally block execution
and followed by normal execution of the code.


Observation 1 : Even- though you return a value, the finally block will still get Executed.


Observation 2: throw new MyException("can't divided by Zero ");
                 System.out.println(" Vizag ");
                return 50;


Any Statements written after the throw command those are just unreachable.

Question : Write an Example for the user defined Exception ?
Answer :    public class MyException extends Exception{
    
    public MyException(String exp){

System.out.println(" U Throwed the Exception :"+exp);
    }    
}


------------------This class throws the actual  exception object of above class-----------

public class ThrowException {


    public static int divideByZero(int first,int second) throws MyException{

if(second == 0){
   throw new MyException("can't divided by Zero ");
}else{
   return first/second;
}
    }
    public static void main(String[] args) {  
   try {
int value = divideByZero(4,0);
   } catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
   }
    }
}
------------------------------------------------------------------------
O/p : MyException
at ThrowException.divideByZero(ThrowException.java:12)
at ThrowException.main(ThrowException.java:21)
      U Throwed the Exception :can't divided by Zero.

Observation : A user defined exception class must extends the Exception class.

Question : How will you define an Exception in Java?
Answer 1:  An Exception is an event which occurs during the execution of a program,
that will disrupt the normal flow of the program instructions.
Answer 2 : Exceptions are objects that define the abnormal condition that 
interrupts the normal flow of Execution.

Detailed Exception Hierarchy :
Question : Explain the exception Hierarchy of Exception Handling?
                                 Throwable 
          |----------------------- | ------------------------------------------------|
        Exception                                                                           Error
 | ------------------------------------|                             | ---------------------|
 Interrupted Exception  RunTime                   Thread-Death   Linkage Error.
                         |----------------- | -----------------|
                           Arithmetic     Null Pointer     ClassCast Exception.  



Q)  What will happen to the Exception object after exception handling?
Rep) It will go for Garbage Collector. And frees the memory.



Question : What are the cases of ClassCastException ?
Ans :  u Created a collection suppose TreeSet, and you added some interge values for that
collection.And if you try to insert string Objects into that collection, at run time it throws
it throws ClassCastException Exception.
Example :

package Collection;
import java.util.Set;
import java.util.TreeSet;
public class ClassCast {
public static void main(String[] args) {
Set mySet = new TreeSet();
mySet.add(new Integer(40));
mySet.add(new Integer(50));
mySet.add(new Integer(60));
mySet.add(new Integer(70));
mySet.add(new Integer(80));
mySet.add(new String("my String"));
}
}


o/p :

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at java.lang.String.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at Collection.ClassCast.main(ClassCast.java:22)


Observe the BELOW code CAREFULLY :

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;




public class ExceptionQuestion {


/**
* @param args
*/
public static void main(String[] args) {


try{
BufferedReader bf = new BufferedReader(new FileReader("C:\\Movies\\MyFile.txt"));
throw new FileNotSupportedException();

}catch(FileNotFoundException fnf){
fnf.printStackTrace();
}catch(FileNotSupportedException ffns){
ffns.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}


}



public class FileNotSupportedException extends Exception {


/**
* @param args
*/
FileNotSupportedException(){


}
public static void main(String[] args) {

}
@Override
public String toString(){
return "FileNotSupportedException  Sekhar";

}


}
o?P:::: 
FileNotSupportedException  Sekhar
at ExceptionQuestion.main(ExceptionQuestion.java:17)









static blocks in java

HI,
        What is static block in java ?
Observe the Below program Here:

package newPackage;

public class StaticBlock {

int i;
StaticBlock()
{
System.out.println("Inside Constructor ");
}
static
{
System.out.println(" Inside the static block ");
}
{
System.out.println("Inside the Non static Block ");
}

public static void main(String[] args) {
  System.out.println(" Inside the Main Method ");
  StaticBlock b = new StaticBlock();

}

}

The output of the above program is as follows :

 Inside the static block 
 Inside the Main Method 
Inside the Non static Block 
Inside Constructor 

Saturday, October 23, 2010

Microsoft Interview Questions

HI,
 Recently i had,written test with MIcrosoft.

Here are the Questions

Question 1 : What is the Output of below program?

Question : void main()
{
   int a = 4;
  e(a);
  }
  void e(int n)
{
    if (n>0)
{
   e(--n);
print("%d",n);
e(--n);
}
What is the output : ?





c

Friday, October 22, 2010

Maximum subarray in one dimensional Array


Kadane's algorithm

Kadane's algorithm consists of a scan through the array values, computing at each position the maximum subarray ending at that position. This subarray is either empty (in which case its sum is zero) or consists of one more element than the maximum subarray ending at the previous position. Thus, the problem can be solved with the following code, expressed here in Python:
def max_subarray(A):
    max_so_far = max_ending_here = 0
    for x in A:
        max_ending_here = max(0, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far

Finding least common ancestor of two nodes

Question:

For a binary tree (not BST), this can be done by getting the paths from root to both the nodes and then outputting the node where the path differ for the first time. Can we do better ?
Answer:
Node* LCA(Node *R,Node* P,Node* Q)
{
  if(R == NULL)
        return NULL;
  if(R->left == P || R->right == Q
    || R->left == Q || R->right == P)
      return R;
  Node *f = LCA(R->left,P,Q);
  Node *s = LCA(R->right,P,Q);
  if(f!=NULL && s !=NULL)
        return R;
  else
    return (f == NULL)?s:f;
}

 
 
code.. Explanation :

 
 
I think the code algorithm is as follows:

Inputs: a Root R, two nodes (P, Q) to search for a LCA

Algo: function LCA (R, P, Q)
 - if R is NULL return
 - if the R->left is (P or Q) , or the R->Right is (P or Q)
        then we have the LCA = R and return it
  else --then no node (P or Q) is found as a direct child of R) --
      - search for LCA of (P and Q) using the R->Left as root , call it F
      - search for LCA of (P and Q) using the R->Right as root , call it S

      if (F is LCA AND also S is LCA -not NULLS-)
          this means that we have one of the nodes (P or Q) on the left OR right of R (say Right), AND the other node on the Other Side of R (say left)
      so the Root R is the LCA for (P, Q) -- because it is impossible that we will find another node after further  "Depth First Search" such that P , Q exists on left and right of it

      else if ONLY F is LCA then both (P, Q) are found on the LEFT of R and F is the LCA of them

      else if ONLY S is LCA then both (P, Q) are found on the Right of R and S is the LCA of them

Wednesday, October 20, 2010

Inner Classes in Java

Question : What is inner Class?
Ans : A class defined in another class is known as Inner Class.
Question :What are the Inner Classes in Java?
Ans : i) Member Inner Classes
        ii) Static Inner Classes.
        iii) Local Inner Classes.
        iv) Anonymous Inner Classes.
Question :What is Member Inner Classes?
Example :
        package newPackage;
public class MemberInnerClass {
public static void main(String[] args) {

/*Creating the Inner Class Object */
MemberInnerClass.InnerClass ob = new MemberInnerClass().new InnerClass();
ob.function();
}
int outerClassNonStaticMember = 100;
static int outerClassStaticMember = 300;
class InnerClass
{
int innerClassNonStaticMember = 500;

static int v = 800;


/*Error :  1 We cannot create a static member inside a inner 

class which is not static*/
public void function()
{
System.out.println(" Inside Inner Class 'Function()' ");
outerClassStaticMember = 400;
static int myVar = 500;

/*Error  2 We cannot create a static member in non static block But We can access the static members from // a Non static block.*/

System.out.println("Accessing the outerClass Non Static Member : "+outerClassNonStaticMember);
System.out.println("Accessing the outerClass  Static Member : "+outerClassStaticMember);
outerClassNonStaticFunction();
outerClassStaticFunction();
}
}
public void outerClassNonStaticFunction()
{
System.out.println("Outer Class Non Static Function ");
}
public  static void outerClassStaticFunction()
{
System.out.println(" Outer Class Static Function ");
}
}
  class myClass
  {
 MemberInnerClass.InnerClass ob = new MemberInnerClass().new InnerClass();

/* ERROR  3 We canot create an Object for the private inner class in another class except in Outer Class. */

  }

Key Points :

1) we cannot create static members inside a non-static block.
   i.e., Error 2  
 we can access static members from a Non static block.

2) we cannot create a static member inside a non-static member inner class.
   i.e., Error 1 
  Note : A non static member inner class is just like the non static block in a class.

3)we cannot create an object for the private class in any class except in Outer Class.
 i.e., Error 3

 4) An inner class can extend any class which is available to Outer class.
       /*               Static Inner Class                 */

What is Static inner Class?
Ans :
                   An Inner Class defined as static is called a Static Inner Class.
Example : 
             package newPackage; 
public class StaticInnerClass {
int instanceVariable = 100;
        static int classVariable = 400;   
static class staticClass
{
int staticClassInstanceVariable = 500;
static int staticClassClassVariable = 600;
 
public static void staticFunction()
{  
System.out.println(" Static Function in Static Inner Class");
System.out.println("   "+instanceVariable);//Error 1 
System.out.println("   "+staticClassClassVariable);
}
public void nonStaticFunction()
{
System.out.println(" Non Static Function Inside the  Non Static Inner Class ");
System.out.println(" "+instanceVariable);//Error 1 
System.out.println("   "+staticClassClassVariable);
}
}
public static void main(String[] args) {
StaticInnerClass.staticClass object = new StaticInnerClass.staticClass();
object.staticFunction();
object.nonStaticFunction();//Point 1

}

public void nonStaticOuterClassFunction()
{
System.out.println(" NON Static Function in Outer Class");
StaticInnerClass.staticClass object = new StaticInnerClass.staticClass();
object.staticClassInstanceVariable = 500;
object.nonStaticFunction();
}
}

Important points about the Static Inner Class  


Point 1 :  A non Static function inside an static Inner class is also a static function,
                Because it is Declared in static block.


Notice point 1 in above Program.
  Observation : Here we are accessing a non-static function("nonStaticFunction")
                  where it is declared in static class from a static context in outer class.


  Point 2 : Just like previous Observations, We cannot access the non static members(instance
                  variables) from a static context.


Notice Error1 in above Program.
 Observation : Here we trying to access the instance variables from a static Context.
                         but that is not Possible we cannot access those.
Simply : Static members of a outer class are available to a static Inner class.But
            Non static members of a outer class are not available to static Inner class


Local Inner Class in Java

aWhat is LocalInner Class?
Answer : A Class declared inside a Body of a method is known as "Local Inner Class"
Example :
                    Class LocalInnerClass {
                       int x ;
                       public void function()
                      {
                          int i;
                          final int j = 30;
                          class innerClass
                         {
                               public void innerClassFunction()
                            {
                               System.out.println("Inside the local Inner Class Function");
                               System.out.println(x);
                               System.out.println(i); //Error 
                             }
                          }
                        //Creating the Object for the Local Inner class in method where it is declared.
                           LocalInnerClass lic = new LocalInnerClass();
                              lic .innerClassFunction();
                        }//End of Function
  public static void main(String[] args)
{
     LocalInnerClass ll = new LocalInnerClass();
      ll.function();
}                      
}


Important Points of the Local Inner Class.
Point 1 : Local Inner Class is just like a Local variable to class.
point 2 : As like "access specifiers are not applicable for local variables"
so,we cannot specify the access specifiers for local inner classes.


point 3 : we cannot create the 'localinnerclass' object in the outer class.because the local inner 
class we define inside the local function of the outer class,so that localinnerclass
is available to that local function only.so we can create the object of the inner local
class only in the local function of the outer class.


point 4 : A local inner class, cannot access the local variables of the method/function in which 
it is declared.it can only access the constants(like final) of that method.


 Anonymous InnerClass
What is Anonymous Inner Class?
Ans : An Anonymous inner class is just like the local inner class,but it has two differences
Difference 1 : it does not have the class name as like local inner class.
Difference 2 : As name is not there it does not have the constructor also.


Observation 1 : An Anonymous class does not have the class name
  Example :   
           {
               public void funX()
              {
                 -------------------
                --------------------
              }
              public void funY()
             {
                ...........................
                ..........................
              }
          };
  
Above is the Anonymous inner class.
Observation 2 : Inorder to define an anonymous inner class we definitely need a
 Interface or an Abstract class.
Example :
               Interface myInterface
            {
                  public void funX();
                  public void funnY();
             }
              class Anony1
{
         static myInterface my = new myInterface() {
                                                                   public void funx() {------}
                                                                   public void funy() {------}
                                                                   };
}
  class Test
{
         public static void main()
{
    Anony1.x.funx();
}
}


Example: a very common usage of an anonymous inner class

public class GUI extends JFrame{
...
public void buildComponents(){
...
button1 = newJButton();
...
button1.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent ae){
...
...
}
});
...
...
}
}

Interface = ActionListener 
Anonymous inner class : 

public void actionPerformed(java.awt.event.ActionEvent ae){
...
...
}
}

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...