Java Samples Codes

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)
Tells you the domain name and IP of the machine
XML Parser
Create Text to speech with JSAPI

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;
   }
}



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;
   }
}


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();
 }
}
}



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



XMLParserUtils.java

import javax.xml.parsers.*;
import org.w3c.dom.*;

  /**
  * 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;
   }
    }



ReadContentsOfURL.java

import java.io.*;
import java.net.*;

   /**
   * 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 );
   }
   }



ProcessExec.java

import java.io.IOException;

  /**
  * 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();
  }
  }
  }



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;

  /**
  * 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 World" string
  synthesizer.speakPlainText("Hello World", null);
  // wait till speaking is done
  synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
   // clean up
   synthesizer.deallocate();
  }
  catch (Exception e) {
   e.printStackTrace();
  }
  System.exit(0);
   }
  }



BasicDateFormatting.java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
  /**
  * 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 );
  }
  }



Whoami.java
  /**
  * 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.
  * 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) ;
  }
  }
  }
  //------------

Related:

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.