Tuesday, 29 September 2015

Java Bubble Sort Example

/*
        Java Bubble Sort Example
        This Java bubble sort example shows how to sort an array of int using bubble
        sort algorithm. Bubble sort is the simplest sorting algorithm.
*/

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

                 In bubble sort, we basically traverse the array from first
                  to array_length - 1 position and compare the element with the next one.
                  Element is swapped with the next element if the next element is greater.
               
                  Bubble sort steps are as follows.
               
                  1. Compare array[0] & array[1]
                  2. If array[0] > array [1] swap it.
                  3. Compare array[1] & array[2]
                  4. If array[1] > array[2] swap it.
                  ...
                  5. Compare array[n-1] & array[n]
                  6. if [n-1] > array[n] then swap it.
               
                  After this step we will have largest element at the last index.
               
                  Repeat the same steps for array[1] to array[n-1]
                 
                 */
                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;
                                }
                             
                        }
                }
             
                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] + " ");
                }

        }
}

/*
Output of the Bubble Sort Example would be

Array Before Bubble Sort
5 90 35 45 150 3
Array After Bubble Sort
3 5 35 45 90 150

*/

Wednesday, 23 September 2015

Sorting ArrayList of Integer arraylist

import java.util.*;
class ArrayListSorting  {

public static void main(String args[]){
  ArrayList<Integer> listofcountries = new ArrayList<Integer>();
  listofcountries.add(89);
  listofcountries.add(5);
  listofcountries.add(3);
  listofcountries.add(9);

  /*Unsorted List*/
  System.out.println("Before Sorting:");
  for(int counter: listofcountries){
System.out.println(counter);
}

  /* Sort statement*/
  Collections.sort(listofcountries);

  /* Sorted List*/
  System.out.println("After Sorting:");
  for(int counter: listofcountries){
System.out.println(counter);
}
}
}

OutPut : - 


Add caption

Tuesday, 15 September 2015

Vactor Class Example 4

import java.util.*;
class VectorDemo3
{ public static void main(String args[])
{ Vector<String> list=new Vector<String>();
for(int i=0;i<args.length;i++)
{ list.addElement(args[i]);
}
list.insertElementAt("Cobol",2);
int size=list.size();
Object a[] = list.toArray();
System.out.println("List of Languages:");
for(int i=0;i<size;i++)
System.out.println((String)a[i]);
}
}

Vactor Class Example 3

