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) {}
   }
  }
}