Java Tutorials 1-10/56

Java Tutorials


  1. Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
  • Armstrong Number
  • Binary Search
  • Binary Search on Java float Array
  • Recursive Binary Search
  • Bubble Sort
  • Constructor
  • Convert Boolean Object to boolean primitive exmaple
  • Convert Java String to Double Example
  • Data Input Stream
  • Encapsulation 

Name Code

Armstrong Number

     class Armstrong
   {
     public static void main(String args[])
     {
       int num = Integer.parseInt(args[0]);
       int n = num; //use to check at last time
       int check=0,remainder;
       while(num > 0)
       {
         remainder = num % 10;
         check = check + (int)Math.pow(remainder,3);
         num = num / 10;
       }
       if(check == n)
         System.out.println(n+" is an Armstrong Number");
       else
         System.out.println(n+" is not a Armstrong Number");
     }
   } 

Binary Search

      class binary_search
   {
     public static void main(String args[])throws IOException
     {
       int i;
       InputStreamReader x=new InputStreamReader(System.in);
       BufferedReader y=new BufferedReader(x);
       int a[]=new int[10];
       System.out.println("ENTER THE NUMBER TO BE SEARCHED");
       int n=Integer.parseInt(y.readLine());
       System.out.println("ENTER 10 NUMBERS FOR THE ARRAY");
      
       for(i=0;i<10;i++)
       {
         a[i]=Integer.parseInt(y.readLine());
       }
       System.out.println("CONTENTS OF ARRAY ARE");
       for(i=0;i<10;i++)
       {
         System.out.println(a[i]);
       }
       System.out.println("NUMBER TO BE SEARCHED IS "+n);
       int p=-1,mid,l=0,u=9;
       while(l<=u)
       {
         mid=(l+u)/2;
         if(a[mid]==n)
         {
           p=mid;
           break;
         }
         else if(n> a[mid])
         {
           l=mid+1;
         }
         else if(n < a[mid])
         {
           u = mid-1;
         }
       }
       if(p == -1)
       {
         System.out.println("NUMBER DOES NOT EXIST IN THE ARRAY");
       }
       else
       {
         System.out.println("NUMBER EXISTS AT THE INDEX "+p);
       }
     }
   } 

Binary Search on Java float Array

       public class BinarySearchFloatArrayExample
   {
     public static void main(String[] args)
     {
       //create float array
       float floatArray[] = {1.23f,2.10f,4.74f,5.34f};
      
       /*
       To perform binary search on float array use
       int binarySearch(float[] b, float value) of Arrays class. This method searches
       the float array for specified float value using binary search algorithm.
      
       Please note that the float array MUST BE SORTED before it can be searched
       using binarySearch method.
      
       This method returns the index of the value to be searched, if found in the
       array.
       Otherwise it returns (- (X) - 1)
       where X is the index where the the search value would be inserted.
       i.e. index of first element that is grater than the search value
       or array.length, if all elements of an array are less than the
       search value.
       */
      
       //sort float array using Arrays.sort method
       Arrays.sort(floatArray);
      
       //value to search
       float searchValue = 4.74f;
      
       //since 4.74 is present in float array, index of it would be returned
       int intResult = Arrays.binarySearch(floatArray,searchValue);
       System.out.println("Result of binary search of 4.74 is : " + intResult);
      
       //lets search something which is not in float array !
       searchValue = 3.33f;
       intResult = Arrays.binarySearch(floatArray,searchValue);
       System.out.println("Result of binary search of 3.33 is : " + intResult);
     }
   } 

Recursive Binary Search

        public class BinarySearchRecursive
   {
     public static final int NOT_FOUND = -1;
     /**
     * Performs the standard binary search
     * using two comparisons per level.
     * This is a driver that calls the recursive method.
     * @return index where item is found or NOT_FOUND if not found.
     */
     public static int binarySearch( Comparable [ ] a, Comparable x )
     {
       return binarySearch( a, x, 0, a.length -1 );
     }
     /**
     * Hidden recursive routine.
     */
     private static int binarySearch( Comparable [ ] a, Comparable x,int low, int high )
     {
       if( low > high )
         return NOT_FOUND;
       int mid = ( low + high ) / 2;
       if( a[ mid ].compareTo( x ) < 0 )
         return binarySearch( a, x, mid + 1, high );
       else if( a[ mid ].compareTo( x ) > 0 )
         return binarySearch( a, x, low, mid - 1 );
       else
         return mid;
     }
     // Test program
     public static void main( String [ ] args )
     {
       int SIZE = 8;
       Comparable [ ] a = new Integer [ SIZE ];
       for( int i = 0; i < SIZE; i++ )
         a[ i ] = new Integer( i * 2 );
    
       for( int i = 0; i < SIZE * 2; i++ )
         System.out.println( "Found " + i + " at " +
           binarySearch( a, new Integer( i ) ) );
     }
   } 

