Wednesday, November 30, 2011

Threads Example

This programme checks the numbers between 0 to 100 and prints the numbers that are not divisible by 10 with a sleeping period of 500 milliseconds.

class ThreadExercise extends Thread

    public void run(){
        for(int i=0;i<=100; i++)
        {
            if ((i%10) != 0)
            {
                System.out.println("numbers.... "+i);
                try{
                    Thread.sleep(500);
                }
                catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
            }       
        }
    }
    public static void main(String[] args)
    {
        ThreadExercise te=new ThreadExercise();
        te.start();
    }
}

Sleep() and Wait()

Difference between sleep() and wait() ?

1) wait() is a method of Object class. sleep() is a method of Thread class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object

The javax.servlet.Servlet interface

  ?

init() :     

          public void init(ServletConfig config) throws ServletException

          It is executed only once after the instantiation of servlet to perform initialization
          activities. Web Container doesnot place the servlet into the context if the method
          throws any exception or if the method execution is not completed in the specified
          time.

service() :
            
          public void service(ServletRequest  req,ServletResponse res) throws ServletException,
                                                                                                                        IOException

          This method will be executed for every request. The request and response objects
          created for this request are eligible for garbage collection once the service method
          execution completes succesfully.

destroy() :
  
            public void destroy()
            
            This method is executed only once just before  taking servlet out of  service to
            perform clean up activities.

Sunday, November 27, 2011

Java Programme5

class CGG192{
public static void main(String[] args){
String CG="-" ;
switch(Friends.nares){
case praveen :    CG+="L";
case nares:         CG+="M";
default    : CG+="P";
case aravind :  CG+="Q";
}
System.out.println(CG);
}
}

enum Friends {praveen, aravind, nares}

Ans: -MPQ

We can use enums in switch .

Java Programme4

class ExException
{
   static String v="-" ;
  
    public  static void main(String[] args){
    new ExException().v1();
   System.out.println(v);
   }

     void v1(){
     try{
             v2();

           }
    catch(Exception e){
         s+="C"; 
         }
       }

     void v2() throws Exception{
     v3();     v+="2";
     v3();      v+="2b"
     }
 
    void v3() throws Exception{
          throw new Exception();
    }
   
}

Ans :  -c

Once v3 throws the exception to v2,v2 throws it to v1() and no more of v2()'s code is executed.


Saturday, November 26, 2011

Java Programme3


What will be the result of the following code:

public class Tester {
public static void main(String[] args) {

System.out.print("1");
try {
System.out.print("2");
System.exit(0);
} finally {
System.out.print("3");
}
}

}

Ans : 12 : System.exit(0) will cause the program to exit and finally block will not be executed

Thursday, November 24, 2011

Polymorphism --- OOP Feature

Polymorphism provides one of the most useful programming techniques of the object-oriented paradigm. Polymorphism,  means "many forms," is the ability to treat an object of any subclass of a base class as if it were an object of the base class. A base class has, therefore, many forms: the base class itself, and any of its subclasses. If you need to write code that deals with a family of types, the code can ignore type-specific details and just interact with the base type of the family. Even though the code thinks it is sending messages to an object of the base class, the object's class could actually be the base class or any one of its subclasses. This makes your code easier for you to write and easier for others to understand. It also makes your code extensible, because other subclasses could be added later to the family of types, and objects of those new subclasses would also work with the existing code.

Tuesday, November 22, 2011

Design Pattern -- Singleton

Singleton Design patttern is used to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation arises.To prevent direct instantiation we create a private default constructor,so that other classes can’t create  a new Instance. The following few lines of code demonstrates a way of creating a singleton object.

public class SingletonObject
  {
     private static SingletonObject ref;
     
     private SingletonObject()
      {
      }
    
    public static SingletonObject getSingletonObject()
      {
    if(ref == null)
{
  ref = new SingletonObject();
  return ref;
}
      }

   public Object clone() throws CloneNotSupportedException
{
throws new CloneNotSupportedException();
}
}

Monday, November 21, 2011

Java Programme2

class MyExample{
public static void main(String[] args){
String v="-";
try{
calculate(args[0]);
v=v+"k";
}
finally{
System.out.println(s+="f");}
}
public static void calculate(String b)
{
int y=7/Integer.parseInt(a);
}
}

At the command line :

java MyExample
java MyExample 0

What would be the ouput of the above.

On both the invocations finally block will be executed. ArrayIndexOutOfBoundsException,ArithmeticException will be thrown respectively.

Saturday, November 19, 2011

Java Programme1

public class ExampleClass1 {
public int  exMethod()
{
   int r = 1;
   r+=x;

if( (x>4)  && (x<10) )
{
         r+=2*x;
}
else(x<=4)
{
  r+=3*x;
}
else()
{
r+=4*x;
}
r+=5*x;
return x;
}

public static void main(String[] args)
{
Function1 f1=new Function1();
System.out.println("OF(11)  is "+ f1.exMethod(11));
}
}

The above programme on compilation gives out compilation error. This is because 'if' should not be followed by two 'else' statements immediately.

Appropriate use of Assertions

  • AssertionError is a sub class of Throwable, so it can be caught. But sun not doesnot allow access to the object that generated it. We only get a String message.
  • We should not use Assertions to validate arguments of a public method.
  • We can use Assertions to validate arguments of a private method.
  • We should not use Assertions to validate command line arguments.
  • We should use Assertions which doesnot leave the state of the program in the same state.

Friday, November 18, 2011

Assertions

Assertions in java help us in testing our assumptions during development. The assertion code gets erased when the programme is deployed. While we are developing an application we use 'System.out.println()' in a java class for debugging purpose. We use it inorder to find out any logical problems. Instead we can use Assertions concept.

Ex:

public int myAccNum(int accno)
{
      assert(accno  > 0);// line 1
 
      int myAccno=accno;
}

If the accno is negative on line 1 then the compiler throws an assertion error.

Assertions needed to be turned on then they will work. Other wise the compiler will overlook the Assertion code. There are two ways to write assertion code.

1. assert( X > A);
2. assert(X > A) : "X value is" + X + "A value is" + A


java    -ea        com.venkates.TestClass
java    -enableassertions   com.venkates.Testclass

The above two commands enable assertions at runtime. The below commands disable assertions .

java   -da   com.venkates.TestClass
java   -disableassertions  com.venkates.TestClass