Wednesday, December 9, 2015

Language: JAVA (String and arrays)...........

Compiling
javac File.java
Compiling with debugging
javac File.java -g
Executing
java File
java file name and class name must be same. Its better to name a class name befitting what the code does.
For ease, the class  and file name has been kept Example.
javac Example.java
java Example
-------------------------------------------
**********************Strings************************
##Word finding in  a string
public class Example{
   public static void main(String[] args) {
      String strOrig = "Vibrant autumn colors";
      int intIndex = strOrig.indexOf("autumn");
      if(intIndex == - 1){
         System.out.println("autumn not found");
      }else{
         System.out.println("autumn is found at index "
         + intIndex);
      }
   }
}
autumn is found at index 8   
-------------------------------------------
##String comparison
public class Example{
   public static void main(String args[]){
      String str = "Fall Foliage Beauty";
      String String2 = "fall foliage beauty";
      Object objStr = str;

      System.out.println( str.compareTo(String2) );
      System.out.println( str.compareToIgnoreCase(String2) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

-32
-------------------------------------------
##Removal of a particular character of a string (index-based)
public class Example {
   public static void main(String args[]) {
      String str = "Autumn colors";
      System.out.println(removeCharAt(str, 7));
   }
   public static String removeCharAt(String s, int pos) {
      return s.substring(0, pos) + s.substring(pos + 1);
   }
}
Autumn olors 
-------------------------------------------
##Sub-string changing within a string
public class Example{
   public static void main(String args[]){
      String str="sunny, crisp day";
      System.out.println( str.replace( 's','m' ) );
      System.out.println( str.replaceFirst("su", "mo") );
      System.out.println( str.replaceAll("y", "x") );
   }
}
munny, crimp day      
monny, crisp day      
sunnx, crisp dax      
-------------------------------------------
##String reversal
public class Example{
   public static void main(String[] args){
      String string="california";
      String reverse = new StringBuffer(string).
      reverse().toString();
      System.out.println("\nOriginal string: " + string);
      System.out.println("String after reversal: "+ reverse);
   }

}
Original string: california               
String after reversal: ainrofilac         
-------------------------------------------
  ##Finding index of a substring
public class Example {
   public static void main(String[] args) {
      String strOrig = "mango fruits, orange fruit, apple fruit";
      int lastIndex = strOrig.lastIndexOf("fruit");
      if(lastIndex == - 1){
         System.out.println("The word fruit is missing");
      }else{
         System.out.println("The word fruit occurs for the last time at index "+ lastIndex);
      }
   }
}
The word fruit occurs for the last time at index 34   
-------------------------------------------
 ##Breaking a string into many substrings
public class Example{
   public static void main(String args[]){
      String str = "spring:summer:autumn";
      String[] temp;
      String delimeter = ":";
      temp = str.split(delimeter);
   
      for(int i =0; i < temp.length ; i++){
         System.out.println(temp[i]);
         //System.out.println("");
         str = "spring.summer.autumn";
         delimeter = "\\.";
         temp = str.split(delimeter);
      }
      for(int i =0; i < temp.length ; i++){
         System.out.println(temp[i]);
         //System.out.println("");
         temp = str.split(delimeter,1);
         for(int j =0; j < temp.length ; j++){
            System.out.println(temp[j]);
         }
      }
   }
}
spring              
summer              
autumn              
spring              
spring.summer.autumn
-------------------------------------------
##Alphabet case conversion (lower to upper; upper to lower)
public class Example {
   public static void main(String[] args) {
      String str = "deep blue ocean";
      String strUpper = str.toUpperCase();
      System.out.println("Original String: " + str);
      System.out.println("String changed to upper case: "
      + strUpper);
   }
}
Original String: deep blue ocean             
String changed to upper case: DEEP BLUE OCEAN
--------------------------------------
public class Example {
    public static void main(String[] args) {
      String str = "DEEP BLUE OCEAN";
      String strLower = str.toLowerCase();
      System.out.println("Original String: " + str);
      System.out.println("String changed to lower case: "
      + strLower);
    }
}
Original String: DEEP BLUE OCEAN
String changed to lower case: deep blue ocean
-------------------------------------------
##Time taken for string generation
public class Example{
   public static void main(String[] args){
    //Literal way (takes less time)
      long startTime1 = System.currentTimeMillis();
      for(int i=0;i<100000;i++){
         String s1 = "spring";
         String s2 = "spring";
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Time required for generation"
      + " of String literals : "+ (endTime1 - startTime1)
      + " milli seconds" );
    //Object way (takes more time)
      long startTime2 = System.currentTimeMillis();
      for(int i=0;i<100000;i++){
         String s3 = new String("spring");
         String s4 = new String("spring");
    }
      long endTime2 = System.currentTimeMillis();
      System.out.println("Time required for generation"
      + " of String objects : " + (endTime2 - startTime2)
      + " milli seconds");
   }
}
Time required for generation of String literals : 3 milli seconds
Time required for generation of String objects : 13 milli seconds
-------------------------------------------
##Substring matching boolean output 
public class Example{
   public static void main(String[] args){
      String string1 = "rose is fragrant";
      String string2 = "rose has thorns";
      boolean match = string1.regionMatches(0, string2, 0, 4);
      System.out.println("string1== "  + "string2: "+ match);
   }
}
string1==string2: true
##############################################################
**************************Arrays******************************
##Writing output to display
public class Example {
   public static void main(String[] args){
      String[] greeting = new String[3];
      greeting[0] = "Hello";
      greeting[1] = "How are you?";
      greeting[2] = "Hope you are fine.";
      for (int i = 0; i < greeting.length; i++){
         System.out.println(greeting[i]);
      }
   }

}
Hello                                                                            
How are you?                                                                     
Hope you are fine.                                                               
-------------------------------------------
##Sorting an array and finding an item
//This class views arrays as lists, so imported.
import java.util.Arrays;
// Sorting and binary search
public class Example {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 7, -4, 8, 0, 6, -1 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 8);
      System.out.println("Found the element at index " + index + " of the sorted arary");
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if(i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);                  
      }
      System.out.println();
   }
}
Sorted array: [length: 7]                                                                           
-4, -1, 0, 2, 6, 7, 8                                                                               
Found the element at index 6 of the sorted arary                                                    
-------------------------------------------
##Sorting an array and inserting an item
import java.util.Arrays;

