Saturday, June 2, 2012

String Permutations


import java.util.ArrayList;

public class StringPermutation {

public static ArrayList<String> PermutationFinder(String s) {

ArrayList<String> perm = new ArrayList<String>();

if (s == null) { // error case

    return null;

} else if (s.length() == 0)

{

    perm.add(""); // initial

    return perm;

}

char initial = s.charAt(0); // first character

String rem = s.substring(1); // Full string without first character

ArrayList<String> words = PermutationFinder(rem);

for (String str : words)

{

    for (int i = 0; i <= str.length(); i++)

    {

        perm.add(charinsert(str, initial, i));

    }

}

return perm;

}

public static String charinsert(String str, char c, int j) {

String begin = str.substring(0, j);

String end = str.substring(j);

return begin + c + end;

}

public static  void main(String[] args) {

    String s = "CODE";

ArrayList<String> value = PermutationFinder(s);

System.out.println("\nThe Permutations are : \n" + value);

}

}

Friday, June 1, 2012

Exceptions and return types in overriding.


import java.io.IOException;
import java.sql.*;
public class Test1 {
public Test4 myMetohd1() throws Exception
{
return null;
}

}

class Test2 extends Test1 {
public Test5  myMetohd1() throws SQLException, IOException
{
return null;
}
}

class Test3 extends Test1 {
public Test5 myMetohd1()
{
return null;
}
}

class Test4
{
}

class Test5 extends Test4
{
}

Friday, May 25, 2012

If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?


