Here are some java samples codes that may help you.

Factorial
Prime #
ASCII code printing
See how the #s are stored in memory(this helps u to understand binary operations)
XML Parser
Read Contents Of URL
Date Formatting
To start a process(Spawn a process within the jvm)
Hide Password From CommandLine
Tells you the domain name and IP of the machine
XML Parser
XML Parser
Create Text to speech with JSAPI
A Desktop Telephone Application

More samples will be added...


 
 
 
 
 
 

Factorial.java
import java.util.*;
import java.lang.*;
public class Factorial {
   public static void main(String[] args)
   {
   if (args.length == 0)
        System.out.println("Example: java Factorial 10");
   try
   {
        for (int i=0; i < args.length; i++)
        {
          System.out.print("Fact of Param # " + (i+1) + ": " + Fact(args[i]));
        }
   }
   catch(Exception E)
   {
        System.out.println(E.getMessage());
   }
   }
   public static long Fact(String f) throws Exception
   {
        int f1 = Integer.parseInt(f);
        long Result = 1;
        if (f1 < 0)
                throw new Exception("I can not calculate this!");
        if (f1 > 20)
                throw new Exception("that is a big ####");
        try
        {
        for (int j=1; j <= f1; j++)
                Result *= j;
        }
        catch(Exception e)
        {
                System.out.println(e.getMessage());
                throw e;
        }
        return Result;
   }
}
Top
 
 
 

Prime.java
import java.util.*;
import java.lang.Math;
public class Prime {
   public static void main(String[] args)
   {
 for (int i = 1; i < 1500; i++)
    if (isPrime(i))
       System.out.println(i);
   }
   public static boolean isPrime(int n)
   {
 for (int i = 2; i <= Math.sqrt(n); i++)
 {
  if (n % i == 0)
   return false;
 }
 return true;
   }
}
Top

ASCII_code.java
public class ASCII_code{
public static void main(String argv[]){

 System.out.println("Value\tChar\tValue\tChar\tValue\tChar\tValue\tChar\tValue\tChar\t");
 int c=1;
 while (c < 256)
 {
  for (int col = 0; col <  5 && c < 256; col++, c++)
   System.out.print(c + "\t" + (char)c + "\t");
  System.out.println();
 }
}
}
Top
 
 
 
 

Bin.java

import java.awt.*;
import java.awt.event.*;

/*
RUN THIS PROGRAM AND ENTER 2 VALUES(+ve or -ve), then CLICK ON
THE OPERATOR BUTTON...SEE THE RESULT in binary(exactly the
way it is stored in memory).
*/
class BinApp extends Frame {
   TextField T1, T2;
  Label Result, Error;
  Button bAND, bOR, bXOR, bRShift, bLShift,bRRShift;

 BinApp(){
  Panel P = new Panel();
  Panel P_edit = new Panel();
  Panel P_btn = new Panel();
  Panel P_result = new Panel();
  add(P, "Center");
  P.setLayout(new GridLayout(3, 0));
    P.add(P_edit);
       T1 = new TextField(20);
      T2 = new TextField(20);
      P_edit.add(T1);
      P_edit.add(T2);
    P.add(P_btn);
      bAND = new Button("&");
      bOR = new Button("|");
      bXOR = new Button("^");
      bRShift = new Button(">>");
      bLShift = new Button("<<");
      bRRShift = new Button(">>>");
      P_btn.setLayout(new GridLayout(3, 0));
           P_btn.add(bAND);
      P_btn.add(bOR );
      P_btn.add(bXOR);
      P_btn.add(bRShift);
      P_btn.add(bLShift);
      P_btn.add(bRRShift);
    P.add(P_result);
      Result = new Label(" ");
      Error = new Label("");
      P_result.setLayout(new GridLayout(2, 0));
      P_result.add(Result);
      P_result.add(Error);
  ButtonHandler handler = new ButtonHandler();
       bAND.addActionListener(handler);
       bOR.addActionListener(handler);
       bXOR.addActionListener(handler);
       bRShift.addActionListener(handler);
       bLShift.addActionListener(handler);
   bRRShift.addActionListener(handler);
  Error.setForeground(Color.red);
      }