public class Example {
   public static void main(String args[]) throws Exception {
      int array[] = { 3, 7, -2, -6, 8 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 2);
      //System.out.println("Didn't find the element at" + index);
     int newIndex = -index - 2;
      array = insertElement(array, 2, newIndex);
      printArray("After adding element 2 ", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length of array: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);      
      }
      System.out.println();
   }
   private static int[] insertElement(int original[],
   int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index
      + 1, length - index);
      return destination;
   }
}
Sorted array: [length of array: 5]                                                                     
-6, -2, 3, 7, 8                                                                                        
After adding element 2 : [length of array: 6]                                                          
-6, 2, -2, 3, 7, 8                                                                                     
-------------------------------------------
##Finding upper bound of 2D array
public class Example {
   public static void main(String args[]) {
      String[][] data = new String[3][8];
      System.out.println("Dimension 1: " + data.length);
      System.out.println("Dimension 2: " + data[0].length);
   }
}
Dimension 1: 3                                                                                         
Dimension 2: 8                                                                                         
-------------------------------------------
##Reversing an array order
//This class views arrays as lists, so imported.
import java.util.ArrayList;
//This class returns collections, so imported
import java.util.Collections;

public class Example {
   public static void main(String[] args) {
      ArrayList arrayList = new ArrayList();
      arrayList.add("orange");
      arrayList.add("apple");
      arrayList.add("quince");
 
      System.out.println("Original order: " + arrayList);
      Collections.reverse(arrayList);
      System.out.println("Reversed order: " + arrayList);
   }
}
Original order: [orange, apple, quince]                                                                
Reversed order: [quince, apple, orange]                                                                
-------------------------------------------

No comments:

Post a Comment