The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SubSerialSuperNotSerial {

    public static void main(String [] args) {

        ChildSerializable c = new ChildSerializable();
        System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
        try {
        FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(c);
        os.close();
        } catch (Exception e) { e.printStackTrace(); }

        try {
        FileInputStream fis = new FileInputStream("superNotSerail.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c = (ChildSerializable) ois.readObject();
        ois.close();
        } catch (Exception e) { e.printStackTrace(); }
        System.out.println("After :- " + c.noOfWheels + " "+ c.color);
        }

}

 class ParentNonSerializable {
    int noOfWheels;
   
    ParentNonSerializable(){
        this.noOfWheels = 4;
    }
   
}


 class ChildSerializable extends ParentNonSerializable implements Serializable {
 
    private static final long serialVersionUID = 1L;
    String color;


    ChildSerializable() {
        this.noOfWheels = 8;
        this.color = "blue";
    }
}



Result on executing above code –
Before : - 8 blue
After :- 4 blue
The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.

Tuesday, May 22, 2012

Thread pool:Concurrency

import java.util.ArrayList;
import java.util.List;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutorService;

public class Concurrency {

   public static void main(String args[]) {
       long start = System.currentTimeMillis();

       // initialize pool
       ExecutorService pool = Executors.newFixedThreadPool(3);

       // store futures somewhere
       List<Future<CallableData>> futures = new ArrayList<Future<CallableData>>();

       // submit a bunch of Callables to the Pool
       for(int i = 0; i < 10; i++) {
           System.out.println("Creating! " + i);
           futures.add(pool.submit(new CallableData(i)));
       }

       // wait for everything to finish
       for(Future<CallableData> future : futures) {
           try {
               CallableData data = future.get();
               System.out.println("Got result!" + data.getFoo());
           } catch (Exception e){
               e.printStackTrace();
           }
       }

       System.out.println("Total time: " + (System.currentTimeMillis() - start) + " ms");

       // don't forget to shutdown
       pool.shutdown();
   }

   private static class CallableData implements Callable<CallableData> {
       private int foo;
       public CallableData(int foo) {
           this.foo = foo;
       }
       public CallableData call() {
           System.out.println("Running! " + foo);
           try { Thread.sleep(2000); } catch (Exception e) {}
           foo = foo + 1000;
           System.out.println("Completed! " + foo);
           return this;
       }
       public int getFoo() {
           return foo;
       }
   }
}

Friday, May 18, 2012

Why HashSet / HashMap in java does not maintain the insertion order?


Why HashSet / HashMap in java does not maintain the insertion order? example code

Tough interview questions like "Why HashSet / HashMap in java does not maintain the insertion order? OR Why HashSet / HashMap does not make guarantee that the iteration order will remain constant over time?" may be asked .When you run the following code with default hash map capacity (16) , you may get the output as gvien below
    
import java.util.*;
import java.util.*;
class HashMap2
{
public static void main(String args[]) {
HashMap hm=new HashMap();
hm.put("545", "Kumar");
hm.put("5143", "Jegan");
hm.put("767", "Akshu");
hm.put("1766", "Lakshan");
    Iterator it = hm.entrySet().iterator();
System.out.println("\nIteration Order when using HashMap");
    while (it.hasNext()) {
        Map.Entry keyValue= (Map.Entry)it.next();
        System.out.println(keyValue.getKey() + " -> " + keyValue.getValue());
    }
HashSet<String> set = new HashSet<String>(16);
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Pine Apple");
System.out.println("\nIteration Order when using HashSet");
  for (String fruit : set){
         System.out.println(fruit); }
}
}


Insertion Order in HashMap : 545 , 5143, 767, 1766 . In HashSet : Apple, Banana, Orange, Pine Apple. The Iteration order is given below.
Output:

In the above output , the display order (iteration order) is different from the order in which the elements are inserted. Let us see how does this happen ?
HashSet stores elements in a hash table (actually through a HashMap instance , where element in the HashSet is the key to HashMap and dummy object is passed as a value). So the below answer is applicable to both HashMap and HashSet . Hashing determines where the object has to be placed in a HashMap. In Detail : HashMap internally uses an array to store key and value pairs (i.e the reference to HashMap.Entry objects where HashMap.Entry objects have the fields to store hash, key ,value , link to next HashMap.Entry object - a linked list implementation) . The index to above array is calculated from the key using hash function. The hash function accepts the hashcode of the key (key.hashCode()) and calculates the hash using formula given below and returns hash. The index is calculated based on the hash value and the length of array (Capacity) with the formula ( h & (length-1) , h -> hash value, length -> array capacity) so that the elements (key-value pairs) can be distributed in the array within the given range (capacity) . Array can be resized if required but the length should be a power of two. So whenever the length (capacity) of the array is resized to 2^n , the index of the element is also changed .Thus the iteration order is changed.
Function to calculate hash using the hashcode of key.
    
//fromJava Source code . This function ensures that hashCodes that differ only by constant multiples at each bit position have a bounded  number of collisions (approximately 8 at default load factor).
  static int hash(int h) {
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

The below code prints the index which is calculated using the hashcode and capacity using hash function .
    
import java.util.*;
class HashMap3
{
public static void main(String args[]) {
int length=128; // capacity
HashMap hm=new HashMap(length);
hm.put("545", "Kumar");
hm.put("5143", "Jegan");
hm.put("767", "Akshu");
hm.put("1766", "Lakshan");
    Iterator it = hm.entrySet().iterator();
System.out.println("\nIteration Order when using HashMap with capacity : "+ length);
    while (it.hasNext()) {
        Map.Entry keyValue= (Map.Entry)it.next();
        System.out.println(  "Index : " + (hash(keyValue.getKey().hashCode()) & (length -1) )+ " " +  keyValue.getKey() + " -> " + keyValue.getValue());
    }

HashSet<String> set = new HashSet<String>(length);
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Pine Apple");

System.out.println("\nIteration Order when using HashSet with capacity : "+ length);
    for (String fruit : set){
System.out.println("Index : " + (hash(fruit.hashCode()) & (length -1) )+ " Element : " + fruit);
}
}

static int hash(int h) {
         h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
}

Output :

Two keys with different hashCode can also generate the same index (collisions) . In the above output, Orange and Banana has same index 12. The following two lines of code adds new elements and also solves collision.
Entry e = table[index];
table[index] = new Entry(hash, key, value, e);

if e==null means , there is no collision. Collision can be resolved by many techniques like Chaining

Picture : HashMap with Collision

Change the length to 128 and run the above program . The index / iteration order is changed.

Final conclusion : The location of the element in the HashMap is determined by the Hashcode of key and capacity of the HashMap.
Note: To maintain insertion order , you can use LinkedHashSet / LinkedHashMap

Tuesday, April 24, 2012

Test Object state after serialization and transient variables state.


import java.io.*;
public class TestSerializationVersion {

public static  void main(String [] args)
{
Dog d=new Dog(45,"Ramesh");

try
{
System.out.println(d.getName()+"    "+d.getAge());
//FileOutputStream fos=new FileOutputStream("Anand.txt");
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Anand.txt"));
oos.writeObject(d);
d.setAge(56);
d.setName("Sravani");
System.out.println(d.getName()+"    "+d.getAge());
oos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}


try
{
//FileOutputStream fos=new FileOutputStream("Anand.txt");
ObjectInputStream ios=new ObjectInputStream(new FileInputStream("Anand.txt"));
Dog d1=(Dog)ios.readObject();
    ios.close();
System.out.println(d1.getName()+"    "+d1.getAge());
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}

catch(IOException ex)
{
ex.printStackTrace();
}

}
}


class Dog implements Serializable
{
private int age;
private transient String name;
public Dog(int age, String name)
{
this.age=age;
this.name=name;
}

public String getName()
{
return name;
}

public int getAge()
{
return age;
}

public String setName(String name1)
{
this.name=name1;
return name1;
}

public int setAge(int age1)
{
this.age=age1;
return age1;
}

}

Thursday, April 19, 2012

Sequential run of threads

Thread t1 = new Thread( new MyRunnable( ) );
Thread t2 = new Thread( new MyRunnable( t1 ) );
Thread t3 = new Thread( new MyRunnable( t2 ) );
t1.start();
t2.start();
t3.start();

...

class MyRunnable()
{
   private Thread mustFinishFirst;
   public MyRunnable()
   {}
   public MyRunnable( Thread mustFinishFirst )
   {
      this.mustFinishFirst = mustFinishFirst;
   }
   public void run()
   {
      if( mustFinishFirst != null )
         mustFinishFirst.join()
      ...
   }
}

Wednesday, April 18, 2012

To find nth Fibonacci number

//Using recursion
public class Febo
{
public static void main(String[] args)
{
    for ( int i = 0; i < 10; i++ ) {
        System.out.print ( fib(i) + " " );
    }
    //System.out.println ( fib(10) );
}

//to find nth Fibonacci number
static long fib(int n) {
    return n <= 1 ? n : fib(n-1) + fib(n-2);
}
}

//Simple program written by me




import java.io.*;
public class Febo {
    public static void main(String []args) throws IOException
    {
        BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please enter a number");
        String input=reader.readLine();
        int i=Integer.parseInt(input);
        int []ret=Fibo(i);
        for(int j=0;j<ret.length;j++)
        {
            System.out.print(" "+ret[j]);
        }
    }
    public static int[] Fibo(int n)
    {
         int a[]=new int[n];
         if (n==1)
        a[0]=0;
         else
        {a[0]=0;
        a[1]=1;
        }
        if(n>2)
        {
            for(int i=2;i<n;i++)
            {
                a[i]=a[i-1]+a[i-2];
            }
        }
        return a;
    }
}

Efficient program to reverse a string


public class Reverse {

    public static void main(String [] args)
    {
    String s=reverse("Anand Prakash Yadav");   
    System.out.println(s);
    }
     public static String reverse ( String s ) {
            int length = s.length(), last = length - 1;
            char[] chars = s.toCharArray();
            for ( int i = 0; i < length/2; i++ ) {
                char c = chars[i];
                chars[i] = chars[last - i];
                chars[last - i] = c;
            }
            return new String(chars);
        }
}

Friday, March 23, 2012

Hit Counter Servlet Example

This example illustrates about counting how many times the servlet is accessed. When first time servlet (CounterServlet) runs then session is created and value of the counter will be zero and after again accessing of servlet  the counter value will be increased by one. In this program isNew() method is used whether session is new or old and getValue() method is used to get the value of counter.
Here is the source code of CounterServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CounterServlet extends HttpServlet{
  public void doGet(HttpServletRequest request,
  HttpServletResponse response
)
  throws 
ServletException, IOException {
  HttpSession session = request.getSession(true);
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  Integer count = new Integer(0);
  String head;
  if (session.isNew()) {
  head = "This is the New Session";
  else {
  head = "This is the old Session";
  Integer oldcount =(Integer)session.getValue("count")
  if (oldcount != null) {
  count = new Integer(oldcount.intValue() 1);
  }
  }
  session.putValue("count", count);
  out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
  "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" 
  "<TABLE BORDER=1 ALIGN=CENTER>\n"

  "<TR BGCOLOR=\"#FFAD00\">\n" 
  +"  <TH>Information Type<TH>Session Count\n" 
  +"<TR>\n" +" <TD>Total Session Accesses\n" +
  "<TD>" + count + "\n" +
  "</TABLE>\n" 
  +"</BODY></HTML>" );
  }
}
Mapping of Servlet ("CounterServlet.java") in web.xml file
<servlet>
  <servlet-name>CounterServlet</servlet-name>
  <servlet-class>CounterServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>CounterServlet</servlet-name>
  <url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>
Running the servlet by this url: http://localhost:8080/CodingDiaryExample/CounterServlet 

Thursday, March 22, 2012

How can I create a daemon thread?

The Thread API allows Threads to be created which are at the mercy of their user threads. This is accomplished simply by passing true to the setDaemon() method and invoking the method off an instance of the thread wishing to set it's status.
public void setDeamon(boolean b)
The following is a simple program which creates a thread within the context of the main thread of execution. Since the main thread is a user thread the created thread will also be a user thread unless it's status is set otherwise. A couple of notes about the following code. If the created threads status is not set or false is passed to the setDameon() method then the created thread will fully execute. This is because the main thread cannot return until all non-daemon threads are finished. Setting the status to true in our case doesn't give our daemon thread much time to do it's bussiness since the main method will quickly execute then return thus stopping our daemon thread dead in it's tracks. We would be lucky to get a print out of one year!. So what can we do? Either we can put the main thread to sleep for an amount of time (enough to give our dameon thread time to do it's business) or simply make it a non-daemon thread by setting it's status to false.
public class UserThread{ 
 public static void main(String[] args){
  Thread t = new Thread(new DaemonThread(525.00f, 0.09f));
  t.setDaemon(true); 
  t.start();
  try{
  Thread.sleep(250); // must give the deamon thread a chance to run! 
  }catch(InterruptedException ei){ // 250 mills might not be enough!
   System.err.println(ei);
  }
 }
}

class DaemonThread implements Runnable{
 private float principal;
 private float futureval;
 private float rate; 
 private float i;   
 public DaemonThread(float principal, float rate){
  this.principal= principal;
  this.rate = rate;  
 }

 public void run(){ 
  for(int year = 0; year <= 75; year++){
  i = (1 + rate); 
  futureval = principal * (float)Math.pow(i,year); 
  System.out.print(principal + " compounded after " + year + " years @ " + rate + "% = " + futureval);
  System.out.println();  
  }
 }
}

Java is strictly pass-by-value


/*Java is Pass-by-Value
Pass-by-value
The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application.
Pass-by-reference
The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter.
Java is strictly pass-by-value
Litmus test is swap method.
Value outside the method not changed.
*/

public class Swap {

public static void main(String [] args)
{
int a=20;
int b=30;
swap(20,30);
System.out.println(" "+a+"  "+b);
}
public static void swap(int a,int b)
{
// int temp=a;
// a=b;
// b=temp;
a=a+b;
b=a-b;
a=a-b;
System.out.println(" "+a+"  "+b);
}
}

Another good example show how values change if you directly change value pointed by that reference else if you create by new operator or setters, it will not change.

public class PassByRefEx {
    public static void main(String [] args)
    {
        int [] a={2,3,6,9,10};

        int abc=23;
        Dog aDog = new Dog("Max");
        System.out.println("int Before modification   "+abc);
        System.out.println("Dog object Before modification   "+aDog.name);
        System.out.print("Array Before modification   ");
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
        System.out.println();
        modifyArray(a,abc,aDog);
        System.out.println("int After modification   "+abc);
        System.out.println("Dog object after modification   "+aDog.name);
        System.out.print("Array After modification    ");

        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
    }

    public static void modifyArray(int []b, int x, Dog d)
    {
        // d.setName("Fifi");   // would change the name of the dog
          d = new Dog("Fifi"); // would not change the original variable

         // b[0] = 3;       // would change the contents of the original array
          b = new int[1]; // followed by...
          b[0] = 3;       // would not affect the original array
          x=34;             // It would not affect the original value
    }
}


 class Dog {
    String name=null;
    public Dog(String aname)
    {
        name=aname;
    }

    public void setName(String bname)
    {
        name=bname;
    }
}

Monday, March 12, 2012

OccurancesInArray

import java.io.*;

public class OccurancesInArray{
  public static void main(String[] argsthrows IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("How many elements you want to enter in the array: ");
  int num=0;
  try{
  num = Integer.parseInt(in.readLine());
  }
  catch(NumberFormatException ne){
  System.out.println(ne.getMessage() " is not a number!");
  System.exit(0);
  }
  String[] elements = new String[num];
  int a;
  int k;
  for(int i = 0; i < num; i++){
  elements[i= in.readLine();
  }
  for(int i = 0; i < elements.length; i++){
  a = 0;
  k = 1;
  for(int j = 0; j < elements.length; j++){
  if(j >= i){
  if(elements[i].equals(elements[j]) && j != i){
  k++;
  }
  }
  else if(elements[i].equals(elements[j])){
  a = 1;
  }
  }
  if(a != 1){
  System.out.println("Occurance of \'" + elements[i"\' : " + k);
  }
  }
  }
}

FindMissingNumber

/*Find out sum of n numbers and substract the sum of numbers from this sum.
 *
 *
 */
public class FindNumber {

    public static void main(String [] args)
    {
        int totalsum=10*(10+1)/2;
        int givensum=0;
        int [] a={1,4,3,2,5,7,9,8,10};
        for(int i=0;i<a.length;i++)
        {
            givensum +=a[i];
        }
        int missingnum=totalsum-givensum;
        System.out.println(" Missing number is :"+missingnum);
    }
}

Palindrome


import java.io.*;


public class Palindrome {

public static void main(String []args )
{
        palindromeEx ex=new palindromeEx();
        ex.palindrome(121);
        ex.palindrome("ADHCVBVCHDAA");
        ex.palind("ANANDNANA");
    }
}

class palindromeEx
{
    public void palindrome(int a)
    {
        //121
        int original=a;
        int reverse=0;
        while(a>0)
        {
            int b=a%10;
            reverse=reverse*10+b;
            a=a/10;
        }
        if(reverse==original)
        {
            System.out.println("Number is palindrome : "+reverse);   
        }
        else
            System.out.println("Number is not palindrome : "+reverse);

    }

    public void palinwithFor(int in)
    {
        int length=in;

        int rev=0;

        System.out.println("Entered number is:   "+in);

        for (int j=0;j<length;j++)

        {

            int num=length%10;

            length=length/10;

            rev=(rev*10)+num;

            j--;

        }

        System.out.println("Reverse number is:   "+rev);

        if(in==rev)

        {

            System.out.println("Number is palindrome");

        }

        else

            System.out.println("Number is not palindrome");
    }
    public void palindrome(String a)
    {
        String original=a;
        String reverse="";
        int length =a.length();
        for (int i=a.length();i>0;i--)
        {
            reverse=reverse+a.charAt(i-1);   
        }
        if(reverse.equalsIgnoreCase(original))
        {
            System.out.println("String is palindrome : "+reverse);   
        }
        else
            System.out.println("String is not palindrome : "+reverse);

    }

    public void palind(String a)
    {
        String original=a;
        String reverse=new StringBuffer(a).reverse().toString();
        if(reverse.equalsIgnoreCase(original))
        {
            System.out.println("String is palindrome : "+reverse);   
        }
        else
            System.out.println("String is not palindrome : "+reverse);

    }

}

Sunday, March 11, 2012

Nth Largest number in List


import java.io.*;

public class NthLargest {

public static void main(String args[])
{
int A[] = new int[]{6,5,2,7,3,8,32,1,43,87,45};
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter number");
try {
int n = Integer.parseInt(reader.readLine());
int res = 0;
for(int i=0;i<A.length;i++)
{
int k = 0;
for(int j=0;j<A.length;j++)
{
if(A[i]<A[j])
++k;
if((k==(n-1))&&(j==A.length-1))
{
res = A[i];
i = A.length;
}
}
}
System.out.println("The "+n+"th largest number is  :"+res);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//This is the supposed nth largest number,here it is third
}
}

Largest/Smallest number in array



import java.util.ArrayList;
public class SmallestinList {
public static void main(String []args)
{
int []a = {12,23,15,34,45,56,67,89,80,8,80,11};
ArrayList<Integer> list=new ArrayList<Integer>();
//list=Arrays.asList(a);
for(int i=0;i<a.length;i++)
{
list.add(a[i]);
}
//Using sort method of collection class
/*Collections.sort(list);
System.out.println("The sorted list is"+list.toString());
int n=list.size();
System.out.println(" Length of list "+n);
System.out.println("The smallest number in list is:  "+list.get(0));
System.out.println("The Largest number in list is:  "+list.get(n-1));
System.out.println("The second largest number in list is:  "+list.get(n-2));*/
//Self implementation
int smallest=list.get(0);
int largest=list.get(0);
for (int i=0;i<list.size()-1;i++)
{
if(smallest>list.get(i+1))
{
smallest=list.get(i+1);
}
if(largest<list.get(i+1))
{
largest=list.get(i+1);
}
}
System.out.println("The smallest number in list is:  "+smallest);
System.out.println("The Largest number in list is:  "+largest);
}
}


Saturday, March 10, 2012

CountFilesinDir



import java.io.*;

public class CountFilesInDirectory {
static int count;
        public static void main(String[] args) {
                File f = new File("C:/Users/anandy/Downloads/Resume");
                countFile(f);
                System.out.println("Number of files: " + count);
        }
       
        public static void countFile(File fdir)
        {
            for (File file : fdir.listFiles()) {
                if (file.isFile()) {
                        count++;
                }
                else
                {
                String path = file.getAbsolutePath();
//Extra check for backward /
              //String absPath= path.replace('\\', '/');
               //System.out.println(path);
               //System.out.println(absPath);
               File f1=new File(path);
                countFile(f1);
                }
        }
        }
}

Tuesday, March 6, 2012

Interactive program for Factor

import java.io.*;
public class Factor {

    public static void main(String [] args)
    {
        getFactor();
        while(true)
        {
        System.out.print("Do you want another number?(YES/NO)  ");
        BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
        try {
            String decision = reader.readLine();
            if(decision.equalsIgnoreCase("YES")|| decision.equalsIgnoreCase("Y"))
            {
                getFactor();
            }
            else
            {
                System.out.println("Exiting...");
                break;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
    public static void getFactor()
    {
    BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.print("Please enter a number for factor:  ");
        int n=Integer.parseInt(reader.readLine());
       
        for(int i=2;i<=n;i++)
        {

      if(i>n/2)
{
i=n;
}

            while (n%i==0)
            {
                System.out.println("  "+i);
                n=n/i;
            }
        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
    }

Thursday, March 1, 2012

JDBCSample

import java.sql.*;
class JDBCSample {
  public static void main (String[] args) throws Exception
  {
   Class.forName("oracle.jdbc.OracleDriver");

   /*Connection conn = DriverManager.getConnection
     ("jdbc:oracle:thin:@//localhost:1521/orcl", "system", "admin");
                        // @//machineName:port/SID,   userid,  password*/
   Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott", "tiger");
   try {
     Statement stmt = conn.createStatement();
     try {
       ResultSet rset = stmt.executeQuery("select BANNER from SYS.V_$VERSION");
      // ResultSet rset = stmt.executeQuery("select 'Shalini' from dual");
       try {
         while (rset.next())
           System.out.println (rset.getString(1));   // Print col 1
       }
       finally {
          try { rset.close(); } catch (Exception ignore) {}
       }
     }
     finally {
       try { stmt.close(); } catch (Exception ignore) {}
     }
   }
   finally {
     try { conn.close(); } catch (Exception ignore) {}
   }
  }
}

Sunday, February 26, 2012

ArrayListExample

// Find out why it throws exception at  list.remove(d);

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {

        @SuppressWarnings("rawtypes")
        public static void main(String[] args) {
     
        ArrayList<Comparable> list=new ArrayList<Comparable>();   
        //ArrayList<Integer> list=new ArrayList<Integer>();
        int a=8;
        String b="Anand";
        boolean c=true;
        list.add(a);
        list.add(b);
        list.add(c);
        int size=list.size();
            System.out.println("The size of list is :  "+size);
            int indexc=list.indexOf(c);
            System.out.println("The Index of c is :  "+indexc);
            char d='A';
            list.add(2, d);
            System.out.println("The size of list is :  "+size);
            indexc=list.indexOf(c);
            System.out.println("The Index of c is :  "+indexc);
            System.out.println("The value of d is :  "+list.get(list.indexOf(d)));
            list.remove(d);
            //System.out.println("The Index of c is :  "+list.get(list.indexOf(d)));
        Iterator<Comparable> itr=list.iterator();
        while(itr.hasNext())
        {
            System.out.println("The elements of list are:   "+itr.next());
        }
        }
}

Saturday, February 25, 2012

Static Variable Example


public class StaticExample {

    public static void main(String [] args)
    {
        StaticMethod sm =new StaticMethod();
        StaticMethod sm1 =new StaticMethod();
        sm.getValue(25,25);
        sm1.getValue(30,30);
        int val1=sm.var1;
        int val2=sm1.var1;
        int val3=sm.var2;
        int val4=sm1.var2;
        System.out.println("The value of 1st static instance:  "+val1+"" +
                "   The value of 2nd static instance:  "+val2);
       
        System.out.println("The value of 1st non static instance:  "+val3+"" +
                "   The value of 2nd non static instance:  "+val4);
    }
}

class StaticMethod {
   
    static int var1;
    int var2;
   
    public void getValue(int val1, int val2)
    {
        var1=val1;
        var2=val2;
       
        //return a;
    }

   
}

PrimeNumbers with Scanner

import java.util.*;

class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want ");
      n = in.nextInt();

      if ( n >= 1 )
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }        
   }
}

Print output without semicolon

interface abc
{
int a=10;   
}
public class SemiColon implements abc{
   
    public static void main(String [] args ){
        if (System.out.printf("Hello World", null).toString().length() > 20){ }       
//Example of ternary operator  
    int a=2;
    int b=3;
    int c=4;
    System.out.println((a>b?a:b)>c?(a>b?a:b):c);
    }
}

OverrideStatic

//Static method cannot be overridden. Look into the following code:
class ParentClass {
    public void method1(){
        System.out.println("Parent Method1");
    }
    public static void method2(){
        System.out.println("Parent Method2");
    }
}



class ChildClass extends ParentClass{
    public void method1(){
        System.out.println("Child Method1");
    }
    public static void method2(){
        System.out.println("Child Method2");
    }
}

public class OverrideStatic {
    public static void main(String args[]){
        ParentClass parent;
        ChildClass child = new ChildClass();
        parent = child;
        parent.method1();
        parent.method2();
    }
}

Why-is-the-tostring-method-being-called-when-i-print-an-object

//Example why-is-the-tostring-method-being-called-when-i-print-an-object
//Because PrintStream.println has an overload that takes an Object, and then calls //itstoString method
public class ABC {
    public static void main(String[] args) {
        Coin1 q = new Quarter1();
        System.out.println("I am calling get value on coin " + q.getABC());
   
        System.out.println(q);
     
    }
}

  class Money1 {
    private int value;

    public Money1(int v) {
        value=v;
    }

    public  int getValue()
    {
    return value;
    }

    protected int myValue() {
        return value;
    }

    public  String toString()
    {
    return "Anand";
  }
}

  class Coin1 extends Money1 {
    public Coin1(int value) {
        super(value);
        System.out.println("I am a coin, my value is " + getValue());
    }
 
    public int getABC() {
        return 23;
    }

}

 class Quarter1 extends Coin1 {
    public Quarter1 () {
        super(25);
    }

    public int getValue() {
        return myValue();
    }

    public String toString() {
        return "A Quarter is "+getValue();
    }
}

Constructor Calling

public class Test {

public static void main(String args[])
{
//Constructor related code block
System.out.println(args.length);
Parent a=new Parent();
System.out.println("1");
Child b=new Child();
System.out.println("2");
Parent c=new Child();
System.out.println("3");
//Child d=(Child)new Parent();
Parent d=(Parent) new Child();
System.out.println("4");
a.Method(34);
System.out.println("5");
b.Method(56);
System.out.println("6");
c.Method(102);
System.out.println("7");
d.Method(123);
}
}



public class Parent {

public Parent()
{
this("Anand");
System.out.println("Parent Constructor");
}

public Parent(String args)
{
System.out.println("Parent Constructor with args");
}

public void Method(int args)
{
System.out.println("Parent");
System.out.println(args);
}

}


public class Child extends Parent{
public Child()
{
this("Anand");
//super();
//this.thisCall();
//Child("Annad");
System.out.println("Child Constructor");
}

public Child(String args)
{
System.out.println("Child Constructor calling with args cons");
}
public void thisCall()
{
System.out.println("Child Constructor calling this");
}
public void Method(int args)
{
System.out.println("Child");
System.out.println(args);
}

}


SerializationDemo

import java.io.*;
public class SerilizationExm {

public static void main(String args[])
{
int i=10;
int j=0;
long start = System.currentTimeMillis ();
//Serializing object

MyClass2 a= new MyClass2();
try {
MyClass1 object1=new MyClass1("Anand",27,1984,a);
System.out.println("Object1:     "+object1);
FileOutputStream fos=new FileOutputStream("Stream");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(object1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
MyClass1 object2;
//System.exit (0);
//Runtime.getRuntime().exit(0);
FileInputStream fis=new FileInputStream("Stream1");
ObjectInputStream ois=new ObjectInputStream(fis);
object2=(MyClass1)ois.readObject();
System.out.println("Object2:     "+object2);
//System.exit (0);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File name mentioned does not exists");
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
System.out.println("This is finally Method"+i/j);
}
catch(ArithmeticException e)
{
System.out.println("Exception in finally");
//e.printStackTrace();
}
}
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start)+"  In milli seconds");
}
}

 class MyClass1 implements Serializable
 {
String s;
static  int c=2;
String d;
int a;
long b;
public MyClass1(String ab,int bc,long ac,MyClass2 abc )
{
s=ab;
a=bc;
b=ac;
d=abc.aMethod();
}

public String toString()
{
//d=(new MyClass2()).aMethod();
return "s="+s+";a="+a+";b="+b+";c="+c+";d="+d;
}


 }

 class MyClass2
 {
public String aMethod()
{
return "Prakash";
}
 }