Monday, January 16, 2012

ArrayDeque - used like a Stack

import java.util.*;
class ArrayDequeDemo
{
public static void main(String args[])
{
//create ArrayDeque
ArrayDeque<String> adq=new ArrayDeque<String>();

//using ArrayDeque like stack.
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("C");
adq.push("F");
System.out.println(adq);

//Popping the elements from ArrayDeque
System.out.println("Popping the stack");
while(adq.peek()!=null)  //  returns null if this deque is empty.
{
System.out.println(adq.pop() +"- popped ");
}
System.out.println(adq);
}

}

Output:
[F, C, E, D, B, A]
Popping the stack
F- popped
C- popped
E- popped
D- popped
B- popped
A- popped
[]

Note:

  • ArrayDeque implements Deque

TreeSet


import java.util.*;
class TreeSetDemo
{
public static void main(String args[])
{
//create TreeSet
TreeSet<String> hs=new TreeSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
                System.out.println("Displaying contents of hs using for each: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();

//--------------------------------------------------------
//adding a to z in TreeSet
System.out.println();
LinkedHashSet<Character> h=new LinkedHashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
                System.out.println("Displaying contents of hs using for each: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();

}
}


Output:


[A, B, C, D, E, F]
Displaying contents of hs using Iterator:
A-B-C-D-E-F-
Displaying contents of hs using for each:
A B C D E F

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y]
Displaying contents of h using Iterator:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-
Displaying contents of h using for each:
a b c d e f g h i j k l m n o p q r s t u v w x y



Note:
  • LinkedHashSet guarantee the elements in sorted, ascending order.
  • In LinkedHashSet ListIterator cannot be used.
  • LinkedHashSet implements NavigableSet interface.


LinkedHashSet

import java.util.*;
class LinkedHashSetDemo
{
public static void main(String args[])
{
//create HashSet
LinkedHashSet<String> hs=new LinkedHashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
System.out.println("Displaying contents of hs using Iterator: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();

//--------------------------------------------------------
//adding a to z in HashSet
System.out.println();
LinkedHashSet<Character> h=new LinkedHashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
System.out.println("Displaying contents of h using Iterator: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();
}
}


Output:
[B, A, D, E, C, F]
Displaying contents of hs using Iterator:
B-A-D-E-C-F-
Displaying contents of hs using for each:
B A D E C F

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y]
Displaying contents of h using Iterator:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-
Displaying contents of h using for each:
a b c d e f g h i j k l m n o p q r s t u v w x y


Note:
  • LinkedHashSet guarantee the order of its elements in which they were inserted.
  • In LinkedHashSet ListIterator cannot be used.
  • LinkedHashSet implements Set interface.

HashSet

import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
//create HashSet
HashSet<String> hs=new HashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
System.out.print("Displaying contents of hs using Iterator: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();
//--------------------------------------------------------
//adding a to z in HashSet
System.out.println();
HashSet<Character> h=new HashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
System.out.println("Displaying contents of h using Iterator: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();

}
}

Output:
[D, E, F, A, B, C]
Displaying contents of hs using Iterator: D E F A B C
Displaying contents of hs using for each: D E F A B C

[f, g, d, e, b, c, a, n, o, l, m, j, k, h, i, w, v, u, t, s, r, q, p, y, x]
Displaying contents of h using Iterator:
f-g-d-e-b-c-a-n-o-l-m-j-k-h-i-w-v-u-t-s-r-q-p-y-x-
Displaying contents of h using for each:
f g d e b c a n o l m j k h i w v u t s r q p y x

Note:
  • HashSet does not guarantee the order of its elements
  • In HashSet ListIterator cannot be used.
  • HashSet implements Set Interface.



Linked List

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");
System.out.println("Original contents of ll: " + ll);

//adding first and last element in linkedlist
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("contents of ll after adding first and last: " + 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 and last: " + ll);

// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);

//Iterator to display elements
System.out.print("Displaying contents of ll using Iterator: ");
Iterator itr = ll.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of ll using for each: ");
for(String s:ll)
{
System.out.print(s + " ");
}
System.out.println();

// modify objects being iterated
ListIterator litr = ll.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}

System.out.print("Modified contents of ll: ");
itr = ll.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}

Output:
Original contents of ll: [F, B, D, E, C]
contents of ll after adding first and last: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Displaying contents of ll using Iterator: A2 D E Changed C
Displaying contents of ll using for each: A2 D E Changed C
Modified contents of ll: A2+ D+ E Changed+ C+
Modified list backwards: C+ E Changed+ D+ A2+

Note:
LinkedList implements List, Deque and Queue.

Converting an ArrayList into an array.


//Obtaining an Array from an ArrayList

import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList<Integer> al = new ArrayList<Integer>();

// Add elements to the array list
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("Contents of al: " + al);

// get array
Object ia[] = al.toArray();
int sum = 0;

//Display using array
System.out.println("Display using array");
for(int i=0;i<ia.length;i++)
{
System.out.println(ia[i]);
}

// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

Output:

Contents of al: [1, 2, 3, 4]
Display using array
1
2
3
4
Sum is: 10


Note:
Reasons to convert ArrayList to Array:
  • To obtain faster processing times for certain operations.
  • To pass an array to a method that is not overloaded to accept a collection.
  • To integrate collection-based code with legacy code that does not understand collections.

Array List


import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());

// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");

System.out.println("Size of al after additions: " +
al.size());

// display the array list
System.out.println("Contents of al: " + al);

// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);

//Iterator to display elements
System.out.print("Displaying contents of al using Iterator: ");
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of al using for each: ");
for(String s:al)
{
System.out.print(s + " ");
}
System.out.println();

// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}

System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();


}
}


Output:

Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Displaying contents of al using Iterator: C A2 E B D
Displaying contents of al using for each: C A2 E B D
Modified contents of al: C+ A2+ E+ B+ D+
Modified list backwards: D+ B+ E+ A2+ C+


Note:
  • ArrayList implements only List interface.

Sunday, January 15, 2012

Sorting and Searching using in build Arrays methods


import java.util.Arrays;
class Sorting
{
static void display(int array[])  //Static method for Displaying
{
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
System.out.println("");
}

public static void main(String args[])
{
int array[]=new int[10];

for(int i=0;i<10;i++)
array[i]=-3*i; //assigning some values in single dimensional array

System.out.println("Original contents:");  //Displaying original Contents
display(array);

Arrays.sort(array); //calling sort method to sort the contents
System.out.println("Sorted:");
display(array);

Arrays.fill(array,2,6,-1); //replacing the 0th position to 5th position with "-1"
System.out.println("After fil():");
display(array);

Arrays.sort(array); //sorting after inserting -1
System.out.println("After sorting:");
display(array);

System.out.println("The value -9 is at location"); //Searching the "-9" in the array by calling binary Search method
int index=Arrays.binarySearch(array,-9);
System.out.println(index);

}
}

Arrays


1. Two Dimentional Array Example

class ArrayDemo
{
public static void main(String args[])
{
int[]num={1,2,3,4,5}; //Single Dimensional Array
System.out.println("Array Length:" + num.length);

int k=0;
int [][] twoD=new int[4][5]; //Two Dimensional array (even columns)
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
twoD[i][j]=k;    //Storing 1 to 19 in two dimentional array
k++;
}

}

for(int i=0;i<4;i++)      //Displaying the elements from two dimentional array
{
for(int j=0;j<5;j++)
{
System.out.print(twoD[i][j]+"   ");
}
System.out.println();

}

}
}

Output:

Array Length:5
0   1   2   3   4
5   6   7   8   9
10   11   12   13   14
15   16   17   18   19

2. Two Dimensional (Uneven column) Array Example

public class Uneven
{
public static void main(String args[])
{
int [][] twoD=new int[4][];      //Two dimensional with Uneven columns array declaration
int k=0;
twoD[0]=new int[1];
twoD[1]=new int[2];
twoD[2]=new int[3];
twoD[3]=new int[4];
for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
twoD[i][j]=k;
k++;
}
}

for(int i=0;i<4;i++)
{
for(int j=0;j<i+1;j++)
{
System.out.print(twoD[i][j]+" ");
}
System.out.println();
}
}
}

Output:

0
1 2
3 4 5
6 7 8 9


Sunday, January 1, 2012

Reflect Concept (Display all methods in a class including inherited class methods)


import java.lang.reflect.Method;
public class Reflect
{
public static void main(String args[])
{
CarB ob1=new CarB();
    Class c1=ob1.getClass();
    Method[] meths=c1.getMethods();
    for(Method m:meths)
    {
      System.out.println(m.getName());
    }
}
}

Note:  public class CarB extends Automobile implements IVehicle,IBox

output:

It displays all the methods in CarB, Automobile class

Palindrome Code


import java.util.*;
class palin12
{
public static void main(String args[])
{
String s1;
String s2="";
System.out.println("Enter the String");
Scanner scan=new Scanner(System.in);
s1=scan.next();

int l=s1.length();
char c[]=new char[l];
for(int i=l-1;i>=0;i--)
{
c[i]=s1.charAt(i);
s2=s2+c[i];
}
System.out.println(s2);
if(s1.equals(s2))
{
System.out.println("palindrome");
}
else
{
System.out.println("not palindrome");
}
}
}

