abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try void volatile while
public class AJavaApp
{
public static void main( String Args[])
{
AJavaApp ja = new AJavaApp();
ja.doIt(Args);
}
public void doIt( String [] inArguments)
{
for (int i=0; i < inArguments.length; i++)
{
System.out.println("Command Line Argument # " + Integer.toString(i) +
" = " + inArguments[i]);
}
}
Compile these files using the Sun javac command like so:
int [] numbers = { 1, 2, 3, 4, 5 };
//*** Print out elements of Array
System.out.print("Printing array: ");
System.out.println();
Output = Printing array: 1, 2, 3, 4, 5,
//***** Create a new array twice the size of the original, and copy the original
//***** into the new array then- set the original array name "numbers" to the new array
int [] numbers = { 1, 2, 3, 4, 5 }; //Original Array
int [] copyOfNumbers = new int [numbers.length * 2]; //Copy to Array
System.arraycopy( numbers, 0, copyOfNumbers, 0, numbers.length); //Do array copy
numbers = copyOfPrimes; // Set "numbers" to point at new array
public void runTests()
{
int [] numbers = { 1, 2, 3, 4, 5 };
// Call another method passing it the array
char [] lettersReturned = PassArray(numbers);
for (int i=0; i < numbers.length; i++)
{
System.out.print( numbers[i] + ", ");
}
for (int i=0; i < lettersReturned.length; i++)
{
System.out.print( lettersReturned[i] + ", ");
}
System.out.println();
}
public char [] PassArray(int [] inArray)
{
char [] letters = { 'a', 'b', 'c' };
// "inArray" points at original array in arrayTest
System.out.print("Passing array to method: ");
for (int i=0; i < inArray.length; i++)
{
inArray[i] = 9; //* Change array in calling method
}
return letters;
}
Output = Passing array to method: 9, 9, 9, 9, 9, a, b, c,
String [] s = { "one", "two", "three" };
try {
for ( int i = 0; i < 999; i++)
{
System.out.print( s[i] + ", " );
}
}
catch ( ArrayIndexOutOfBoundsException err)
{ System.out.println("Handled error: " + err.getMessage() ); }
System.out.println();
Output = one, two, three, Handled error: null
char [][] myMatrix = {
{ 'x' },
{ 'x', 'x' },
{ 'x', 'x', 'x' },
{ 'x', 'x', 'x', 'x' },
{ 'x', 'x', 'x', 'x', 'x' },
{ 'x', 'x', 'x', 'x' },
{ 'x', 'x', 'x', },
{ 'x', 'x' },
{ 'x', }
};
System.out.println("Multi Dimension Array Test: ");
for (int i = 0; i < myMatrix.length; i++)
{
for (int k = 0; k < myMatrix[i].length; k++)
{
System.out.print( myMatrix[i][k] );
}
System.out.print("\n");
}
System.out.println();
Output =
x xx xxx xxxx xxxxx xxxx xxx xx x
class rec
{
public int i;
public String s;
rec(int iIn, String sIn)
{
this.i = iIn;
this.s = sIn;
}
}
.........................................
Character charObj;
Object [] objArray = new Object[10];
for (int i = 0; i < objArray.length; i++ )
{
charObj = new Character( (char)(i + 97) );
objArray[i] = new rec( i, charObj.toString() );
}
for (int i = 0; i < objArray.length; i++ )
{
System.out.print( ((rec)objArray[i]).i + " " + ((rec)objArray[i]).s + ", " );
}
System.out.println();
Output = 0 a, 1 b, 2 c, 3 d, 4 e, 5 f, 6 g, 7 h, 8 i, 9 j,
import java.util.Vector;
import java.util.Enumeration;
//************************************************************************
//***************** Test Programs ****************************************
//************************************************************************
class TestPrograms
{
// Vector Notes:
// Vectors are dynamic arrays of Objects that grow automatically as needed.
// Vectors Capacity is how many elements they can currently hold before growing. They
// default to growing by *2 unless its specified with a 2nd parameter (capacity increment)
// Vector Constructors:
// Vector StringVector = new Vector(); //Constructor:defaults to capacity size of 10
// Vector StringVector = new Vector(1); //Constructor: set to capacity size of 1
// Vector StringVector = new Vector(1,2); //Constructor:Capacity=1, Capacity increment=2
Vector StringVector = new Vector(1);
public void doSomething()
{
StringVector.addElement("one");
printVector(); //Output = "Vector=one,"
StringVector.addElement("two");
printVector(); //Output = "Vector=one, two,"
StringVector.addElement("three"); //Output = "Vector=one, two, three,"
printVector();
StringVector.setElementAt("TWO", 1);
printVector(); //Output = "Vector=one, TWO, three,"
StringVector.removeElement("TWO");
printVector(); //Output = "Vector=one, three,"
StringVector.insertElementAt("two", 1);
printVector(); //Output = "Vector=one, two, three,"
System.out.println("First Element = " + StringVector.firstElement()
+ " Last Element = " + StringVector.lastElement() );
//Output = "First Element = one Last Element = three"
if ( StringVector.contains("two") ) System.out.println("Vector contains \"two\" ");
//Output = "Vector contains "two""
if ( !StringVector.isEmpty() ) System.out.println("Vector is not emptey");
//Output = "Vector is not emptey"
System.out.println("Index of \"two\" is " + StringVector.indexOf("two") );
//Output = "Index of "two" is 1"
printVector(); //Output = "Vector=one, two, three,"
StringVector.removeElementAt(0);
printVector(); //Output = "Vector=two, three,"
StringVector.removeElementAt(0);
printVector(); //Output = "Vector=three,
StringVector.removeElementAt(0);
printVector(); //Output = "Vector="
if ( StringVector.isEmpty() ) System.out.println("Vector is emptey");
//Output = "Vector is emptey"
}
public void printVector()
{
Enumeration enum = StringVector.elements();
System.out.print("Vector=");
while ( enum.hasMoreElements() )
{
System.out.print( enum.nextElement() + ", " );
}
//This could also be written as follows:
//for (int i =0; i < StringVector.size(); i++)
// { System.out.print( StringVector.elementAt(i) + ", " ); }
System.out.println();
}
// Other Vector Methods:
// .trimToSize() Trim off unused capacity from Vector to save memory
// .size() Return current elements in use
// .capacity() Return current capacity of Vector
}// ******************** End of TestPrograms Class *************************
Output =
Vector=one, Vector=one, two, Vector=one, two, three, Vector=one, TWO, three, Vector=one, three, Vector=one, two, three, First Element = one Last Element = three Vector contains "two" Vector is not emptey Index of "two" is 1 Vector=one, two, three, Vector=two, three, Vector=three, Vector= Vector is emptey
//int to String
int i;
String s = Integer.toString(i);
or
String s = new String("" + i);
//String to int;
int n = Integer.parseInt("1234");
//String to long;
int n = Long.parseLong("1234");
//String to float, Note: Requres JDK 1.2
int n = Float.parseFloat("1234");
Inheritance should be used when there is a "Is a" relationship
between objects. When the sub-class would be a special case of the
super-class. Don't inherit when there is a "Has a" relationship.
For instance a "Employee" class should not be sub classed for "Salaried
Employee", and "Hourly Employee". Rather than saying a Hourly Employee
"is a" Employee- we should say a Employee "has a" status which is "hourly",
or "Full Time". The status can be variable that points to a object
held in a reference to an object- "EmployeeType"
Class c = object1.getClass(); //Get Class of this instantiated object.
Field [] fieldsArray = c.getDeclaredFields(); //Get a Array of "Field" objects representing every variable defined in the class
try { fieldsArray[1].set(objhect1,h.get( f[k].getName() ) ); }
This example will examine an Object and if any of its variable name are also found in
the passed Hashtable it will set them to the vaule for that key in the hash.
You might use this when loading object states from a file to a DB.
Will only work for strings as written.
import java.util.*;
import java.lang.reflect.*;
class T
{
public static void main (String args[] )
{
T t = new T();
t.doIt();
}
private void doIt()
{
Record r = new Record();
Hashtable h = new Hashtable();
h.put("title_id","TITLE-ID");
h.put("type","TYPE");
setObjectStringFieldsFromHash(r,h);
System.out.println("R title_id=" + r.title_id + " R type = " + r.type );
}
public static void setObjectStringFieldsFromHash(Object o, Hashtable h)
{
Field [] f;
Class c = o.getClass();
f = c.getDeclaredFields();
for ( int k = 0; k < f.length; k++)
{
System.out.println("F Name =" + f[k].getName() );
if ( h.containsKey(f[k].getName()) )
{
try { f[k].set(o,h.get( f[k].getName() ) ); }
catch (Exception e) { System.out.println("Exception=" + e.getMessage()); }
}
}
}
}
import java.util.*;
class Test
{
public static void main (String args[] )
{
Test t = new Test();
t.doIt();
}
private void doIt()
{
ObservableExample os = new ObservableExample();
ObserverExample o = new ObserverExample();
os.addObserver(o);
os.doSomethingWorthTelling();
}
}
------------------------------------------------------------------
import java.util.*;
class ObserverExample implements Observer
{
public void update(Observable observable, Object o)
{
System.out.println( ((String)o) );
}
}
------------------------------------------------------------------
import java.util.*;
public class ObservableExample extends Observable
{
public void doSomethingWorthTelling()
{
setChanged();
notifyObservers("Hi there");
setChanged();
notifyObservers("Bye now");
}
}
--------------------- Test.java ------------------------------------
import JDTools.*;
import java.util.*;
import java.lang.reflect.*;
/**
* This test application will print "Debugging Off" once a second.
* It instantiates a IPSignalCatcher class to listen for Telnet connections on port 5050.
* If the user Telnets to port 5050 while this application is running and types "debug=yes",
* the program will start printing "Debugging On" instead.
*/
class Test implements Observer
{
boolean debug;
public static void main (String args[] )
{
Test t = new Test();
t.doIt();
}
private void doIt()
{
Runnable ipsc = new IPSignalCatcher(this,5050);
while (true)
{
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
if (debug) System.out.println("Deguggin On");
else System.out.println("Debugging Off");
}
}
public void update(Observable observable, Object o)
{
System.out.println("Was updated by IPSignalCatcher, String passed = " + ((String)o) );
if ( ((String)o).indexOf("debug=yes") != -1 ) debug = true;
if ( ((String)o).indexOf("debug=no") != -1 ) debug = false;
}
}
---------------- IPSignalCatcher.java -------------------------------------
import java.util.*;
import java.net.*;
import java.io.*;
/**
* @IPSignalCatcher
* @version 1.0, 02 Dec 1998
* @author: John Donohue
*
* The purpose of this class is to provide a way of signaling a running Java application from a Telnet client
* across the network. The class listens for connections (under a seperate thread) for IP connections.
* Once the connection is made the server accepts a single line of input (terminated by \n) and then kills
* the connection, and returns to listening for new connections. The input line is sent to the Observer's
* of this class so that they can act on it.
* For example: If you have a Java application running as a Daemon, and you wish to tell it to begin
* writing debuggin messages to a log without stopping and starting it, you could use this class.
* Your application would Observe this class and react to its update method being with a string
* "debug=yes" being passed. To send the string telnet to the IP and port, and type the string.
*/
public class IPSignalCatcher extends Observable implements Runnable
{
int port;
public IPSignalCatcher(Observer o, int portIn)
{
this.addObserver(o);
Thread th = new Thread(this);
th.start();
this.port = portIn;
}
public void run()
{
ServerSocket server;
Socket connection;
InputStream input;
char c;
String s;
StringBuffer sb;
try
{
server = new ServerSocket(port, 100);
while ( true)
{
connection = server.accept();
input = connection.getInputStream();
sb = new StringBuffer();
while ( (c= (char)input.read() ) != '\n')
{
sb.append(c);
}
connection.close();
s = new String(sb.toString());
setChanged();
notifyObservers(s);
}
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Message=" + e.getMessage());
}
}
}
import java.util.*;
class Test
{
public static void main(String [] args )
{
Test t = new Test();
t.doIt();
}
public void doIt()
{
//Singleton s = new Singleton(); //This won't work as the constructor is private
Singleton s2 = Singleton.getInstance("First"); // Prints "First"
System.out.println(" String is = " + s2.s);
Singleton s3 = Singleton.getInstance("Second"); // Will not print "Second"
System.out.println(" String is = " + s3.s);
}
}
......................................
class Singleton
{
static Singleton instance = null;
static String s;
// To instatiate new Singleton's other class's must call this getInstance() method.
public static Singleton getInstance(String sIn)
{
if ( instance == null) instance = new Singleton(sIn);
return instance;
}
private Singleton(String sIn) // Make constructor private so that only this class can instantiate itself
{
this.s = sIn;
System.out.println("Singleton's Constructor was called. String set to " + s );
}
}