  class ButtonHandler implements ActionListener{
    public void actionPerformed(ActionEvent e){
   Error.setText("");
        String s = e.getActionCommand();
   int n1 = getInt(T1.getText());
   int n2 = getInt(T2.getText());
        if (s=="&")
  Result.setText(printBin(n1&n2));
        else if (s=="|")
  Result.setText(printBin(n1|n2));
        else if (s=="^")
  Result.setText(printBin(n1^n2));
        else if (s==">>")
  Result.setText(printBin(n1>>n2));
        else if (s=="<<")
  Result.setText(printBin(n1<<n2));
        else if (s==">>>")
  Result.setText(printBin(n1>>>n2));
    }
  }
  int getInt(String s)
  {
 int n1 = 0;
 try
 {
   n1 = Integer.parseInt(s);
 }
 catch(Exception e)
 {
    Error.setText("Illegal integer #: " + s);
 }
 return n1;
  }
  String printBin(int x)
  {
 String result = "";

 int filter = 0x40000000;
 try
 {
  if ((x & 0x80000000) == 0x80000000)//This is sign bit
   result = result + "1";
  else
   result = result + "0";
 for (int i=0; i < 31; i++)
 {
  if ((filter & x) == filter)
   result = result + "1";
  else
   result = result + "0";
  filter = filter >> 1;
 }
 }
 catch(Exception e)
 {
  System.out.println("ERROR");
 }
 return result;
  }
}

public class Bin extends Frame {
 public static void main(String[] arg) {
  BinApp a = new BinApp();
  a.setSize(250,200);
  a.setVisible(true);
  }
}
Top


 
 
 
 
 

XMLParserUtils.java

import javax.xml.parsers.*;
import org.w3c.dom.*;
 
  /**
  * @author kishore
  * Created on Nov 21, 2002
  * Used for parsing elements & attributes
  */
 
public class XMLParserUtils {
 
   /**
   This method is used to get the value of the element.
   The element should have only one text node, and no child elements.
   Eg: xxx
   @params n = 'value' node
   @return value = 'xxx' in the value element
   */
   public static String getElementValue(Node n) {
  String retVal = null;
   Node textNode = n.getFirstChild();
   if((textNode != null) && (textNode.getNodeType() == Node.TEXT_NODE)) {
   retVal = textNode.getNodeValue();
   }
  return retVal;
   }
 
  /**
   This method is used to get the value of the attribute in an element.
   Eg: xxx
   @params n = 'value' node
   @params attr = attribute name, 'id' in the above example
   @return value = "abc" the attribute value of id in the value element
   */
 
   public static String getAttributeValue(Node n, String attr) {
  String retVal = null;
  if(n.getNodeType() == Node.ELEMENT_NODE) {
   retVal = ((Element)n).getAttribute(attr);
  }
  return retVal;
   }
    }
  Top
 
 
 
 
 

ReadContentsOfURL.java

import java.io.*;
import java.net.*;
 
   /**
   * @author kishore
   * Created on Feb 20, 2003
   */
   public class ReadContentsOfURL{
   public static void main(String[] args) throws Exception
   {
   // create a URL object and open a stream to it
   URL httpUrl = new URL("http://www.weather.com/weather/local/94539?lswe=94539");
   InputStream istream = httpUrl.openStream();
   // convert stream to a BufferedReader
   InputStreamReader ir = new InputStreamReader(istream);
   BufferedReader reader = new BufferedReader( ir );
   // then read the contents of the URL through a BufferedReader
   StringBuffer buf = new StringBuffer();
   int nextChar;
   while( (nextChar = reader.read()) != -1 )
   {
   buf.append( (char)nextChar );
   }
   // close the reader
   reader.close();
   System.out.println( buf );
   }
   }
  Top
 
 
 
 
 

ProcessExec.java

import java.io.IOException;
 
  /**
  * @author kishore
  * Created on Feb 21, 2003
  */
  // To start a process(Spawn a process within the jvm)
  public class ProcessExec
  {
  public static void main( String[] argv )
  {
  String command = "c:\\winnt\\explorer.exe";
  try
   {
   Process process = Runtime.getRuntime().exec( command );
  }
  catch ( IOException ioex )
  {
  ioex.printStackTrace();
  }
  }
  }
  Top
 
 
 
 
 

HidePasswordFromCommandLine.java

import java.io.*;
 
  /**
  * @author kishore
  * Created on Feb 21, 2003
  */
  public class HidePasswordFromCommandLine extends Thread {
  boolean stopThread= false;
  boolean hideInput= false;
  boolean shortMomentGone= false;
  public void run() {
  try {
  sleep(500);
  } catch (InterruptedException e) {}
  shortMomentGone= true;
  while (!stopThread) {
  if (hideInput) {
  System.out.print("\b*");
  }
  try {
  sleep(1);
  } catch (InterruptedException e) {}
  }
  }
  public static void main(String[] arguments) {
  String name= "";
  String password= "";
  HidePasswordFromCommandLine hideThread= new HidePasswordFromCommandLine();
  hideThread.start();
  BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
  try {
  System.out.println("Name: ");
  // Wait for the username and clear the keyboard buffer (if neccessarry)
  do {
  name= in.readLine();
  }
  while (hideThread.shortMomentGone == false);
  // Now the hide thread should begin to overwrite any input with "*"
  hideThread.hideInput= true;
  // Read the password
  System.out.println("\nPassword:");
  System.out.print(" ");
  password = in.readLine();
  hideThread.stopThread= true;
  }
  catch (Exception e) {}
  System.out.print("\b \b");
  // JUST FOR TESTING - PLEASE DELETE!
  System.out.println("\n\nLogin= " + name);
  System.out.println("Password= " + password);
  }
  }
  Top
 
 
 
 
 

