1. Java Programs cs567
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);
2. Java Programs cs567
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);
}
3. Java Programs cs567
}
}
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);
4. Java Programs cs567
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 );
5. Java Programs cs567
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];
6. Java Programs cs567
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
7. Java Programs cs567
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"));
8. Java Programs cs567
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;
}
9. Java Programs cs567
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());
}
}
Enumerate through a Vector using Java Enumeration Example
public class EnumerateThroughVectorExample
{
public static void main(String[] args)
{
//create a Vector object
Vector v = new Vector();
//populate the Vector
v.add("One");
v.add("Two");
v.add("Three");
v.add("Four");
//Get Enumeration of Vector's elements using elements() method
Enumeration e = v.elements();
/*
Enumeration provides two methods to enumerate through the elements.
It's hasMoreElements method returns true if there are more elements to
enumerate through otherwise it returns false. Its nextElement method returns
the next element in enumeration.
*/
10. Java Programs cs567
System.out.println("Elements of the Vector are : ");
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Exception Handling
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
11. Java Programs cs567
}
}
Create a Thread by Extending Thread
class MyThread extends Thread
{
int count;
MyThread()
{
count = 0;
}
public void run()
{
System.out.println("MyThread starting.");
try
{
do
{
Thread.sleep(500);
System.out.println("In MyThread, count is " + count);
count++;
} while (count < 5);
}
catch (InterruptedException exc)
{
System.out.println("MyThread interrupted.");
}
System.out.println("MyThread terminating.");
}
}
public class Main
{
public static void main(String args[])
{
System.out.println("Main thread starting.");
MyThread mt = new MyThread();
mt.start();
do
{
System.out.println("In main thread.");
12. Java Programs cs567
try
{
Thread.sleep(250);
}
catch (InterruptedException exc)
{
System.out.println("Main thread interrupted.");
}
} while (mt.count != 5);
System.out.println("Main thread ending.");
}
}
Factorial
class Factorial
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]); //take argument as command line
int result = 1;
while(num>0)
{
result = result * num;
num--;
}
13. Java Programs cs567
System.out.println("Factorial of Given no. is : "+result);
}
}
Fibonacci Series
class Fibonacci
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);//taking no. as command line argument.
System.out.println("*****Fibonacci Series*****");
int f1, f2=0, f3=1;
for(int i=1;i<=num;i++)
{
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
14. Java Programs cs567
}
}
File Reader/Writer
public class FileRead
{
public static void main(String args[])throws IOException
{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Thisn isn ann examplen");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}
Java Float Compare Example
public class JavaFloatCompareExample
{
public static void main(String[] args)
{
/*
To compare two float primitive values use
compare(float f1, float f2) method of Float class. This is a static method.
It returns 0 if both the values are equal, returns value less than 0 if
f1 is less than f2, and returns value grater than 0 if f2 is grater than f2.
*/
15. Java Programs cs567
float f1 = 5.35f;
float f2 = 5.34f;
int i1 = Float.compare(f1,f2);
if(i1 > 0)
{
System.out.println("First is grater");
}
else if(i1 < 0)
{
System.out.println("Second is grater");
}
else
{
System.out.println("Both are equal");
}
/*
To compare a Float object with another Float object use
int compareTo(Float f) method.
It returns 0 if both the values are equal, returns value less than 0 if
this Float object is less than the argument, and returns value grater
than 0 if this Float object is grater than f2.
*/
Float fObj1 = new Float("5.35");
Float fObj2 = new Float("5.34");
int i2 = fObj1.compareTo(fObj2);
if(i2 > 0)
{
System.out.println("First is grater");
}
else if(i2 < 0)
{
System.out.println("Second is grater");
}
else
{
System.out.println("Both are equal");
}
16. Java Programs cs567
}
}
Generate Harmonic Series
class HarmonicSeries
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
double result = 0.0;
while(num > 0)
{
result = result + (double) 1 / num;
num--;
}
System.out.println("Output of Harmonic Series is "+result);
}
}
Simple Java HashMap example
public class JavaHashMapExample
{
public static void main(String[] args)
{
//create object of HashMap
HashMap hMap = new HashMap();
/*
17. Java Programs cs567
Add key value pair to HashMap using
Object put(Object key, Object value) method of Java HashMap class,
where key and value both are objects
put method returns Object which is either the value previously tied
to the key or null if no value mapped to the key.
*/
hMap.put("One", new Integer(1));
hMap.put("Two", new Integer(2));
/*
Please note that put method accepts Objects. Java Primitive values CAN NOT
be added directly to HashMap. It must be converted to corrosponding
wrapper class first.
*/
//retrieve value using Object get(Object key) method of Java HashMap class
Object obj = hMap.get("One");
System.out.println(obj);
/*
Please note that the return type of get method is an Object. The value must
be casted to the original class.
*/
}
}
Simple Java HashSet example
public class SimpleHashSetExample
{
public static void main(String[] args)
{
//create object of HashSet
HashSet hSet = new HashSet();
/*
Add an Object to HashSet using
boolean add(Object obj) method of Java HashSet class.
This method adds an element to HashSet if it is not already present in HashSet.
It returns true if the element was added to HashSet, false otherwise.
*/
18. Java Programs cs567
hSet.add(new Integer("1"));
hSet.add(new Integer("2"));
hSet.add(new Integer("3"));
/*
Please note that add method accepts Objects. Java Primitive values CAN NOT
be added directly to HashSet. It must be converted to corrosponding
wrapper class first.
*/
System.out.println("HashSet contains.." + hSet);
}
}
Simple Java Hashtable Example
public class SimpleHashtableExample
{
public static void main(String[] args)
{
//create object of Hashtable
Hashtable ht = new Hashtable();
/*
Add key value pair to Hashtable using
Object put(Object key, Object value) method of Java Hashtable class,
where key and value both are objects
and can not be null.
put method returns Object which is either the value previously tied
to the key or null if no value mapped to the key.
*/
ht.put("One", new Integer(1));
ht.put("Two", new Integer(2));
/*
Please note that put method accepts Objects. Java Primitive values CAN NOT
be added directly to Hashtable. It must be converted to corrosponding
wrapper class first.
*/
//retrieve value using Object get(Object key) method of Java Hashtable class
19. Java Programs cs567
Object obj = ht.get("One");
System.out.println(obj);
/*
Please note that the return type of get method is Object. The value must
be casted to the original class.
*/
}
}
HeapSort
public class HeapSort
{
private static int heapSize; //this will help us to stop sorting list numbers that are already
sorted.
/**
* Sorts the given list in place.
* Worst Case Performance O(nlogn)
* Best Case Performance O(nlogn)
* Average Case Performance O(nlogn)
* @param A - list that needs to be sorted.
*/
public void sortNumbers(int[] A)
{
HeapSort(A);
}
/**
* Read sortNumbers method description.
* @param A - list that needs to be sorted.
*/
private void HeapSort(int[] A)
{
heapSize = A.length; //we need to sort all the list so heapSize == A.length
BuildMaxHeap(A); //first we build max heap
//now we have the biggest element in the heap on the top
//we will exchange it with the last element in the list
//reduce heapSize so this (biggest) element wont be sorted anymore
//and we will call MaxHeapify once again to get new biggest element on the top
//and once again we place it at the current end of the list, we do it all the way
//til we will have only one element left in the heap (which will be the lowest number)
//this way our array will get sorted, from smallest (at the start of the list) to biggest (at
the end of the list).
20. Java Programs cs567
for (int i = A.length-1; i>0; i--)
{
//exchange biggest number with the current last one
int temp = A[0];
A[0] = A[i];
A[i] = temp;
//reduce the heap size
heapSize--;
//find new biggest
MaxHeapify(A,0);
}
}
/**
* Builds MaxHeap (runs in linear time so: O(n) )
* if n = amount of numbers in the list, then n/2 = amount of leaves (nodes that have no
children)
* We need to call MaxHeapify from bottom and up, but we can skip all leaves so we start
at index = n/2 and go up.
* @param A - list that we will build MaxHeap of.
*/
private void BuildMaxHeap(int[] A)
{
for(int i = A.length/2-1;i>=0;i--)
{
MaxHeapify(A, i);
}
}
/**
* Takes O(logn) or we can also say that if subtree with root at index i has height of h
* then running time of algorithm is O(h) (note that a binary tree with n elements has
height = logn)
* Sorts the array at the given index so that subtree meets heap requirements.
* @param A array list
* @param i index of the root of subtree that might be smaller than its children.
*/
private void MaxHeapify(int[] A, int i)
{
int l = Left(i); //lets find left child of the given index.
int r = Right(i);//lets find right child of the given index.
int max;
if (l < heapSize)
{
//lets check if left child is an existing child
21. Java Programs cs567
//if it is an existing child
if (A[l] > A[i])
{
//if left child is bigger than parent
max = l; //left child becomes maximum
}
else
{
max = i; //otherwise parent is maximum
}
}
else
{
//if this index does not have left child
max = i;
}
if (r < heapSize)
{
//lets check if the right child is an existing child
//if it is existing child
if(A[r] > A[max])
{
//if right child is bigger than our current maximum
max = r; //right child becomes our new maximum
}
}
if (max != i)
{
//if our parent is not maximum
//we need to swap max with parent
int temp = A[i];
A[i] = A[max];
A[max] = temp;
//at the end we need to run MinHeapify on the child that was just swapped
//and see if it is supposed to go even further down the list
MaxHeapify(A, max);
}
}
/**
* Returns Left child index of the given parent index.
* @param i - parent index.
* @return - index of parents left child.
*/
22. Java Programs cs567
private int Left(int i)
{
return 2 * i;
}
/**
* Returns Right child index of the given parent index.
* @param i - parent index.
* @return - index of parents right child.
*/
private int Right(int i)
{
return (2 * i) + 1;
}
/**
* Just for testing purposes.
*/
public static void main(String[] args)
{
int[] list = {156,344,54,546,767,23,34,64,234,654,234,
65,234,65,87,3,5,76,24,2,3,7,9,5,34,32,
4525,345,0};
HeapSort hs = new HeapSort();
hs.sortNumbers(list);
for (int i = 0;i < list.length;i++)
{
System.out.println(list[i]);
}
}
}
InsertionSort
public class InsertionSort
{
/**
* Sorts the given list in place.
* Worst Case Performance O(n^2)
* Best Case Performance O(n)
* Average Case Performance O(n^2)
* @param list - int array that you want to sort.
*/
23. Java Programs cs567
public static void sortNumbers(int[] list)
{
//go through the list of the numbers, starting with number two (we say that number
one is already sorted)
for (int i=1; i< list.length -1; i++)
{
//store the value of the number we are dealing with (because it's place can be taken
by other bigger numbers)
int value = list[i];
//define j (its a pointer to the already sorted list, starting at the largest number - back
of the sorted list)
int j = i-1;
//as long as value is lower than the number in sorted list and we are still in the list
while (j >= 0 && list[j] > value)
{
// we are going to move the higher number(from the sorted list) one step to the
right (so it will make space for the current value number - witch is lower)
list[j+1] = list[j];
//and we move our pointer in the list to next place - lower number
j--;
}
//once we come to the right spot, we insert our value number in there and start with
next i value.
list[j+1] = value;
}
}
}
ArrayList using Iterator Example
public class IterateThroughArrayListUsingIteratorExample
{
public static void main(String[] args)
{
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
24. Java Programs cs567
//get an Iterator object for ArrayList using iterator() method.
Iterator itr = arrayList.iterator();
//use hasNext() and next() methods of Iterator to iterate through the elements
System.out.println("Iterating through ArrayList elements...");
while(itr.hasNext())
System.out.println(itr.next());
}
}
Iterate through a Collection using Java Iterator Example
public class JavaIteratorExample
{
public static void main(String[] args)
{
//create an ArrayList object
ArrayList aList = new ArrayList();
//populate ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
/*
Get Iterator object by invoking iterator method of collection.
Iterator provides hasNext() method which returns true if has more
elements. next() method returns the element in iteration.
*/
Iterator itr = aList.iterator();
//iterate through the ArrayList values using Iterator's hasNext and next methods
while(itr.hasNext())
System.out.println(itr.next());
/*
Please note that next method may throw a java.util.NoSuchElementException
if iteration has no more elements.
*/
25. Java Programs cs567
}
}
Java Boolean Example
public class JavaBooleanExample
{
public static void main(String[] args)
{
//Create an Boolean object using one the below given ways
//1. Create an Boolean object from boolean value
Boolean blnObj1 = new Boolean(true);
/*
2. Create an Boolean object from String. It creates a Boolean object
representing true if the string is not null and equals to true. Otherwise
it creates Boolean object representing false.
*/
Boolean blnObj2 = new Boolean("false");
//print value of Boolean objects
System.out.println(blnObj1);
System.out.println(blnObj2);
}
}
Linear Search
public class LinearSearch
{
public int find(final int[] data, final int key)
{
for (int i = 0; i < data.length; ++i)
{
if (data[i] > key)
return -1;
else if (data[i] == key)
return i;
}
return -1;
}
public static void main(String[] args)
{
final int arr[] = new int[10];
26. Java Programs cs567
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++)
{
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length))
{
System.out.println("Found at index: " + n);
}
else
{
System.out.println("Not Found");
}
}
}
Simple Java LinkedHashMap example
public class JavaLinkedHashMapExample
{
public static void main(String[] args)
{
//create object of LinkedHashMap
LinkedHashMap lHashMap = new LinkedHashMap();
/*
Add key value pair to LinkedHashMap using
Object put(Object key, Object value) method of Java LinkedHashMap class,
where key and value both are objects
put method returns Object which is either the value previously tied
to the key or null if no value mapped to the key.
*/
lHashMap.put("One", new Integer(1));
lHashMap.put("Two", new Integer(2));
/*
Please note that put method accepts Objects. Java Primitive values CAN NOT
27. Java Programs cs567
be added directly to LinkedHashMap. It must be converted to corrosponding
wrapper class first.
*/
//retrieve value using Object get(Object key) method of Java LinkedHashMap class
Object obj = lHashMap.get("One");
System.out.println(obj);
/*
Please note that the return type of get method is an Object. The value must
be casted to the original class.
*/
}
}
LinkedHashSet Example
public class SimpleLinkedHashSetExample
{
public static void main(String[] args)
{
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
/*
Add an Object to LinkedHashSet using
boolean add(Object obj) method of Java LinkedHashSet class.
This method adds an element to LinkedHashSet if it is not
already present in LinkedHashSet.
It returns true if the element was added to LinkedHashSet, false otherwise.
*/
lhashSet.add(new Integer("1"));
lhashSet.add(new Integer("2"));
lhashSet.add(new Integer("3"));
/*
Please note that add method accepts Objects. Java Primitive values CAN NOT
be added directly to LinkedHashSet. It must be converted to corrosponding
wrapper class first.
*/
28. Java Programs cs567
System.out.println("LinkedHashSet contains.." + lhashSet);
}
}
LinkedList Example
public class SimpleJavaLinkedListExample
{
public static void main(String[] args)
{
//create LinkedList object
LinkedList lList = new LinkedList();
//add elements to LinkedList
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
/*
* Please note that primitive values can not be added into LinkedList
* directly. They must be converted to their corrosponding wrapper class.
*/
System.out.println("LinkedList contains : " + lList);
}
}
MergeSort
public class MergeSort
{
/**
* Merges two arrays into one.
* @param A array that contains the two arrays.
* @param temp temporary array that we will work with
* @param lo lowest index value in the array
* @param mid middle index value in the array (represents break between low and high
values)
* @param hi highest index value in the array
*/
private static void Merge(int[] A, int[] temp, int lo, int mid, int hi)
29. Java Programs cs567
{
int i = lo;
int j = mid;
for (int k = lo; k < hi; k++)
{
if (i == mid) temp[k] = A[j++]; //if lo-mid array is empty
else if (j == hi) temp[k] = A[i++]; //if mid-hi array is empty
else if (A[j] > A[i]) temp[k] = A[i++]; //i is lower so we put it in the array first
else temp[k] = A[j++]; //j is lower or equal to i, so we put it in the array first.
}
//now we need to copy back temp array to its place in A array
for (int k = lo; k < hi; k++)
A[k] = temp[k]; //we are copying only the numbers we just merged.
}
private static void MergeSort(int[] A, int lo, int hi)
{
if (hi - lo == 1) return; //only one element in the array, return.
int mid = lo + (hi - lo) / 2; //find middle
MergeSort(A, lo, mid); //sort first part
MergeSort(A, mid, hi); //sort second part
Merge(A, new int[A.length], lo, mid, hi); //merge both parts
}
/**
* Sorts the given list. (Not in place)
* Worst Case Performance O(nlogn)
* Best Case Performance O(nlogn)
* Average Case Performance O(nlogn)
* @param A list of int array.
*/
public static void sortNumbers(int[] A)
{
MergeSort(A, 0, A.length);
}
/**
* Just for testing purposes.
*/
public static void main(String[] args)
{
int[] list = {156,344,54,546,767,23,34,64,234,654,
234,65,234,65,87,3,5,76,24,2,3,7,
9,5,34,32,4525,345,0};
sortNumbers(list);
30. Java Programs cs567
for (int i = 0;i< list.length;i++)
{
System.out.println(list[i]);
}
}
}
Method Overriding
class A
{
String name() { return "A"; }
}
class B extends A
{
String name() { return "B"; }
}
class C extends A
{
String name() { return "C"; }
}
public class Overriding
{
public static void main(String[] args)
{
A[] tests = new A[] { new A(), new B(), new C() };
for (int i = 0; i < tests.length; i++)
System.out.print(tests[i].name());
}
}
Number is Even Or Odd with Average
class EvenOdd_Avg
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
while(n > 0)
{
if(n%2==0)
{
cntEven++;
31. Java Programs cs567
sumEven = sumEven + n;
}
else
{
cntOdd++;
sumOdd = sumOdd + n;
}
n--;
}
int evenAvg,oddAvg;
evenAvg = sumEven/cntEven;
oddAvg = sumOdd/cntOdd;
System.out.println("Average of first N Even no is "+evenAvg);
System.out.println("Average of first N Odd no is "+oddAvg);
}
}
Palindrome
class Palindrome
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(reverse == n)
System.out.println(n+" is a Palindrome Number");
else
System.out.println(n+" is not a Palindrome Number");
}
}
Polymorphism
class Box
{
int w,h;
32. Java Programs cs567
void info()
{
System.out.println("This is a simple box");
System.out.println("width = "+ w + " hieght "+ h);
}
}
class WoddenBox extends Box
{
int life;
void info( )
{
System.out.println("This is a Wodden box");
}
}
class SteelBox extends Box
{
int wg;
void info( )
{
System.out.println("This is a steel box");
}
}
class LargeWoddenBox extends WoddenBox
{
void info()
{
System.out.println("This is a Huge Wodden box");
}
}
class BoxDemo
{
public static void main ( String ary[ ] )
{
Box x;
Box b1 =new Box( );
WoddenBox wb=new WoddenBox( );
SteelBox s1=new SteelBox( );
LargeWoddenBox p1=new LargeWoddenBox( );
b1.info( );
wb.info( );
s1.info( );
p1.info( );
33. Java Programs cs567
}
}
Prime Number
class PrimeNo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i< num;i++)
{
if(num%i==0)
{
System.out.println(num+" is not a Prime Number");
flag = 1;
break;
}
}
if(flag==0)
System.out.println(num+" is a Prime Number");
}
}
Setting Priorities on the Thread objects
public class Main
{
public static void main(String[] args) throws Exception
{
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
class TestThread implements Runnable
{
int id;
34. Java Programs cs567
public TestThread(int id)
{
this.id = id;
}
public void run()
{
for (int i = 1; i <= 10; i++)
{
System.out.println("Thread" + id + ": " + i);
}
}
}
All Real Solutions to the Quadratic Equation
class Quadratic
{
public static void main(String args[])throws IOException
{
double x1,x2,disc,a,b,c;
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter a,b,c values");
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
{
System.out.println("roots are real and equal ");
x1=x2=-b/(2*a);
System.out.println("roots are "+x1+","+x2);
}
else if(disc>0)
{
System.out.println("roots are real and unequal");
x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b+Math.sqrt(disc))/(2*a);
System.out.println("roots are "+x1+","+x2);
}
else
{
System.out.println("roots are imaginary");
35. Java Programs cs567
}
}
}
QuickSort
public class QuickSort
{
/**
* Sorts the given list in place.
* Worst Case Performance O(n^2)
* Best Case Performance O(nlogn)
* Average Case Performance O(nlogn)
* @param list - int array that you want to sort.
*/
public void sortNumbers(int[] list)
{
Quicksort(list, 0,list.length-1);
}
public void Quicksort(int[] A, int start, int end)
{
if (start < end)
{
//we partition the list and get back two lists (lower than pivot, and bigger than pivot)
int middle = Partition(A, start, end);
//we then do a recursive call to sort out lower numbers than pivot
Quicksort(A, start, middle-1);
//and we do same with higher numbers than pivot
Quicksort(A, middle+1, end);
//NOTE: pivot is already in it's place, where he supposed to be (in a sorted list).
}
}
public int Partition (int[] A, int start, int end)
{
int pivot = A[end]; //we define pivot (the number we will be comparing other numbers
to
int lo = start-1; // we define low value index
for (int hi = start; hi < end; hi++)
{
//we go throug the list, compare other numbers to pivot
if (A[hi] <= pivot)
{
//if pivot is lower that the current number
36. Java Programs cs567
lo++; //we increase lo value
//and exchange current lo with hi (so we will have all lower numbers than pivot on
one side)
int temp = A[lo];
A[lo] = A[hi];
A[hi] = temp;
}
}
//at the end we put in pivot right inbetween low and high values and we know that
pivot element is in the right place.
int temp = A[lo+1];
A[lo+1] = A[end];
A[end] = temp;
return lo+1; //we return the pivot elements place
}
public static void main(String[] args)
{
int[] list = {156,344,54,546,767,23,34,64,234,
654,234,65,234,65,87,3,5,76,24,2,3,7,
9,5,34,32,4525,345,0};
QuickSort qs = new QuickSort();
qs.sortNumbers(list);
for (int i = 0;i < list.length;i++)
{
System.out.println(list[i]);
}
}
}
Read File Using Java BufferedInputStream Example
public class ReadFileUsingBufferedInputStream
{
public static void main(String[] args)
{
//create file object
File file = new File("C://FileIO//ReadFile.txt");
BufferedInputStream bin = null;
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
37. Java Programs cs567
//create object of BufferedInputStream
bin = new BufferedInputStream(fin);
/*
* BufferedInputStream has ability to buffer input into
* internal buffer array.
*
* available() method returns number of bytes that can be
* read from underlying stream without blocking.
*/
//read file using BufferedInputStream
while( bin.available() > 0 )
{
System.out.print((char)bin.read());
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
finally
{
//close the BufferedInputStream using close method
try
{
if(bin != null)
bin.close();
}catch(IOException ioe)
{
System.out.println("Error while closing the stream : " + ioe);
}
}
}
}
38. Java Programs cs567
Reading Directories
class DirList
{
public static void main(String args[])
{
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}
Reverse Number
class Reverse
{
39. Java Programs cs567
public static void main(String args[])
{
int num = Integer.parseInt(args[0]); //take argument as command line
int remainder, result=0;
while(num>0)
{
remainder = num%10;
result = result * 10 + remainder;
num = num/10;
}
System.out.println("Reverse number is : "+result);
}
}
SelecionSort
public class SelecionSort
{
/**
* Sorts the given list in place.
* Worst Case Performance O(n^2)
* Best Case Performance O(n^2)
* Average Case Performance O(n^2)
* Insertion sort can be- and usually is a much faster sorting algorithm, than selection
sort.
* Selection sort is superior because it does less swaps.
* @param list - int array that you want to sort.
*/
public static void sortNumbers(Integer[] list)
{
//go through the list
for (int i=0; i< list.length;i++)
{
//define min
int min = i;
40. Java Programs cs567
//go through the remaining list and see if there is smaller number
for (int j=i+1;j< list.length;j++)
{
//if there is a smaller number
if (list[j] < list[min])
{
//remember its place
min = j;
}
}
if (i != min)
{
//swap the min element, moving it to its proper place in the list.
int temp = list[min];
list[min] = list[i];
list[i] = temp;
}
}
}
/**
* Just for testing purposes.
*/
public static void main(String[] args)
{
Integer[] list = new Integer[5];
list[0] = 32;
list[1] = 24;
list[2] = 235;
list[3] = 1;
list[4] = 0;
sortNumbers(list);
for (int i = 0;i< list.length;i++)
{
System.out.println(list[i]);
}
}
}
ShellSort
public class ShellSort
{
private long[] data;
41. Java Programs cs567
private int len;
public ShellSort(int max)
{
data = new long[max];
len = 0;
}
public void insert(long value)
{
data[len] = value;
len++;
}
public void display()
{
System.out.print("Data:");
for (int j = 0; j < len; j++)
System.out.print(data[j] + " ");
System.out.println("");
}
public void shellSort()
{
int inner, outer;
long temp;
//find initial value of h
int h = 1;
while (h <= len / 3)
h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
while (h > 0) // decreasing h, until h=1
{
// h-sort the file
for (outer = h; outer < len; outer++)
{
temp = data[outer];
inner = outer;
// one subpass (eg 0, 4, 8)
while (inner > h - 1 && data[inner - h] >= temp)
{
data[inner] = data[inner - h];
inner -= h;
}
data[inner] = temp;
}
h = (h - 1) / 3; // decrease h
}
42. Java Programs cs567
}
public static void main(String[] args)
{
int maxSize = 10;
ShellSort arr = new ShellSort(maxSize);
for (int j = 0; j < maxSize; j++)
{
long n = (int) (java.lang.Math.random() * 99);
arr.insert(n);
}
arr.display();
arr.shellSort();
arr.display();
}
}
Simple Thread Example
public class SimpleThread extends Thread
{
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread()
{
super("" + ++threadCount); // Store the thread name
start();
}
public String toString()
{
return "#" + getName() + ": " + countDown;
}
public void run()
{
while(true)
{
System.out.println(this);
if(--countDown == 0)
return;
}
}
public static void main(String[] args)
{
for(int i = 0; i < 5; i++)
43. Java Programs cs567
new SimpleThread();
}
}
Square Root of BigInteger
public class SquareRootOfBigIntegerExample
{
public static void main(String[] args)
{
SquareRootOfBigIntegerExample SquareRootOfBigIntegerExample = new
SquareRootOfBigIntegerExample();
String n = "";
MathContext mc = new MathContext(0, RoundingMode.DOWN);
mc = MathContext.DECIMAL32;
BigInteger my2P100000 = new BigInteger("0");
BigInteger two = new BigInteger("2");
BigInteger one = new BigInteger("1");
my2P100000 = two.shiftLeft(2000 - 1);
System.out.println("2^2000 -- Step 1");
System.out.println("Value of 2^2,000 " + my2P100000 );
System.out.println("");
System.out.println("Finding the Square Root of 2^2000");
String mys = my2P100000 + "";
n = (mys) ;
int firsttime = 0;
BigDecimal myNumber = new BigDecimal(n);
BigDecimal g = new BigDecimal("1");
BigDecimal my2 = new BigDecimal("2");
BigDecimal epsilon = new BigDecimal("0.0000000001");
BigDecimal nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);
//Get the value of n/g
BigDecimal nBygPlusg = nByg.add(g);
//Get the value of "n/g + g
BigDecimal nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);
//Get the value of (n/g + g)/2
BigDecimal saveg = nBygPlusgHalf;
firsttime = 99;
do
{
g = nBygPlusgHalf;
nByg = myNumber.divide(g, 9, BigDecimal.ROUND_FLOOR);
nBygPlusg = nByg.add(g);
44. Java Programs cs567
nBygPlusgHalf = nBygPlusg.divide(my2, 9, BigDecimal.ROUND_FLOOR);
BigDecimal savegdiff = saveg.subtract(nBygPlusgHalf);
if (savegdiff.compareTo(epsilon) == -1 )
{
firsttime = 0;
}
else
{
saveg = nBygPlusgHalf;
}
} while (firsttime > 1);
System.out.println("For " + mys + "nLength: " + mys.length() + "nThe Square Root is "
+ saveg);
}
}
StringBuffer To File Java Example
public class JavaStringBufferToFileExample
{
public static void main(String[] args) throws IOException
{
//create StringBuffer object
StringBuffer sbf = new StringBuffer();
//StringBuffer contents
sbf.append("StringBuffer contents first line.");
//new line
sbf.append(System.getProperty("line.separator"));
//second line
sbf.append("StringBuffer contents second line.");
/*
* To write contents of StringBuffer to a file, use
* BufferedWriter class.
*/
BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("d:/demo.txt")));
//write contents of StringBuffer to a file
bwr.write(sbf.toString());
//flush the stream
45. Java Programs cs567
bwr.flush();
//close the stream
bwr.close();
System.out.println("Content of StringBuffer written to File.");
}
}
Convert String to primitive byte Example
public class StringToPrimitiveByteExample
{
public static void main(String[] args)
{
//declare String object
String str = new String("10");
/*
use parseInt method of Byte class to convert String into byte primitive
data type. This is a static method.
Please note that this method can throw a NumberFormatException if the string
is not parsable to byte.
*/
byte b = Byte.parseByte(str);
System.out.println(b);
}
}
Sum Product of Digit
class Sum_Product_ofDigit
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]); //taking value as command line argument.
int temp = num,result=0;
//Logic for sum of digit
46. Java Programs cs567
while(temp>0)
{
result = result + temp;
temp--;
}
System.out.println("Sum of Digit for "+num+" is : "+result);
//Logic for product of digit
temp = num;
result = 1;
while(temp > 0)
{
result = result * temp;
temp--;
}
System.out.println("Product of Digit for "+num+" is : "+result);
}
}
Create a thread by implementing Runnable
class MyThread implements Runnable
{
int count;
MyThread()
{
count = 0;
}
public void run()
{
System.out.println("MyThread starting.");
try
{
do
{
Thread.sleep(500);
System.out.println("In MyThread, count is " + count);
count++;
} while (count < 5);
} catch (InterruptedException exc)
{
System.out.println("MyThread interrupted.");
}
System.out.println("MyThread terminating.");
47. Java Programs cs567
}
}
class RunnableDemo
{
public static void main(String args[])
{
System.out.println("Main thread starting.");
MyThread mt = new MyThread();
Thread newThrd = new Thread(mt);
newThrd.start();
do
{
System.out.println("In main thread.");
try
{
Thread.sleep(250);
} catch (InterruptedException exc)
{
System.out.println("Main thread interrupted.");
}
} while (mt.count != 5);
System.out.println("Main thread ending.");
}
}
Thread Synchronization
// File Name : Callme.java
// This program uses a synchronized block.
class Callme
{
void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
48. Java Programs cs567
}
}
// File Name : Caller.java
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run()
{
synchronized(target)
{
// synchronized block
target.call(msg);
}
}
}
// File Name : Synch.java
class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
49. Java Programs cs567
{
System.out.println("Interrupted");
}
}
}
TreeMap example
public class JavaTreeMapExample
{
public static void main(String[] args)
{
//create object of TreeMap
TreeMap treeMap = new TreeMap();
/*
Add key value pair to TreeMap using,
Object put(Object key, Object value) method of Java TreeMap class,
where key and value both are objects
put method returns Object which is either the value previously tied
to the key or null if no value mapped to the key.
*/
treeMap.put("One", new Integer(1));
treeMap.put("Two", new Integer(2));
/*
Please note that put method accepts Objects. Java Primitive values CAN NOT
be added directly to TreeMap. It must be converted to corrosponding
wrapper class first.
*/
//retrieve value using Object get(Object key) method of Java TreeMap class
Object obj = treeMap.get("Two");
System.out.println(obj);
/*
Please note that the return type of get method is an Object. The value must
be casted to the original class.
*/
50. Java Programs cs567
}
}
TreeSet Example
public class SimpleJavaTreeSetExample
{
public static void main(String[] args)
{
//create object of TreeSet
TreeSet tSet = new TreeSet();
/*
Add an Object to TreeSet using
boolean add(Object obj) method of Java TreeSet class.
This method adds an element to TreeSet if it is not already present in TreeSet.
It returns true if the element was added to TreeSet, false otherwise.
*/
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
/*
Please note that add method accepts Objects. Java Primitive values CAN NOT
be added directly to TreeSet. It must be converted to corrosponding
wrapper class first.
*/
System.out.println("TreeSet contains.." + tSet); }
}
Java Vector Example
public class SimpleVectorExample
{
public static void main(String[] args)
{
//create a Vector object
Vector v = new Vector();
51. Java Programs cs567
/*
Add elements to Vector using
boolean add(Object o) method. It returns true as a general behavior
of Collection.add method. The specified object is appended at the end
of the Vector.
*/
v.add("1");
v.add("2");
v.add("3");
/*
Use get method of Java Vector class to display elements of Vector.
Object get(int index) returns an element at the specified index in
the Vector
*/
System.out.println("Getting elements of Vector");
System.out.println(v.get(0));
System.out.println(v.get(1));
System.out.println(v.get(2));
}
}
Write byte array to file using BufferedOutputStream
public class WriteByteArrayToFile
{
public static void main(String[] args)
{
String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
BufferedOutputStream bos = null;
try
{
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(strFileName));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
String str = "BufferedOutputStream Example";
/*
52. Java Programs cs567
* To write byte array to file use,
* public void write(byte[] b) method of BufferedOutputStream
* class.
*/
System.out.println("Writing byte array to file");
bos.write(str.getBytes());
System.out.println("File written");
}
catch(FileNotFoundException fnfe)
{
System.out.println("Specified file not found" + fnfe);
}
catch(IOException ioe)
{
System.out.println("Error while writing file" + ioe);
}
finally
{
if(bos != null)
{
try
{
//flush the BufferedOutputStream
bos.flush();
//close the BufferedOutputStream
bos.close();
}
catch(Exception e){}
}
}
}
}
Write file using File Output Stream
public class WriteFile
{
public static void main(String[] args)
53. Java Programs cs567
{
String strFilePath = "C://FileIO//demo.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
byte b = 01;
/*
* To write byte data to a file, use
* void write(int i) method of Java FileOutputStream class.
* This method writes given byte to a file.
*/
fos.write(b);
/*
* Close FileOutputStream using,
* void close() method of Java FileOutputStream class.
*
*/
fos.close();
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
}