import java.util.*;
class VectorDemo
{ public static void main(String args[])
{ // initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after 4 additions:"+ v.capacity());
v.addElement(5);
System.out.println("Current capacity: " + v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Current capacity: " +   v.capacity());
v.addElement(8);
v.addElement(9);
System.out.println("Current capacity: " + v.capacity());
v.addElement(10);
v.addElement(11);
v.addElement(12);

System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());

if(v.contains(3))
     System.out.println("Vector contains 3.");

// Enumerate the elements in the vector.
Enumeration e = v.elements();
System.out.println("\nBy Enumeration: Elements in vector:");
while(e.hasMoreElements())
System.out.print(e.nextElement() + " ");
System.out.println();

Iterator<Integer> itr = v.iterator();
System.out.println("\nBy Iterator: Elements in vector:");
while(itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();

// Use for-each loop to display contents.  
System.out.println("\nBy for-each: Elements in vector:");
for(int i : v)
System.out.print(i + " ");
System.out.println();
System.out.println(v);
}
}

Vactor Class Example 2

import java.util.*;
class VectorDemo1
{ public static void main(String args[])
{ Vector<String> list=new Vector<String>();
for(int i=0; i < args.length; i++)
{ list.addElement(args[i]);
}
list.insertElementAt("Cobol",2);
int size=list.size();
String listArray[]=new String[size];
list.copyInto(listArray);
System.out.println("List of Languages:");
for(int i=0;i<size;i++)
System.out.println(listArray[i]);
}
}

Vector Class Example 1

import java.util.*;
class VectorDemo
{ public static void main(String args[])
{ // initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after 4 additions:"+ v.capacity());

if(v.contains(3))
     System.out.println("Vector contains 3.");

// Enumerate the elements in the vector.
Enumeration e = v.elements();
System.out.println("\nBy Enumeration: Elements in vector:");
while(e.hasMoreElements())
System.out.print(e.nextElement() + " ");
System.out.println();

Iterator<Integer> itr = v.iterator();
System.out.println("\nBy Iterator: Elements in vector:");
while(itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();

// Use for-each loop to display contents.  
System.out.println("\nBy for-each: Elements in vector:");
for(int i : v)
System.out.print(i + " ");
System.out.println();
System.out.println(v);
System.out.println();
}
}

Monday, 14 September 2015

Add Integer Number in TreeSet Class Example

import java.util.*;
class TreeSetDemo1
{ public static void main(String args[])
{ // Create a tree set.
TreeSet<Integer> ts = new TreeSet<Integer>();
    // Add elements to the tree set.
ts.add(5);
ts.add(4);
ts.add(3);
ts.add(8);
ts.add(2);
ts.add(1);
System.out.println(ts);
}
}

Add String Number in TreeSet Class Example

import java.util.*;
class TreeSetDemo
{ public static void main(String args[])
{
// Create a tree set.
    TreeSet<String> ts = new TreeSet<String>();
     // Add elements to the tree set.
    ts.add("C");
  ts.add("A");
ts.add("B");
  ts.add("E");
    ts.add("F");
  ts.add("D");
System.out.println(ts);
}
}

TreeMap Class Example 1

import java.util.*;
class TreeMapDemo
{ public static void main(String args[])
{ // Create a hash map.
TreeMap<String, Double> tm = new TreeMap<String, Double>();
tm.put("Devesh",1000.00);
tm.put("Rahul",1500.00);
tm.put("Rakesh",1200.00);
tm.put("Manohar",900.00);
tm.put("Prateek",1300.00);
tm.put("Pawan", null);
//tm.put(null,34.56); will result in run-time error
// Get a set of keys
Set<String> set = tm.keySet();
// Display the set.
for(String key : set)
{
    System.out.print(key + ": ");
System.out.println(tm.get(key));
}
System.out.println();
// Deposit 1000 into Prateek's account.
double balance = tm.get("Prateek");
tm.put("Prateek", balance + 1000);
balance = (Double)tm.get("Prateek");
  System.out.println("Prateek's new balance: " + balance);
}
}

TreeMap Class Example 2

import java.util.*;
class Student
{ int rollno;
String name;
String phone;
}
class Comp implements Comparator<Student>
{ public int compare(Student s1, Student s2)
{ int c;
if(s1.rollno < s2.rollno)
c = -1;
else if (s1.rollno > s2.rollno)
c = 1;
else
c = 0;
return c;
}
}

class TreeMapDemo1
{ public static void main(String args[])
{   TreeMap<Student,Double> tm=new TreeMap<Student,Double>(new Comp());
// Add elements to the tree set.
Student s1 = new Student();
s1.rollno = 1; s1.name = "Rahul"; s1.phone = "2590381";

Student s2 = new Student();
s2.rollno = 5; s2.name = "Devesh"; s2.phone = "9829059033";

Student s3 = new Student();
s3.rollno = 3; s3.name = "Rakesh"; s3.phone = "2590381";

Student s4 = new Student();
s4.rollno = 2; s4.name = "Manohar"; s4.phone = "2590381";

Student s5 = new Student();
s5.rollno = 4; s5.name = "Prateek"; s5.phone = "2590381";

tm.put(s1, 1000.0);
tm.put(s2, 2000.0);
tm.put(s3, 3000.0);
tm.put(s4, 4000.0);
tm.put(s5, 5000.0);

Set<Student> set = tm.keySet();
for(Student s : set)
{
System.out.print(s.rollno + ", " + s.name + ", " + s.phone
+ "; " + "balance:");
System.out.println(tm.get(s));
  }
}
}

Stack Class Example

import java.util.*;
class StackDemo
{
  public static void main(String args[])
{ Stack<Integer> st = new Stack<Integer>();
System.out.println("stack: " + st);
st.push(42);
System.out.println("stack: " + st);
st.push(66);
System.out.println("stack: " + st);
st.push(99);
System.out.println("stack: " + st);
Integer io = st.pop();
System.out.println("stack: " + st);
io = st.pop();
System.out.println("stack: " + st);
io = st.pop();
System.out.println("stack: " + st);
try
{ st.pop();
}
catch (EmptyStackException e)
{ System.out.println("empty stack");
}
}
}

Saturday, 12 September 2015

LinkedHashMap class Example

import java.util.*;
class LinkedHashMapDemo
{ public static void main(String args[])
  { // Create a hash map.
LinkedHashMap hm = new LinkedHashMap();
      // Put elements to the map
hm.put("Devesh",1000.00);
hm.put("Rahul",1500.00);
hm.put("Rakesh",1200.00);
hm.put("Manohar",900.00);
hm.put("Prateek",1300.00);
// Get a set of the entries.
Set set = hm.entrySet();
// Display the set.
Iterator i = set.iterator();
while(i.hasNext())
{ Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
}
  System.out.println();
  // Deposit 1000 into John Doe's account.
double balance = (Double) hm.get("Prateek");
hm.put("Prateek", balance + 1000);
balance = (Double)hm.get("Prateek");
System.out.println("Prateek's new balance: " + balance);
}
}

LinkedHashSet Class Example

import java.util.*;
class LinkedHashSetDemo
{ public static void main(String args[])
{ // Create a hash set.
    LinkedHashSet<String> hs = new LinkedHashSet<String>();
// Add elements to the hash set.
  hs.add("B");
    hs.add("A");
    hs.add("D");
    hs.add("E");
    hs.add("C");
    hs.add("F");
System.out.println(hs);
}
}

LinkedList Class Example in java util package

import java.util.*;
class LinkedListDemo
{ public static void main(String args[])
{ // Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion:"  + ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first & last : "+ll);
// Get and set a value.
String val = ll.get(2);
System.out.println("The element at index 2: " + val);
ll.set(2, "E+");
System.out.println("ll after change: " + ll);
}
}

Generic Stack Class Demo Example in java util Package

class Stack<T>
{ int top = -1; int size;
Object a[];
Stack(int size)
{ this.size = size;
a = new Object[size];
}
void push(T obj)
{ if(top == size-1)
{ System.out.println("Stack Full");
return;
}
top = top + 1; a[top] = obj;
}
T pop()
{ if(top ==  -1)
{ return null;
}
T obj = (T)a[top];
top = top - 1;
return obj;
}
void display()
{
for(int i = top; i>=0; i--)
{
T obj1 = (T) a[i];
System.out.println(obj1);
}
}
}

class Student
{
int rollno;
String name;
String phone;
public String toString()
{
return  rollno + ", " + name + ", " + phone;
}
}

class GenericStackDemo
{ public static void main(String args[])
{ Stack st1 = new Stack(10);
st1.push("Devesh");
st1.push(10);
st1.push(new Double(5.4));
System.out.println("Stack of type Object:");
st1.display();
Stack<String> st2 = new Stack<String>(20);
st2.push("Rakesh");
st2.push("Rahul");
st2.push("Devesh");
st2.push("Manohar");
//st2.push(20); //- Compile time error
System.out.println("\nStack of type String:");
st2.display();
Stack<Student> st3 = new Stack<Student>(10);
Student s1 = new Student();
s1.rollno = 1; s1.name = "Rahul"; s1.phone = "2590381";
Student s2 = new Student();
s2.rollno = 5; s2.name = "Devesh"; s2.phone = "9829059033";
Student s3 = new Student();
s3.rollno = 3; s3.name = "Rakesh"; s3.phone = "2590381";
Student s4 = new Student();
s4.rollno = 2; s4.name = "Manohar"; s4.phone = "2590381";
Student s5 = new Student();
s5.rollno = 4; s5.name = "Prateek"; s5.phone = "2590381";
st3.push(s1);
st3.push(s2);
st3.push(s3);
st3.push(s4);
st3.push(s5);
//st3.push("Devesh"); //- will not compile
System.out.println("\nStack of type Student:");
st3.display();
Stack<Integer> s = new Stack<Integer>(10);
st1 = st3; //- will not compile;
}
}

Generic Class Demo Example in java util package

class GenMap<T1,T2>
{
int index = -1;
Object a1[] = new Object[10];
Object a2[] = new Object[10];
void put(T1 obj1, T2 obj2)
{
index++;
a1[index] = obj1;
a2[index] = obj2;
}
T2 get(T1 key)
{
for(int i = 0; i <= index; i++)
{
if(a1[i].equals(key))
return (T2) a2[i];
}
return null;
}
void display()
{
for(int i = 0; i <= index; i++)
{
System.out.println(a1[i] + " : " + a2[i]);
}
}
}


class GenericDemo2
{ public static void main(String args[])
{ GenMap<String, String> gm = new GenMap<String, String>();
gm.put("Devesh", "Ramesh");
gm.put("Pawan", "Prakash");
gm.put("Naveen", "Narendra");
//gm.put("Neeraj", 2433);
System.out.println("Map entries: ");
gm.display();
String fname = gm.get("Pawan");
System.out.println("Pawan's father name: " + fname);

GenMap<String, Double> gm1 = new GenMap<String, Double>();
gm1.put("Devesh", 1000.0);
gm1.put("Pawan", 2000.0);
gm1.put("Naveen", 3000.0);
//gm1.put("Neeraj", "Mohan");
System.out.println();
System.out.println("Map entries: ");
gm1.display();
double balance = gm1.get("Pawan");
System.out.println("Pawan's balance is: " + balance);
}
}

Friday, 11 September 2015

HashTable in java util package

import java.util.*;
class HashtableDemo1
{ public static void main(String args[])
{ // Create a hash map.
Hashtable<String, Double> ht = new Hashtable<String, Double>();
      // Put elements to the map
ht.put("Devesh",1000.00);
ht.put("Rahul",1500.00);
ht.put("Rakesh",1200.00);
ht.put("Manohar",900.00);
ht.put("Prateek",1300.00);
// Get a set of the entries.
Set<String> set = ht.keySet();
// Display the set.
// Get an iterator.
Iterator <String>itr = set.iterator();
String name;
while(itr.hasNext())
{ name = itr.next();
System.out.println(name + ": " + ht.get(name));
}
System.out.println();
  // Deposit 1000 into Prateek's account.
double balance = (Double) ht.get("Prateek");
ht.put("Prateek", balance + 1000);
balance = (Double)ht.get("Prateek");
System.out.println("Prateek's new balance: " + balance);
}
}

HashTable in java util package

import java.util.*;
class HashtableDemo
{ public static void main(String args[])
{ // Create a hash map.
Hashtable<String, Double> ht = new Hashtable<String, Double>();
      // Put elements to the map
ht.put("Devesh",1000.00);
ht.put("Rahul",1500.00);
ht.put("Rakesh",1200.00);
ht.put("Manohar",900.00);
ht.put("Prateek",1300.00);

String name;
Enumeration<String> names = ht.keys();
while(names.hasMoreElements())
{ name = names.nextElement();
System.out.println(name + ": " + ht.get(name));

}
System.out.println();
// Deposit 1000 into Prateek's account.
double balance = (Double) ht.get("Prateek");
ht.put("Prateek", balance + 1000);
balance = (Double)ht.get("Prateek");
System.out.println("Pr ateek's new balance: " + balance);
}
}