TTSTest.java
import java.io.File;
import java.util.Locale;
import javax.speech.Central;
import javax.speech.Engine;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.SynthesizerProperties;
import javax.speech.synthesis.Voice;
 
  /**
  * @author kishore
  * Created on Dec 6, 2002
  * Simple program showing how to use TTS in JSAPI.
  */
  public class TTSTest {
  public static void main(String[] argv) {
  try {
  String synthesizerName = System.getProperty
  ("synthesizerName",
  "Unlimited domain FreeTTS Speech Synthesizer from Sun Labs");
  // Create a new SynthesizerModeDesc that will match the TTS
  // Synthesizer.
  SynthesizerModeDesc desc = new SynthesizerModeDesc
  (synthesizerName,
  null,
  Locale.US,
  Boolean.FALSE, // running?
  null); // voice
  Synthesizer synthesizer = Central.createSynthesizer(desc);
  if (synthesizer == null) {
  String message = "Can't find synthesizer.\n" +
  "Make sure that there is a \"speech.properties\" file " +
  "at either of these locations: \n";
  message += "user.home : " +
  System.getProperty("user.home") + "\n";
  message += "java.home/lib: " + System.getProperty("java.home")
  + File.separator + "lib\n";
  System.err.println(message);
  System.exit(1);
  }
   // create the voice
   String voiceName = System.getProperty("voiceName", "kevin16");
  Voice voice = new Voice
  (voiceName, Voice.GENDER_DONT_CARE, Voice.AGE_DONT_CARE, null);
  // get it ready to speak
  synthesizer.allocate();
  synthesizer.resume();
   synthesizer.getSynthesizerProperties().setVoice(voice);
  // speak the "Hello Kishore" string
  synthesizer.speakPlainText("Hello Kishore", null);
  // wait till speaking is done
  synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
   // clean up
   synthesizer.deallocate();
  }
  catch (Exception e) {
   e.printStackTrace();
  }
  System.exit(0);
   }
  }
  Top
 
 
 
 
 

BasicDateFormatting.java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
  /**
  * @author kishore
  * Created on Feb 21, 2003
  */
  public class BasicDateFormatting
  {
  public static void main(String[] args) throws Exception
  {
   // get today's date
  Date today = Calendar.getInstance().getTime();
  // create a short version date formatter
  DateFormat shortFormatter
  = SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT );
  // create a long version date formatter
  DateFormat longFormatter
  = SimpleDateFormat.getDateInstance( SimpleDateFormat.LONG );
  // create date time formatter, medium for day, long for time
  DateFormat mediumFormatter
  = SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.MEDIUM,
   SimpleDateFormat.LONG );
  // use the formatters to output the dates
  System.out.println( shortFormatter.format( today ) );
  System.out.println( longFormatter.format( today ) );
  System.out.println( mediumFormatter.format( today ) );
  // convert form date -> text, and text -> date
  String dateAsText = shortFormatter.format( today );
  Date textAsDate = shortFormatter.parse( dateAsText );
  System.out.println( textAsDate );
  }
  }
  Top
 
 
 
 
 

Whoami.java
  /**
  * @author kishore
  * Created on Feb 14, 2003
  */
  import java.io.*;
  import java.net.*;
  public class Whoami
  {
  /**
  * Tells you the domain name and IP of the machine
  * you are running.
  * @author kishore
  * Created on Dec 6, 2002 *
  * @param args not used.
  */
  public static void main (String[] args)
  {
  try
  {
  InetAddress localaddr = InetAddress.getLocalHost () ;
  System.out.println ( "main Local IP Address : " + localaddr.getHostAddress () );
  System.out.println ( "main Local hostname : " + localaddr.getHostName () );
  System.out.println ( "main Domain name : " + localaddr.getCanonicalHostName());
  System.out.println () ;
  InetAddress[] localaddrs = InetAddress.getAllByName ( "localhost" ) ;
  for ( int i=0 ; i  {
  if ( ! localaddrs[ i ].equals( localaddr ) )
  {
  System.out.println ( "alt Local IP Address : " + localaddrs[ i].getHostAddress () );
  System.out.println ( "alt Local hostname : " + localaddrs[ i].getHostName () );
  System.out.println () ;
  }
  }
  }
  catch ( UnknownHostException e )
  {
  System.err.println ( "Can't detect localhost : " + e) ;
  }
  }
  }
  Top //-------------------