Wednesday, January 14, 2015

Java Useful Program



Printing Array using Method

import java.util.ArrayList;
import java.util.Vector;
public class Main 
{
public static void main(String[] args) 
 {
   Object testObject = new ArrayList();
      displayObjectClass(testObject);
   }
   public static void displayObjectClass(Object o) 
  {
      if (o instanceof Vector)
      System.out.println("Object was an instance 
      of the class java.util.Vector");
      else if (o instanceof ArrayList)
      System.out.println("Object was an instance of 
      the class java.util.ArrayList");
      else
      System.out.println("Object was an instance of the " + o.getClass());
   }
}

Use of break statement

public class Main 
{
 public static void main(String[] args)
 {
      int[] intary = { 99,12,22,34,45,67,5678,8990 };
      int no = 5678;
      int i = 0;
      boolean found = false;
      for ( ; i < intary.length; i++) 
     {
         if (intary[i] == no) 
        {
            found = true;
            break;
         }
      }
      if (found) 
      {
         System.out.println("Found the no: " + no + " at  index: " + i);
      } 
      else 
     {
         System.out.println(no + "not found  in the array");
      }
   }
}

Use of continue

public class Main 
{
 public static void main(String[] args) 
 {
      StringBuffer searchstr = new StringBuffer("hello how are you. ");
      int length = searchstr.length();
      int count = 0;
      for (int i = 0; i 7lt; length; i++)
        {
         if (searchstr.charAt(i) != 'h')
         continue;
         count++;
         searchstr.setCharAt(i, 'h');
         }
      System.out.println("Found " + count + " h's in the string.");
      System.out.println(searchstr);
   }
}

No comments:

Post a Comment