Wednesday, January 14, 2015

Java Important Program



Use of label in a method

public class Main 
{
 public static void main(String[] args)
 {
      String strSearch = "This is the string in which you 
      have to search for a substring.";
      String substring = "substring";
      boolean found = false;
      int max = strSearch.length() - substring.length();
      testlbl:
      for (int i = 0; i < = max; i++) 
      {
         int length = substring.length();
         int j = i;
         int k = 0;
         while (length-- != 0) 
         {
            if(strSearch.charAt(j++) != substring.charAt(k++)
           {
               continue testlbl;
            }
         }
         found = true;
         break testlbl;
      }
      if (found) 
      {
         System.out.println("Found the substring .");
      }
      else 
      {
         System.out.println("did not find the 
         substing in the string.");
      }
   }
}

Use of enum & switch statement

enum Car 
{
   lamborghini,tata,audi,fiat,honda
}
public class Main 
{
   public static void main(String args[])
   {
      Car c;
      c = Car.tata;
      switch(c) 
      {
         case lamborghini:
         System.out.println("You choose lamborghini!");
         break;
         case tata:
         System.out.println("You choose tata!");
         break;
         case audi:
         System.out.println("You choose audi!");
         break;
         case fiat:
         System.out.println("You choose fiat!");
         break;
         case honda:
         System.out.println("You choose honda!");
         break;
         default:
         System.out.println("I don't know your car.");
         break;
      }
   }
}

Use of Enum constructor, method

enum Car 
{
   lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
   private int price;
   Car(int p) 
   {
      price = p;
   }
   int getPrice() 
  {
      return price;
   } 
}
public class Main 
{
   public static void main(String args[])
  {
      System.out.println("All car prices:");
      for (Car c : Car.values())
      System.out.println(c + " costs " + c.getPrice() + " thousand dollars.");
   }
}

Use for & for each loops

public class Main 
{
public static void main(String[] args)
{
      int[] intary = { 1,2,3,4};
      forDisplay(intary);
      foreachDisplay(intary);
 }
public static void forDisplay(int[] a)
            {  
      System.out.println("Display an array using for loop");
      for (int i = 0; i < a.length; i++) 
      {
         System.out.print(a[i] + " ");
      }
      System.out.println();
   }
   public static void foreachDisplay(int[] data)
   {
      System.out.println("Display an array using for each loop");
      for (int a  : data) 
     {
         System.out.print(a+ " ");
      }
   }
}

No comments:

Post a Comment