Monday, August 9, 2010

String.contains and String.indexOf

To check if a string contains a substring, I usually use:

if(s.indexOf(sub) >= 0)
For JDK 5 or later, a contains method can also be used, which seems to be a little more readable:
if(s.contains(sub))
The signature of contains method is:
public boolean contains(java.lang.CharSequence s);
Note that CharSequence is a super-interface of String, StringBuffer, StringBuilder, java.nio.CharBuffer, javax.swing.text.Segment. So you can pass any of the 5 types to contains method.

The current implementation of contains method just convert the param to String and calls indexOf.

Tuesday, June 29, 2010

Exceptions in Java

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. 

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.

When a method encounters an abnormal condition (an exception condition) that it can't handle itself, it may throw an exception. Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem that can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem will be dealt with. Exceptions are caught by handlers positioned along the thread's method invocation stack. If the calling method isn't prepared to catch the exception, it throws the exception up to its calling method, and so on. If one of the threads of your program throws an exception that isn't caught by any method along the method invocation stack, that thread will expire. When you program in Java, you must position catchers (the exception handlers) strategically, so your program will catch and handle all exceptions from which you want your program to recover. 

From the base upwards, Java exception classes are organised into a hierarchy. There is a basic exception class called Exception as you might expect. But in fact, the base of the hierarchy starts not with Exception but with a class called Throwable, which is then subclassed into Exception and Error. Part of the hierarchy is illustrated in Figure 
The rationale behind the hierarchy is as follows:
  • 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: for example, network connection errors and filing system errors.
  • 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.
  • RuntimeException is a further subclass of Exception. RuntimeException and itsshouldn'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 badly configured environment.  subclasses are slightly different: they represent exceptions that a program

Checked vs unchecked exceptions:

We mentioned above that certain exceptions are generally indicative of a programming error rather than errors that we'd expect to occur in the normal course of events. (Whereas, it is reasonable for the programmer to expect that a networking or file system error will occur from time to time.) We also mentioned that subclasses of Error are not necessarily programming errors, but still errors that we wouldn't really expect to occur in the normal course of events.
A feature built into the Java language is that Errors and RuntimeExceptions (and their subclasses– marked in red in Figure 1) are what are called unchecked exceptions:
  • unchecked exceptions can be thrown "at any time";
  • methods don't explicitly have to declare that they can throw an unchecked exception;
  • callers don't have to handle them explicitly.

General for of an exception-handling block:
try{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
//…..
finally{
// block of code to be executed before try block ends
}

Monday, June 21, 2010

Factorial Using Recursion - Java

   import java.io*;
     class Factorial{
      public static void main(String[] args) {
          try{
             BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("enter the number");
            int a= Integer.parseInt(object.readLine());
            int fact= 1;
            System.out.println("Factorial of " +a+ ":");   

            System.out.println(factorial(a));
           }
          catch (Exception e){}
         }
      int factorial(int n)
       {
             if (n == 1) {
             return n;
        }
        else {
            return n * factorial(n - 1);
        }
    }
  }

Factorial Examples - Java

import java.io*;
class Factorial{
  public static void main(String[] args) {
      try{
        BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter the number");
        int a= Integer.parseInt(object.readLine());
        int fact= 1;
        System.out.println("Factorial of " +a+ ":");
        for (int i= 1; i<=a; i++){
              fact=fact*i;
        }
        System.out.println(fact);
    }
    catch (Exception e){}
  }
}

Friday, June 11, 2010

Syntel interview questions

How do you manage session?
Difference between hashmap and hashset?
Difference between include and forward?
Difference between forward and sendredirect?
can abstract class contain concrete methods(one with implementation)? if yes then why to make that class abstract and not simple java class?
why do we use/need session beans?
which jdbc driver you have used?
To check object's uniqueness which methods we need to override?
How many times servlet's init() method is called in it's one lifecycle?
Can we call servlet's destroy() method from init() method?
Can we control number of servlet instances created by container?