Bubble Sort

      public class BubbleSort
   {
     public static void main(String[] args)
     {
       //create an int array we want to sort using bubble sort algorithm
       int intArray[] = new int[]{5,90,35,45,150,3};
       //print array before sorting using bubble sort algorithm
       System.out.println("Array Before Bubble Sort");
       for(int i=0; i < intArray.length; i++)
       {
         System.out.print(intArray[i] + " ");
       }
       //sort an array using bubble sort algorithm
        bubbleSort(intArray);
       System.out.println("");
       //print array after sorting using bubble sort algorithm
       System.out.println("Array After Bubble Sort");
       for(int i=0; i < intArray.length; i++)
       {
         System.out.print(intArray[i] + " ");
       }
     }
     private static void bubbleSort(int[] intArray)
     {
       int n = intArray.length;
       int temp = 0;
       for(int i=0; i < n; i++)
       {
          for(int j=1; j < (n-i); j++)
          {
            if(intArray[j-1] > intArray[j])
            {
              //swap the elements!
               temp = intArray[j-1];
              intArray[j-1] = intArray[j];
              intArray[j] = temp;
            }
          }
       }
     }
   }   

Constructor

     class Test
   {
     int studentId;
     public Test(int studentId)
     {
       this.studentId=studentId;
     }
     public int getId()
     {
       return studentId;
     }
   }
   public class Constructor
   {
     public static void main(String args[])
     {
       Test t=new Test(50);
       System.out.println(t.studentId);
       System.out.println(t.getId());
     }
   } 

Convert Boolean Object to boolean primitive exmaple

       public class JavaBooleanTobooleanExample
   {
     public static void main(String[] args)
     {
       //Construct a Boolean object.
       Boolean blnObj = new Boolean("true");
      
       //use booleanValue of Boolean class to convert it into boolean primitive
       boolean b = blnObj.booleanValue();
       System.out.println(b);
      
     }
   } 

Convert Java String to Double Example

       public class JavaStringToDoubleExample
   {
     public static void main(String[] args)
     {
       //We can convert String to Double using one of the following ways.
       //1. Construct Double using constructor.
       Double dObj1 = new Double("100.564");
       System.out.println(dObj1);
      
       //2. Use valueOf method of Double class. This method is static.
       String str1 = "100.476";
       Double dObj2 = Double.valueOf(str1);
       System.out.println(dObj2);
      
       /*
       To convert a String object to a double primitive value parseDouble method
       of Double class. This is a static method.
       */
      
       String str2 = "76.39";
       double d = Double.parseDouble(str2);
       System.out.println(d);
      
       //Please note that these methods can throw a NumberFormatException if
       //string can not be parsed.
      
     }
   } 

DataInputStream 

      public class Test
   {
     public static void main(String args[])throws IOException
     {
       DataInputStream d = new DataInputStream(new FileInputStream("test.txt"));
      
       DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
      
       String count;
       while((count = d.readLine()) != null)
       {
         String u = count.toUpperCase();
         System.out.println(u);
         out.writeBytes(u + " ,");
       }
       d.close();
       out.close();
      
     }
   } 

Encapsulation

      public class EncapTest
   {
     private String name;
     private String idNum;
     private int age;
     public int getAge()
     {
       return age;
     }
     public String getName()
     {
       return name;
     }
     public String getIdNum()
     {
       return idNum;
     }
     public void setAge( int newAge)
     {
       age = newAge;
     }
     public void setName(String newName)
     {
       name = newName;
     }
     public void setIdNum( String newId)
     {
       idNum = newId;
     }
   }
   //The variables of the EncapTest class can be access as below::
   * File name : RunEncap.java */
   public class RunEncap
   {
     public static void main(String args[])
     {
       EncapTest encap = new EncapTest();
       encap.setName("James");
       encap.setAge(20);
       encap.setIdNum("12343ms");
       System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge());
     }
   } 
Java Tutorials 1-10/56 Java Tutorials 1-10/56 Reviewed by Abdul hanan on 04:38:00 Rating: 5
Powered by Blogger.