Popular Posts

Monday, 5 March 2012

Model Java Programs

  1. /*
  2.   Reverse Number using Java
  3.   This Java Reverse Number Example shows how to reverse a given number.
  4. */
  5.  
  6. public class ReverseNumber {
  7.  
  8.         public static void main(String[] args) {
  9.                
  10.                 //original number
  11.                 int number = 1234;
  12.                 int reversedNumber = 0;
  13.                 int temp = 0;
  14.                
  15.                 while(number > 0){
  16.                        
  17.                         //use modulus operator to strip off the last digit
  18.                         temp = number%10;
  19.                        
  20.                         //create the reversed number
  21.                         reversedNumber = reversedNumber * 10 + temp;
  22.                         number = number/10;
  23.                          
  24.                 }
  25.                
  26.                 //output the reversed number
  27.                 System.out.println("Reversed Number is: " + reversedNumber);
  28.         }
  29. }
  30.  
  31. /*
  32. Output of this Number Reverse program would be
  33. Reversed Number is: 4321
  34. */
     
    1. /*
    2.   Find Largest and Smallest Number in an Array Example
    3.   This Java Example shows how to find largest and smallest number in an
    4.   array.
    5. */
    6. public class FindLargestSmallestNumber {
    7.  
    8.         public static void main(String[] args) {
    9.                
    10.                 //array of 10 numbers
    11.                 int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
    12.                
    13.                 //assign first element of an array to largest and smallest
    14.                 int smallest = numbers[0];
    15.                 int largetst = numbers[0];
    16.                
    17.                 for(int i=1; i< numbers.length; i++)
    18.                 {
    19.                         if(numbers[i] > largetst)
    20.                                 largetst = numbers[i];
    21.                         else if (numbers[i] < smallest)
    22.                                 smallest = numbers[i];
    23.                        
    24.                 }
    25.                
    26.                 System.out.println("Largest Number is : " + largetst);
    27.                 System.out.println("Smallest Number is : " + smallest);
    28.         }
    29. }
    30.  
    31. /*
    32. Output of this program would be
    33. Largest Number is : 98
    34. Smallest Number is : 23
    35. */
      1. /*
      2.   Even Odd Number Example
      3.   This Java Even Odd Number Example shows how to check if the given
      4.   number is even or odd.
      5. */
      6.  
      7. public class FindEvenOrOddNumber {
      8.  
      9.         public static void main(String[] args) {
      10.                
      11.                 //create an array of 10 numbers
      12.                 int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
      13.                
      14.                 for(int i=0; i < numbers.length; i++){
      15.                        
      16.                         /*
      17.                          * use modulus operator to check if the number is even or odd. 
      18.                          * If we divide any number by 2 and reminder is 0 then the number is
      19.                          * even, otherwise it is odd.
      20.                          */
      21.                          
      22.                          if(numbers[i]%2 == 0)
      23.                                 System.out.println(numbers[i] + " is even number.");
      24.                          else
      25.                                 System.out.println(numbers[i] + " is odd number.");
      26.                                
      27.                 }
      28.                
      29.         }
      30. }
      31.  
      32. /*
      33. Output of the program would be
      34. 1 is odd number.
      35. 2 is even number.
      36. 3 is odd number.
      37. 4 is even number.
      38. 5 is odd number.
      39. 6 is even number.
      40. 7 is odd number.
      41. 8 is even number.
      42. 9 is odd number.
      43. 10 is even number.
      44. */
         
         
      1.  /*
      2.       Java Factorial Using Recursion Example
      3.         This Java example shows how to generate factorial of a given number
      4.         using recursive function.
      5. */
      6.  
      7. import java.io.BufferedReader;
      8. import java.io.IOException;
      9. import java.io.InputStreamReader;
      10.  
      11. public class JavaFactorialUsingRecursion {
      12.        
      13.         public static void main(String args[]) throws NumberFormatException, IOException{
      14.                
      15.                 System.out.println("Enter the number: ");
      16.                
      17.                 //get input from the user
      18.                 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      19.                 int a = Integer.parseInt(br.readLine());
      20.                
      21.                 //call the recursive function to generate factorial
      22.                 int result= fact(a);
      23.                
      24.                
      25.                 System.out.println("Factorial of the number is: " + result);
      26.         }
      27.        
      28.         static int fact(int b)
      29.         {
      30.                 if(b <= 1)
      31.                         //if the number is 1 then return 1
      32.                         return 1;
      33.                 else
      34.                         //else call the same function with the value - 1
      35.                         return b * fact(b-1);
      36.         }
      37. }
      38.  
      39. /*
      40. Output of this Java example would be
      41.  
      42. Enter the number:
      43. 5
      44. Factorial of the number is: 120
      45. */
       
       
      1. /*
      2.         Swap Numbers Java Example
      3.         This Swap Numbers Java Example shows how to
      4.         swap value of two numbers using java.
      5. */
      6.  
      7. public class SwapElementsExample {
      8.  
      9.         public static void main(String[] args) {
      10.                
      11.                 int num1 = 10;
      12.                 int num2 = 20;
      13.                
      14.                 System.out.println("Before Swapping");
      15.                 System.out.println("Value of num1 is :" + num1);
      16.                 System.out.println("Value of num2 is :" +num2);
      17.                
      18.                 //swap the value
      19.                 swap(num1, num2);
      20.         }
      21.  
      22.         private static void swap(int num1, int num2) {
      23.                
      24.                 int temp = num1;
      25.                 num1 = num2;
      26.                 num2 = temp;
      27.                
      28.                 System.out.println("After Swapping");
      29.                 System.out.println("Value of num1 is :" + num1);
      30.                 System.out.println("Value of num2 is :" +num2);
      31.                
      32.         }
      33. }
      34.  
      35. /*
      36. Output of Swap Numbers example would be
      37. Before Swapping
      38. Value of num1 is :10
      39. Value of num2 is :20
      40. After Swapping
      41. Value of num1 is :20
      42. Value of num2 is :10
      43. */
       
       
      1. /*
      2.         Java Bubble Sort Descending Order Example
      3.         This Java bubble sort example shows how to sort an array of int in descending
      4.         order using bubble sort algorithm.
      5. */
      6.  
      7. public class BubbleSortDescendingOrder {
      8.  
      9.         public static void main(String[] args) {
      10.                
      11.                 //create an int array we want to sort using bubble sort algorithm
      12.                 int intArray[] = new int[]{5,90,35,45,150,3};
      13.                
      14.                 //print array before sorting using bubble sort algorithm
      15.                 System.out.println("Array Before Bubble Sort");
      16.                 for(int i=0; i < intArray.length; i++){
      17.                         System.out.print(intArray[i] + " ");
      18.                 }
      19.                
      20.                 //sort an array in descending order using bubble sort algorithm
      21.                 bubbleSort(intArray);
      22.                
      23.                 System.out.println("");
      24.                
      25.                 //print array after sorting using bubble sort algorithm
      26.                 System.out.println("Array After Bubble Sort");
      27.                 for(int i=0; i < intArray.length; i++){
      28.                         System.out.print(intArray[i] + " ");
      29.                 }
      30.  
      31.         }
      32.  
      33.         private static void bubbleSort(int[] intArray) {
      34.                
      35.                 /*
      36.                  * In bubble sort, we basically traverse the array from first
      37.                  * to array_length - 1 position and compare the element with the next one.
      38.                  * Element is swapped with the next element if the next element is smaller.
      39.                  *
      40.                  * Bubble sort steps are as follows.
      41.                  *
      42.                  * 1. Compare array[0] & array[1]
      43.                  * 2. If array[0] < array [1] swap it.
      44.                  * 3. Compare array[1] & array[2]
      45.                  * 4. If array[1] < array[2] swap it.
      46.                  * ...
      47.                  * 5. Compare array[n-1] & array[n]
      48.                  * 6. if [n-1] < array[n] then swap it.
      49.                  *
      50.                  * After this step we will have smallest element at the last index.
      51.                  *
      52.                  * Repeat the same steps for array[1] to array[n-1]
      53.                  *  
      54.                  */
      55.                
      56.                 int n = intArray.length;
      57.                 int temp = 0;
      58.                
      59.                 for(int i=0; i < n; i++){
      60.                         for(int j=1; j < (n-i); j++){
      61.                                
      62.                                 if(intArray[j-1] < intArray[j]){
      63.                                         //swap the elements!
      64.                                         temp = intArray[j-1];
      65.                                         intArray[j-1] = intArray[j];
      66.                                         intArray[j] = temp;
      67.                                 }
      68.                                
      69.                         }
      70.                 }
      71.        
      72.         }
      73. }
      74.  
      75. /*
      76. Output of the Bubble Sort Descending Order Example would be
      77.  
      78. Array Before Bubble Sort
      79. 5 90 35 45 150 3
      80. Array After Bubble Sort
      81. 150 90 45 35 5 3
      82.  
      83. */
       
      1. /*
      2.         Java Bubble Sort Example
      3.         This Java bubble sort example shows how to sort an array of int using bubble
      4.         sort algorithm. Bubble sort is the simplest sorting algorithm.
      5. */
      6.  
      7. public class BubbleSort {
      8.  
      9.         public static void main(String[] args) {
      10.                
      11.                 //create an int array we want to sort using bubble sort algorithm
      12.                 int intArray[] = new int[]{5,90,35,45,150,3};
      13.                
      14.                 //print array before sorting using bubble sort algorithm
      15.                 System.out.println("Array Before Bubble Sort");
      16.                 for(int i=0; i < intArray.length; i++){
      17.                         System.out.print(intArray[i] + " ");
      18.                 }
      19.                
      20.                 //sort an array using bubble sort algorithm
      21.                 bubbleSort(intArray);
      22.                
      23.                 System.out.println("");
      24.                
      25.                 //print array after sorting using bubble sort algorithm
      26.                 System.out.println("Array After Bubble Sort");
      27.                 for(int i=0; i < intArray.length; i++){
      28.                         System.out.print(intArray[i] + " ");
      29.                 }
      30.  
      31.         }
      32.  
      33.         private static void bubbleSort(int[] intArray) {
      34.                
      35.                 /*
      36.                  * In bubble sort, we basically traverse the array from first
      37.                  * to array_length - 1 position and compare the element with the next one.
      38.                  * Element is swapped with the next element if the next element is greater.
      39.                  *
      40.                  * Bubble sort steps are as follows.
      41.                  *
      42.                  * 1. Compare array[0] & array[1]
      43.                  * 2. If array[0] > array [1] swap it.
      44.                  * 3. Compare array[1] & array[2]
      45.                  * 4. If array[1] > array[2] swap it.
      46.                  * ...
      47.                  * 5. Compare array[n-1] & array[n]
      48.                  * 6. if [n-1] > array[n] then swap it.
      49.                  *
      50.                  * After this step we will have largest element at the last index.
      51.                  *
      52.                  * Repeat the same steps for array[1] to array[n-1]
      53.                  *  
      54.                  */
      55.                
      56.                 int n = intArray.length;
      57.                 int temp = 0;
      58.                
      59.                 for(int i=0; i < n; i++){
      60.                         for(int j=1; j < (n-i); j++){
      61.                                
      62.                                 if(intArray[j-1] > intArray[j]){
      63.                                         //swap the elements!
      64.                                         temp = intArray[j-1];
      65.                                         intArray[j-1] = intArray[j];
      66.                                         intArray[j] = temp;
      67.                                 }
      68.                                
      69.                         }
      70.                 }
      71.        
      72.         }
      73. }
      74.  
      75. /*
      76. Output of the Bubble Sort Example would be
      77.  
      78. Array Before Bubble Sort
      79. 5 90 35 45 150 3
      80. Array After Bubble Sort
      81. 3 5 35 45 90 150
      82.  
      83. */
       
     
    1. /*
    2.   Add an element to specified index of Java ArrayList Example
    3.   This Java Example shows how to add an element at specified index of java
    4.   ArrayList object using add method.
    5. */
    6.  
    7. import java.util.ArrayList;
    8.  
    9. public class AddElementToSpecifiedIndexArrayListExample {
    10.  
    11.   public static void main(String[] args) {
    12.     //create an ArrayList object
    13.     ArrayList arrayList = new ArrayList();
    14.    
    15.     //Add elements to Arraylist
    16.     arrayList.add("1");
    17.     arrayList.add("2");
    18.     arrayList.add("3");
    19.    
    20.     /*
    21.       To add an element at the specified index of ArrayList use
    22.       void add(int index, Object obj) method.
    23.       This method inserts the specified element at the specified index in the
    24.       ArrayList.  
    25.     */
    26.     arrayList.add(1,"INSERTED ELEMENT");
    27.    
    28.     /*
    29.       Please note that add method DOES NOT overwrites the element previously
    30.       at the specified index in the list. It shifts the elements to right side
    31.       and increasing the list size by 1.
    32.     */
    33.  
    34.     System.out.println("ArrayList contains...");
    35.     //display elements of ArrayList
    36.     for(int index=0; index < arrayList.size(); index++)
    37.       System.out.println(arrayList.get(index));
    38.    
    39.   }
    40. }
    41.  
    42. /*
    43. Output would be
    44. ArrayList contains...
    45. 1
    46. INSERTED ELEMENT
    47. 2
    48. 3
    49. */
     
    1. /*
    2.   Iterate through elements Java ArrayList using Iterator Example
    3.   This Java Example shows how to iterate through the elements of java
    4.   ArrayList object using Iterator.
    5. */
    6.  
    7. import java.util.ArrayList;
    8. import java.util.Iterator;
    9.  
    10. public class IterateThroughArrayListUsingIteratorExample {
    11.  
    12.   public static void main(String[] args) {
    13.    
    14.     //create an ArrayList object
    15.     ArrayList arrayList = new ArrayList();
    16.    
    17.     //Add elements to Arraylist
    18.     arrayList.add("1");
    19.     arrayList.add("2");
    20.     arrayList.add("3");
    21.     arrayList.add("4");
    22.     arrayList.add("5");
    23.    
    24.     //get an Iterator object for ArrayList using iterator() method.
    25.     Iterator itr = arrayList.iterator();
    26.    
    27.     //use hasNext() and next() methods of Iterator to iterate through the elements
    28.     System.out.println("Iterating through ArrayList elements...");
    29.     while(itr.hasNext())
    30.       System.out.println(itr.next());
    31.    
    32.   }
    33. }
    34.  
    35. /*
    36. Output would be
    37. Iterating through ArrayList elements...
    38. 1
    39. 2
    40. 3
    41. 4
    42. 5
    43. */
     
    1. /*
    2.   Search an element of Java ArrayList Example
    3.   This Java Example shows how to search an element of java
    4.   ArrayList object using contains, indexOf and lastIndexOf methods.
    5. */
    6.  
    7. import java.util.ArrayList;
    8.  
    9. public class SearchAnElementInArrayListExample {
    10.  
    11.   public static void main(String[] args) {
    12.    
    13.     //create an ArrayList object
    14.     ArrayList arrayList = new ArrayList();
    15.    
    16.     //Add elements to Arraylist
    17.     arrayList.add("1");
    18.     arrayList.add("2");
    19.     arrayList.add("3");
    20.     arrayList.add("4");
    21.     arrayList.add("5");
    22.     arrayList.add("1");
    23.     arrayList.add("2");
    24.  
    25.     /*
    26.       To check whether the specified element exists in Java ArrayList use
    27.       boolean contains(Object element) method.
    28.       It returns true if the ArrayList contains the specified objct, false
    29.       otherwise.
    30.     */
    31.    
    32.     boolean blnFound = arrayList.contains("2");
    33.     System.out.println("Does arrayList contain 2 ? " + blnFound);
    34.  
    35.     /*
    36.       To get an index of specified element in ArrayList use
    37.       int indexOf(Object element) method.
    38.       This method returns the index of the specified element in ArrayList.
    39.       It returns -1 if not found.
    40.     */
    41.  
    42.     int index = arrayList.indexOf("4");
    43.     if(index == -1)
    44.       System.out.println("ArrayList does not contain 4");
    45.     else
    46.       System.out.println("ArrayList contains 4 at index :" + index);
    47.      
    48.     /*
    49.       To get last index of specified element in ArrayList use
    50.       int lastIndexOf(Object element) method.
    51.       This method returns index of the last occurrence of the
    52.       specified element in ArrayList. It returns -1 if not found.
    53.     */
    54.  
    55.     int lastIndex = arrayList.lastIndexOf("1");
    56.     if(lastIndex == -1)
    57.       System.out.println("ArrayList does not contain 1");
    58.     else
    59.       System.out.println("Last occurrence of 1 in ArrayList is at index :"
    60.                                                               + lastIndex);
    61.      
    62.   }  
    63. }
    64. /*
    65. Output would be
    66. Does arrayList contain 2 ? true
    67. ArrayList contains 4 at index :3
    68. Last occurrence of 1 in ArrayList is at index :5
    69. */
     
    1. /*
    2.   Find Minimum element of Java ArrayList Example
    3.   This java example shows how to find a minimum element of Java ArrayList using
    4.   min method of Collections class.
    5. */
    6.  
    7. import java.util.ArrayList;
    8. import java.util.Collections;
    9.  
    10. public class FindMinimumOfArrayListExample {
    11.  
    12.   public static void main(String[] args) {
    13.    
    14.     //create an ArrayList object
    15.     ArrayList arrayList = new ArrayList();
    16.    
    17.     //Add elements to Arraylist
    18.     arrayList.add(new Integer("327482"));
    19.     arrayList.add(new Integer("13408"));
    20.     arrayList.add(new Integer("802348"));
    21.     arrayList.add(new Integer("345308"));
    22.     arrayList.add(new Integer("509324"));
    23.    
    24.     /*
    25.        To find minimum element of Java ArrayList use,
    26.        static Object min(Collection c) method of Collections class.
    27.      
    28.        This method returns the minimum element of Java ArrayList according to
    29.        its natural ordering.
    30.     */
    31.    
    32.     Object obj = Collections.min(arrayList);
    33.    
    34.     System.out.println("Minimum Element of Java ArrayList is : " + obj);
    35.   }
    36. }
    37. /*
    38. Output would be
    39. Minimum Element of Java ArrayList is : 13408
    40. */
     
     
    1. /*
    2.   Find maxmimum element of Java ArrayList Example
    3.   This java example shows how to find a maximum element of Java ArrayList using
    4.   max method of Collections class.
    5. */
    6.  
    7. import java.util.ArrayList;
    8. import java.util.Collections;
    9.  
    10. public class FindMaximumOfArrayListExample {
    11.  
    12.   public static void main(String[] args) {
    13.    
    14.     //create an ArrayList object
    15.     ArrayList arrayList = new ArrayList();
    16.    
    17.     //Add elements to Arraylist
    18.     arrayList.add(new Integer("327482"));
    19.     arrayList.add(new Integer("13408"));
    20.     arrayList.add(new Integer("802348"));
    21.     arrayList.add(new Integer("345308"));
    22.     arrayList.add(new Integer("509324"));
    23.    
    24.     /*
    25.        To find maximum element of Java ArrayList use,
    26.        static Object max(Collection c) method of Collections class.
    27.      
    28.        This method returns the maximum element of Java ArrayList according to
    29.        its natural ordering.
    30.     */
    31.    
    32.     Object obj = Collections.max(arrayList);
    33.    
    34.     System.out.println("Maximum Element of Java ArrayList is : " + obj);
    35.   }
    36. }
    37.  
    38. /*
    39. Output would be
    40. Maximum Element of Java ArrayList is : 802348
    41. */
     
    1. /*
    2.   Add elements at beginning and end of LinkedList Java example
    3.   This java example shows how to add an element at beginning or at end of
    4.   java LinkedList object using addFirst and addLast methods.
    5. */
    6.  
    7. import java.util.LinkedList;
    8.  
    9. public class AddElementsAtStartEndLinkedListExample {
    10.  
    11.   public static void main(String[] args) {
    12.  
    13.     //create LinkedList object
    14.     LinkedList lList = new LinkedList();
    15.    
    16.     //add elements to LinkedList
    17.     lList.add("1");
    18.     lList.add("2");
    19.     lList.add("3");
    20.     lList.add("4");
    21.     lList.add("5");
    22.    
    23.     System.out.println("LinkedList contains : " + lList);
    24.    
    25.     /*
    26.      * To add an element at the beginning of the LinkedList, use
    27.      * void addFirst(Object obj) method.
    28.      *
    29.      * This method inserts object at the beginning of the LinkedList.
    30.      */
    31.    
    32.      lList.addFirst("0");
    33.      System.out.println("After inserting 0 at beginning, LinkedList contains :"
    34.      + lList);
    35.  
    36.     /*
    37.      * To append an element at end of the LinkedList, use
    38.      * void addLast(Object obj) method.
    39.      *
    40.      * This method append specified element at the end of the LinkedList.
    41.      */    
    42.    
    43.      lList.addLast("6");
    44.     System.out.println("After appending 0 at end, LinkedList contains :" + lList);
    45.  
    46.   }
    47. }
    48.  
    49. /*
    50. Output would be
    51.  
    52. LinkedList contains : [1, 2, 3, 4, 5]
    53. After inserting 0 at beginning, LinkedList contains :[0, 1, 2, 3, 4, 5]
    54. After appending 0 at end, LinkedList contains :[0, 1, 2, 3, 4, 5, 6]
    55. */
     
     
    1. /*
    2.   Performing Binary Search on Java int Array Example
    3.   This java example shows how to perform binary search for an element of
    4.   java int array using Arrays class.
    5. */
    6.  
    7. import java.util.Arrays;
    8.  
    9. public class BinarySearchIntArrayExample {
    10.  
    11.   public static void main(String[] args) {
    12.     //create int array
    13.     int intArray[] = {1,2,4,5};
    14.    
    15.     /*
    16.       To perform binary search on int array use
    17.       int binarySearch(int[] b, int value) of Arrays class. This method searches
    18.       the int array for specified int value using binary search algorithm.
    19.      
    20.       Please note that the int array MUST BE SORTED before it can be searched
    21.       using binarySearch method.
    22.      
    23.       This method returns the index of the value to be searched, if found in the
    24.       array.
    25.       Otherwise it returns (- (X) - 1)
    26.       where X is the index where the the search value would be inserted.
    27.       i.e. index of first element that is grater than the search
    28.       value or array.length, if all elements of an array are less than
    29.       the search value.
    30.     */
    31.    
    32.     //sort int array using Arrays.sort method
    33.     Arrays.sort(intArray);
    34.    
    35.     //value to search
    36.     int searchValue = 2;
    37.    
    38.     //since 2 is present in int array, index of it would be returned
    39.     int intResult = Arrays.binarySearch(intArray,searchValue);
    40.     System.out.println("Result of binary search of 2 is : " + intResult);
    41.    
    42.     //lets search something which is not in int array !
    43.     searchValue = 3;
    44.     intResult = Arrays.binarySearch(intArray,searchValue);
    45.     System.out.println("Result of binary search of 3 is : " + intResult);
    46.  
    47.   }
    48. }
    49.  
    50. /*
    51. Output would be
    52. Result of binary search of 2 is : 1
    53. Result of binary search of 3 is : -3
    54. */
     

No comments:

Post a Comment