output:
Enter the String

malayalam
malayalam
palindrome


Enter the String
bharath
htarahb
not palindrome




Passing Variable Length Arguments using ...

  • Ambiguity may occur in this method.
PassMulti.java:

class PassMulti
{

/*public void PassTest(int ... v)
{
System.out.println("No of args:" + v.length);
for(int i:v)
System.out.println(i);
}
*/

public void PassTest(double ... v)
{
System.out.println("No of args:" + v.length);
for(double i:v)
System.out.println(i);
}

public void PassTest(int a,boolean ... v)
{
System.out.println("No of args:" + v.length);
System.out.println(a);
for(boolean i:v)
System.out.println(i);
}

public void PassTest(String ... v)
{
System.out.println("No of args:" + v.length);
for(String i:v)
System.out.println(i);
}

}

PassMultiDemo.java


public class PassMultiDemo
{
public static void main(String args[])
{
//int a[]={10,20,30};
//int b[]={5,6};
//int c[]={};
PassMulti ob1=new PassMulti();
PassMulti ob2=new PassMulti();
PassMulti ob3=new PassMulti();

ob1.PassTest(1,2,3,4,5);
ob2.PassTest(10.20,50.5,70.00);
ob3.PassTest(10,true,false);
ob3.PassTest("Bharath","Hussain");

}
}

output:
javac PassMulti.java
javac PassMultiDemo.java
java PassMulti

No of args:5
1.0
2.0
3.0
4.0
5.0
No of args:3
10.2
50.5
70.0
No of args:2
10
true
false
No of args:2
Bharath
Hussain



Passing Variable Length Arguments using array

PassArray.java:


public class PassArray
{

public void PassTest(int v[])
{
System.out.println("No of args:" + v.length);
for(int i:v)
System.out.println(i);
}

public void PassTest(double v[])
{
System.out.println("No of args:" + v.length);
for(double i:v)
System.out.println(i);
}

public void PassTest(String v[])
{
System.out.println("No of args:" + v.length);
for(String i:v)
System.out.println(i);
}

}

PassArrayDemo.java


public class PassArrayDemo
{
public static void main(String args[])
{
int a[]={10,20,30};
String b[]={"Bharath","Hussain"};
double c[]={20.5};
double d[]={10.5,25.6,20};
PassArray ob1=new PassArray();
//PassArray ob2=new PassArray();
//PassArray ob3=new PassArray();
//PassArray ob4=new PassArray();
ob1.PassTest(a);
ob1.PassTest(b);
ob1.PassTest(c);
ob1.PassTest(d);
}
}

output:
javac PassArray.java
javac PassArraydemo.java
java PassArray

No of args:3
10
20
30
No of args:2
Bharath
Hussain
No of args:1
20.5
No of args:3
10.5
25.6
20.0

For Loop - Triangle

class Triangle1
{
public static void main(String args[])
{
for(int j=0;j<10;j++)
{
for(int i=10;i>j;i--)
System.out.print(".");
for(int k=j;k>=1;k--)
System.out.print(k);
System.out.println();
}
}
}

output:
..........
.........1
........21
.......321
......4321
.....54321
....654321
...7654321
..87654321
.987654321




class Triangle2
{
public static void main(String args[])
{

for(int j=0;j<10;j++)
{
for(int i=10;i>j;i--)
System.out.print(" ");

for(int k=j;k>=1;k--)
System.out.print(k);

for (int m=2;m<(j+1);m++)
System.out.print(m);

System.out.println();
}

}
}

output:


               1
             212
           32123
         4321234
        543212345
      65432123456
    7654321234567
  876543212345678
98765432123456789



class Triangle3
{
public static void main(String args[])
{
for(int j=1;j<10;j++)
{
for(int i=10;i>j;i--)
System.out.print(" ");

for(int k=j;k>=1;k--)
System.out.print(k);

for (int m=2;m<(j+1);m++)
System.out.print(m);

System.out.println();
}

for(int j=9;j>1;j--)
{
for(int i=10;i>=j;i--)
System.out.print(" ");

for(int k=j-1;k>=1;k--)
System.out.print(k);

for (int m=2;m<(j);m++)
System.out.print(m);

System.out.println();

}
}
}

output:



                 1
               212
             32123
           4321234
         543212345
       65432123456
     7654321234567
   876543212345678
 98765432123456789
   876543212345678
     7654321234567
       65432123456
         543212345
           4321234
             32123
               212
                 1



