Java core code routine
1.java core code routine: helloworld.java// The MOST Basic Java Program Public Class HelloWorld {public static void main (string args [] "throws exception {system.out.println (" Hello World! ");} }
2. Java's core code routine: StringBufferDemo.java/ ** * Demo use of a StringBuffer *** / public class StringBufferDemo {public static void main (String args []) throws Exception {StringBuffer sb = new StringBuffer (); Sb.append ("Hello, World!"); sb.append (123); sb.append (","); sb.append (2.5); system.out.println (sb.toString ());}}
3. Java core code routines: DateFormat.java
import java.text *;.. / ** * Demo date formatting *** / public class DateFormat {public static void main (String args []) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat ( "MM.dd.yy kk. mm.ss.s "); system.out.println (sdf.format (new java.util.date ()));}}
4. Java's core code routine: VectorDemo.javaimport java.util *; / ** * Demonstrates how to use a Vector (essentially a growable array) *** / public class VectorDemo {public static void main (String args.. []) Throws exception {vector v = new vector (); v.addelement ("mary"); v.addelement ("david"); v.addeElement ("PAM"); v.addeElement ("joe"); for (int i = 0; i 5. Java core code routines: jdbc.javaimport java.sql. *; / ** * Simple demo of how to perform a sql query useing jdbc. ** / public class jdbc {public static void main (String args " ) throws Exception {Class.forName ( "sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection ( "jdbc: odbc: EmpPrjDB", "admin", "letmein"); Statement stmt = conn.createStatement ( ); ResultSet Rslt = Stmt.executeQuery ("SELECT NAME, City from Employee); While (RSLT.Next ()) {System.out.Println (" Hello World from " Rslt.getstring (1) // You CAN Use getString (ColumnNumber) "in" rslt.getstring ("city")); // or, you can use getString (columnname)} rslt.close (); stmt.close (); conn.close (); }} 6. Java core code routine: rmiexampleServer.javaimport java.rmi. *; Import java.rmi.server. *; / ** * this class is a simple escLle of a RMI Server * @Author Re nga ** / public class RMIExampleServer extends UnicastRemoteObject implements RMIExample {/ ** * Do nothing constructor * @throws RemoteException ** / public RMIExampleServer () throws RemoteException {System.out.println ( "RMIExampleServer :: cntr");} / * * @Return World from RMI! "* @Return a string * @throws remoteexception ** / public string sayhello () throws remoteException {return" Hello World from RMI! ";}} 7. Java's core code routine:.. CalendarDemo.javaimport java.util *; / ** * Demo Calendar class *** / public class CalendarDemo {public static void main (String args []) throws Exception {GregorianCalendar cal = New Gregoriancalendar (); Cal.SetTime (New Date ()); System.out.Println ((CAL.GET (Calendar.Mont) "/" Cal.Get (Calendar.day_Of_Month) "/" Cal.get (Calendar.Year));}} 8. Java core code routine: PropertiesDemo.javaimport java.util. *; Import java.io. *; / ** * Demonstrates how to sort strings. ** * / public class protectiesdemo {public static void main (string args []) throws exception {Properties PROPS = new profment (); prOPs.PUT ("db.user", "jack"); prOPs.put ("db.password "," Opendoor "); // getProperty Will Return the value if found, Otherwise null system.out.println (Props.GetProperty (" db.user ")); // getProperty Will Return the VAL UE if found, OtherWise "None" system.out.println (Props.getProperty, "None")); / * // You can Also Load Properties from a file fileinputstream FII = New fileinputstream ("My" .properties "); PrOPS.LOAD (FIS); fis.close (); ** /}} 9. Java's core code routine: ThreadDemo.java / ** * Demo how threads in Java work *** / public class ThreadDemo extends Thread {private int startingNumber = 0; public ThreadDemo (int startingNumber) {this.startingNumber = startingNumber } // this method Runs in a Separate Thread public void () {// loop 10 Times for (INT i = startingnumber; i <(startingnumber 100); i ) System.Println (i);} / / Test Driver public static void main (string args []) throws exception {threadDemo t1 = new threadDemo (100), t2 = new threadDemo (200); t1.start (); t2.start ();}} 10. Java the core code routine: RMIExampleSetup.javaimport java.rmi *; import javax.naming *; / ** * This class registers RMIExampleServer with the RMI registry * @author Renga ** / public class RMIExampleSetup {/ ** * Main.. Method * @Param args command-line arguments ** / public static v oid main (String [] args) {try {// Set the security manager System.setSecurityManager (new RMISecurityManager ()); // Create a new object of RMIExampleServer RMIExampleServer server = new RMIExampleServer (); // Bind this object with the RMI registry naming.bind ("rmiexample", server);} catch (exception e) {E.PrintStackTrace ();}}} 11. Java's core code routine: RMIExample.javaimport java.rmi *; / ** * Remote interface for the RMIExampleServer * @author Renga ** / public interface RMIExample extends Remote {/ ** * Returns a string to the caller. * @Return a string * @throws remoteexception ** / public string Sayhello () throws remoteException; 12. Java core code routine: java.policygrant {permission java.security.Allpermission;}; 13. Java core code routine: showfilecontent.javaimport java.io. *; // read a file useing buffredreader.readline ) public class ShowFileContent {public static void main (String args []) throws Exception {FileReader fr = new FileReader ( "c: /autoexec.bat"); BufferedReader br = new BufferedReader (fr); String line = null; while ( (line = br.readline ())! = NULL) System.out.println (line); br.close ();}} 14. Java core code routines: javamail ---- popmail.javaimport java.io. *; import java.util. *; Import javax.mail. *; Import javax.mail.internet. *; Import javax.actiVation . *; / ** * Demonstrate POP mail using JavaMail Requires mail.jar activation.jar * Sample run: java -cp; mail.jar; activation.jar PopMail ** / public class PopMail {public static void main (String.. args []) throws Exception {String pop3Host = "myhost.com", popUser = "john", popPassword = "letmein"; Session session = Session.getDefaultInstance (System.getProperties (), null); Store store = session.getStore ( "pop3"); store.connect (pop3Host, -1, popUser, popPassword); // Open the default folder Folder folder = store.getDefaultFolder (); if (folder == null) throw new NullPointerException ( "No default mail "); folder = folder.getFolder (" inbox "); if (folder == null) throw new nullpointersException (" Unable to get folder: folde R); // Get Message Count Folder.open (Folder.Read_Write); int totalmessages = folder.getMessageCount (); if (TotalMessages == 0) {system.out.println ("no message found in in inbox); Folder .close (false); store.close (); return;} // Get Attributes & flags for all messages = folder.getMess (); fetchprofile fp = new fetchprofile (); fp.add (fetchprofile.Item) .Envelope); fp.add (fetchprofile.Item.flags); fp.add ("x-mailer"); Folder.Fetch (Messages, fp); // process Each Message for (INT i = 0; I / ** * Home interface for HelloWorldSessionBean * * @see HelloWorldSessionBean ** / public interface HelloWorldSessionHome extends javax.ejb.EJBHome {HelloWorldSession create () throws javax.ejb.CreateException, java.rmi.RemoteException;} 16. Java Core code routine: (EJB) Remote Interface / ** * Remote interface for HelloWorldSessionBean * * @see HelloWorldSessionBean ** / public interface HelloWorldSession extends javax.ejb.EJBObject {public String sayHello () throws java.rmi.RemoteException;} 17. Java core code routines: (JAX) DomImPort javax.xml.parsers. *; Import org.w3c.dom. *; Import org.xml.sax. *; / ** * Domdemo Uses jaxp to acquire a documentbuilder . to build a DOM Document from an XML file * The example XML file represents a shopping cart * * The following JARs must be in your CLASSPATH:. * - jaxp.jar * - xerces.jar (for SAX parser and DOM object implementations) * * Download Jaxp (Which Includes these Jars) Here: http://java.sun.com/xml/ * Find Additional Xerces Info Here: http://xml.apache.org/ * ** / public class Domdemo {public static void main (String [] args) {try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); System.out.println ( "DocumentBuilderFactory classname:". factory.getClass () getName ()); DocumentBuilder builder = factory.newDocumentBuilder (); System.out.Println ("DocumentBuilder ClassName:" builder.getClass (). Getname ()); // Parse the xml file and create the document Document D Ocument = builder.parse ("cart.xml"); / * At this point, All Data IN THE XML FILE HAS BEEN PARSED AND Loaded Into Memory in the form of a trecess. The document is a tree of node objects. This printNode () method simply recurses through a Node tree and displays info about each node ** / printNode (document, "");.} catch (Exception e) {e.printStackTrace ();}} / ** * printNode is A Recursive Method That Prints Info About Each Node * in a Node Tree to System.out. Call it with the root node of your node tree and * an inTIAL Indent of "" ** / public static void printnode (node node, string indent) {string text = null; if (node.getnodetype () == node.text_node) text = node.getnodeValue (). Trim (); else text = node. GetNodename (); if (text.length ()> 0) System.out.println (Indent GetNodetyPename (Node) ":" text); nodelist childnodes = node.getChildNodes (); for (int i = 0; i 18. Java core code routine: jniexample.java / ** * this class is a simple example this class a native function * @Author RENGA ** / public class jniexample {static {system.loadLibrary ("jni");} / ** * native method Declaration. Just returns the string "Hello World from Jni!" * @Return a string ** / public native string Sayhello (); / ** * main method * @Param args command-line arguments ** / public static void main (String [] args) {// create a new jniexample object jniexample temp = new jniexample (); // invoke the native method system.out.println ());}} 19. Java core code routine: (JAX) SAXIMPORT JAVAX.XML.PARSERS. *; Import Org.xml.sax. *; / ** * Saxdemo Usess JAXP to Acquire A Sax Parser to Parse An Xml File. * The example XML file represents a shopping cart * * The following JARs must be in your CLASSPATH:. * - jaxp.jar * - xerces.jar (for SAX parser implementation) * * Download JAXP (which includes these JARs) here: http: / /java.sun.com/xml/ * Find Additional Xerces Info Here: http://xml.apache.org/ * * Note: Unlike Dom, SAX Parsing Does Not Load The XML File Into Memory. * Sax Parsers Traverse The XML File and report parse "Events" to an off detes org.xml.sax.handlerbase {/ ** * main creates and runs a saxtest instance. ** / public static void main (String " args) {SAXDemo me = new SAXDemo (); me.run ();} public void run () {try {SAXParserFactory factory = SAXParserFactory.newInstance (); log ( "SAXParserFactory classname:" factory.getClass (). ge tName ()); SAXParser saxParser = factory.newSAXParser (); log ( "SAXParser classname:" saxParser.getClass ().. getName ()); / * The SAXParser.parse method initiates parsing of the XML file The second parameter Specifies Which Class Will Handle Parse Events. this class must extend org.xml.sax.handlerbase ** / saxparser.parse ("cart.xml", this);} catch (exception e) {E.PrintStackTrace ();}} / ** * log simply prints the specified message to system.out ** / public void log (STRING Message) {system.out.println (Message); } / ** * SAXParser calls startDocument () when it starts parsing a document ** / public void startDocument () throws SAXException {log ( "Start SAX parse");} / ** * SAXParser calls endDocument () when it finishes parsing a document ** / public void endDocument () throws SAXException {log ( "End SAX parse");} / ** * SAXParser calls startElement () when it encounters an opening element tag (eg 20. Java core code routines: javamail ---- smtpmail.javaimport java.io. *; import java.util. *; Import javax.mail. *; Import javax.mail.internet. *; Import javax.activation. * ; public class SmtpMail {public static void main (String args []) throws Exception {// create some properties and get the default Session Properties props = new Properties (); props.put ( "mail.smtp.host", "yoursmtpserver "); Session session = Session.getDefaultInstance (props, null); Message message = new MimeMessage (session); // create a message InternetAddress ia [] = new InternetAddress [1]; ia [0] = new InternetAddress (" myself @ abc.com "," me "); Message.SetFrom (New Internetdress (" Test@abc.com "," Some Developer "); Message. RecipientType.to, IA); Message.setSubject "Hello World"); Message.Settext ("Hello World! This Message Was Generated Using JavaMail."); Message.SAVEChanges (); Trans Port transport = session.getTransport ("smtp"); transport.connect (); transport.send (message);}} 21. Java core code routine: jniexample.java/* do not Edit this file - IT is Machine generated ** / #include twenty two. Java core code routine: (jaxp) Cart.xml XML version = "1.0"?> shopping cart h1>