class Triangle4
{
public static void main(String args[])
{

for(int j=1;j<10;j++)
{
for(int i=10;i>j;i--)
System.out.print("   ");

for(int k=j;k>=1;k--)
System.out.print("  " +k);

for (int m=2;m<(j+1);m++)
System.out.print("  " +m);

System.out.println();
}

for(int j=9;j>1;j--)
{
for(int i=10;i>=j;i--)
System.out.print("   ");

for(int k=j-1;k>=1;k--)
System.out.print("  "+k);

for (int m=2;m<(j);m++)
System.out.print("  "+m);

System.out.println();
}
}
}
output:



                                     1
                                 2  1  2
                             3  2  1  2  3
                         4  3  2  1  2  3  4
                     5  4  3  2  1  2  3  4  5
                 6  5  4  3  2  1  2  3  4  5  6
             7  6  5  4  3  2  1  2  3  4  5  6  7
         8  7  6  5  4  3  2  1  2  3  4  5  6  7  8
     9  8  7  6  5  4  3  2  1  2  3  4  5  6  7  8  9
         8  7  6  5  4  3  2  1  2  3  4  5  6  7  8
             7  6  5  4  3  2  1  2  3  4  5  6  7
                 6  5  4  3  2  1  2  3  4  5  6
                     5  4  3  2  1  2  3  4  5
                         4  3  2  1  2  3  4
                             3  2  1  2  3
                                 2  1  2
                                     1






Spliting the commandline String and storing it in charArray and prints its Ascii Value of each Character

public class CharA
{
public static void main(String args[])
{
int[] j=new int[100];
String str=args[0];
char[] cs=str.toCharArray();
System.out.println("length=" + str.length());
for(int i=0;i<str.length();i++)
{
System.out.print(cs[i]);
j[i]=(int)(cs[i]);
System.out.println("  " + j[i]);
}
}
}

output:
java CharA "Hello World"
length=11

H  72
e  101
l  108
l  108
o  111
   32
W  87
o  111
r  114
l  108
d  100

Spliting words using Split method and print no. of words in a given String and Reverse the Words

public class SplitB
{
public static void main(String args[])
{
String s1=args[0];
String[] str=s1.split(" ");
System.out.println(args[0]);
//int size=(java.util.Arrays.asList(str).size());
int size=str.length;
System.out.println("No of words=" + size);
for(int i=0;i<size;i++)
System.out.println(str[i]);
System.out.println("Reverse words:");
for(int i=size-1;i>=0;i--)
System.out.println(str[i]);
}
}

output:
java SplitB "Hello World"

Hello World
No of words=2
Hello
World
Reverse words:
World
Hello

Passing Parameters in Command Line

public class SampleB
{
public static void main(String args[])
{
String s1=args[0];
String s2=args[1];
System.out.println("s1=" + s1 + "s2=" + s2);
System.out.println("s1+s2=" + s1+s2);

int c1=Integer.parseInt(s1);
int c2=Integer.parseInt(s2);
System.out.println("c1=" + c1 + "c2=" +c2);
System.out.println("c1+c2=" + (c1+c2));
}
}

output:
java SampleB 10 20

s1=10s2=20
s1+s2=1020
c1=10c2=20
c1+c2=30

Finding Age Code

import java.util.*;
public class DateDemoA
{
public static void main(String args[])
{
Date d1=new Date();
System.out.println("Current Date:" + d1);
Date d2=new Date(84,12,01);               //YY,MM,DD
System.out.println("Date of Birth:" + d2);
int age=d1.getYear()-d2.getYear();
System.out.println("Age:" + age);
int x=d2.compareTo(d1); //Big with smaller==> +1  //small with big==> -1
System.out.println(x);
}
}

output:

Current Date:Tue Dec 13 20:45:31 IST 2011
Date of Birth:Tue Jan 01 00:00:00 IST 1985
Age:26
-1

Encoding Code


Encoding a Single Character:

class Encode
{
public static void main(String args[])
{
char s1='a';
int j;
j=(int)s1 + 10;
System.out.println(" "+j);
char s2;
s2= (char)j;
System.out.println(j+"  is  "+s2);
}
}

output:

 107
107  is  k

Encoding a String:



class Encode1
{
public static void main(String args[])
{
String s1="BHARATH";
int a[]=new int [10];
char b[]=new char [10];
int len=s1.length();
for(int  i=0; i<=len-1;i++)
{
a[i]=(int)s1.charAt(i) + 10;
b[i]=(char)a[i];
}
for(int i=0;i<=len-1;i++)
{

System.out.println(a[i]);
}
for(int i=0;i<=len-1;i++)
{
System.out.print(b[i]);
}
}
}

output:


76
82
75
92
75
94
82
LRK\K^R