Character CLDC 1.0, MIDP 1.0 java.lang Character provides (Apache web server)

December 21st, 2007

Character CLDC 1.0, MIDP 1.0 java.lang Character provides an object wrapper for a Java char primitive. The constructor initializes the wrapper with a char value, after which the object is immutable. The value associated with a Character object can be retrieved using the charValue() method. The Character class contains several static methods that are useful for handling characters without making any assumptions about the locale in which an application is executing. The digit() method returns the integer value of a character provided that it represents a digit in a given number base, or -1 if it does not. Use the isDigit() method to test whether a given character represents a numeric digit in a given number base. The isUpperCase() and isLowerCase() methods return true if the primitive char passed to them is an upper-case or lower-case letter, respectively, while toUpperCase() and toLowerCase() convert a char to upper- or lower-case and return the result, or the original char if it has no upper- or lowercase equivalent. The static variables Character.MIN_VALUE and Character.MAX_VALUE are char (not Character) values that represent the smallest and largest values that can be held in a char primitive. public final class Character { // Public Constructors public Character( char value); // Public Constants public static final int MAX_RADIX; // =36 public static final char MAX_VALUE; // =’uFFFF’ public static final int MIN_RADIX; // =2 public static final char MIN_VALUE; // =’ ‘ // Public Class Methods public static int digit( char ch, int radix); public static boolean isDigit( char ch); public static boolean isLowerCase( char ch); public static boolean isUpperCase( char ch); public static char toLowerCase( char ch); public static char toUpperCase( char ch); // Public Instance Methods public char charValue(); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); public String toString(); } #BREAK# Class CLDC 1.0, MIDP 1.0 java.lang This class contains information representing a Java class or interface. Only one instance of this object exists for each class loaded within the Java virtual machine, no matter how many instances of that class are created. The Class object for a class can be obtained by using the getClass() method of any instance of that class, or by calling the static Class forName() method and supplying the fully-qualified class name. For example, the expression Class.forName(”java.lang.Class”) would return a Class object for Class itself. A Class object can be used to discover various attributes of a class. The getName() method returns the fully-qualified name of the class (e.g., java.lang.Class). The isArray() method returns true if the class represents an array, such as the one returned by the expression new Object[0].getClass(). The isInterface() returns true if the Class object to which it is applied represents an interface. The isAssignableFrom() and isInstance() methods can be used to determine the relationship between one class or interface and another. The isInstance() method returns true if the object passed as its argument is of the same class as the Class object, or an instance of a subclass. If the Class object represents an interface, then the object passed as the argument to isInstance() must implement that interface or one of its subinterfaces. The isAssignableFrom() method also takes a Class object as its argument and returns true if that object could be assigned to a varable of the type of Class to which it is applied. The newInstance() method constructs a new instance of the Class to which it is applied using its no-argument constructor. An exception will occur if the class does not have a no- argument constructor, if the caller does not have access to that constructor, or if the class is abstract or represents an interface. The getResourceAsStream() method returns an InputStream that can be used to read the content of a resource whose name is supplied as its argument. This method is typically used to access images or text files that are included in the same JAR file as a MIDlet or a package Java application. The resource name must be either an absolute name beginning with the “/” character (e.g., “/com/acme/MIDlets/resources/icon.png”), or a name that is resolved relative to the package of the Class object, such as “resources/icon.png”. The latter would correspond to the same resource if the Class object on which it is invoked is for a class or interface in the com.acme.MIDlets package. public final class Class { // No Constructor // Public Class Methods public static Class forName( // native String className) throws ClassNotFoundException; // Public Instance Methods public String getName(); // native #BREAK# public java.io.InputStream getResourceAsStream( String name); public boolean isArray(); // native public boolean isAssignableFrom( Class cls); // native public boolean isInstance( Object obj); // native public boolean isInterface(); // native public Object newInstance( // native ) throws InstantiationException, IllegalAccessException; // Public Methods Overriding Object public String toString(); } Passed To Class.isAssignableFrom() Returned By Class.forName(), Object.getClass() ClassCastException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals an attempt to cast an object to a type that it is not an instance of, or an attempt to cast an object to an interface that it does not implement. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class ClassCastException extends RuntimeException { // Public Constructors public ClassCastException(); public ClassCastException( String s); } ClassNotFoundException CLDC 1.0, MIDP 1.0 java.lang checked This exception signals that the class named by the argument of the Class forName() method was not found. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class ClassNotFoundException extends Exception { // Public Constructors public ClassNotFoundException(); public ClassNotFoundException( String s); } #BREAK# Thrown By Class.forName() Error CLDC 1.0, MIDP 1.0 java.lang error Error is a subclass of Throwable. It is the base class for exceptions that are not likely to be recoverable by application code, but also do not represent programming errors (and hence are not derived from RuntimeException). Methods that might throw Errors are not required to indicate that fact by including a throws declaration. In the same manner, code that calls such a method is not required to catch the Error. The number of Error subclasses defined by CLDC is much less than the number that exist in J2SE, primarily because the cause of most errors on this platform is device-specific and therefore not susceptible to common handling by platform-independent code. Errors that are reported as such in J2SE are often regarded as terminal conditions that should halt the execution of the virtual machine in CLDC. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class Error extends Throwable { // Public Constructors public Error(); public Error( String s); } Subclasses VirtualMachineError Exception CLDC 1.0, MIDP 1.0 java.lang checked Exception is the base class for Java language exceptions. Exceptions represent non-fatal error conditions that applications may be able to recover from. Exception is derived from the Throwable class, which is also the parent of Error. However, exceptions derived from Error differ from those derived from Exception in that they represent conditions from which application code would not usually be expected to recover. Methods that throw Exceptions are required to include a throws clause in their declarations, except under one condition: methods are not obliged to declare any exceptions that derive #BREAK# from the RuntimeException class. These types of exceptions typically indicate a programming error that cannot be recovered from. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class Exception extends Throwable { // Public Constructors public Exception(); public Exception( String s); } Subclasses java.io.IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InterruptedException, RuntimeException, javax.microedition.midlet.MIDletStateChangeException, javax.microedition.rms.RecordStoreException IllegalAccessException CLDC 1.0, MIDP 1.0 java.lang checked This exception signals that a class has attempted to perform an operation on an object which it does not have access. This typically occurs when an attempt is made to create an instance of a class using the Class newInstance() method and the executing code does not have access to the no-argument constructor, even though it has access to the class itself. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class IllegalAccessException extends Exception { // Public Constructors public IllegalAccessException(); public IllegalAccessException( String s); } Thrown By Class.newInstance() IllegalArgumentException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals that a method has been passed an argument whose value does not meet certain conditions. This exception is often thrown to signal that a null reference has been #BREAK# passed to a method that expects a non-null argument. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class IllegalArgumentException extends RuntimeException { // Public Constructors public IllegalArgumentException(); public IllegalArgumentException( String s); } Subclasses IllegalThreadStateException, NumberFormatException IllegalMonitorStateException CLDC 1.0, MIDP 1.0 java.lang unchecked This is an exception that signals one of the following conditions: A thread has called the Object wait() method on a object for which it does not hold the monitor. A thread has called the Object notify() or notifyAll() method on a object for which it does not hold the monitor. The monitor for an object obj is acquired either by synchronizing on that object using the synchronized (obj) expression, or by entering a non-static method of that object’s class that is declared using the synchronized keyword. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class IllegalMonitorStateException extends RuntimeException { // Public Constructors public IllegalMonitorStateException(); public IllegalMonitorStateException( String s); } IllegalStateException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception is thrown to indicate that a method has been invoked under inappropriate circumstances. For example, a method may throw this exception to indicate that it expected the caller to first set the parameters that it requires to complete its operation. This class is the same as its J2SE equivalent, apart from its inability to be serialized. #BREAK# public class IllegalStateException extends RuntimeException { // Public Constructors public IllegalStateException(); public IllegalStateException( String s); } IllegalThreadStateException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception is thrown when an operation is performed on a Thread that is not in the proper state. In J2SE, there are several circumstances in which this exception is thrown. In CLDC, however, most of these are not possible because the Thread operations that throw this exception simply do not exist. The only cause for this exception in CLDC is calling the start() method on a Thread that has already been started. This class is the same as its J2SE equivalent, apart from its inability to be serialized. { // Public Constructors public IllegalThreadStateException(); public IllegalThreadStateException( String s); } IndexOutOfBoundsException CLDC 1.0, MIDP 1.0 public class IllegalThreadStateException extends IllegalArgumentException java.lang unchecked This exception indicates that an operation used an index value that was invalid for the given data. J2SE provides two subclasses of IndexOutOfBoundsException that are commonly used with arrays and strings: ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class IndexOutOfBoundsException extends RuntimeException { // Public Constructors public IndexOutOfBoundsException(); public IndexOutOfBoundsException( String s); } Subclasses ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException #BREAK# InstantiationException CLDC 1.0, MIDP 1.0 java.lang checked This exception is thrown when the Class newInstance() method is used to either create an instance of a class that represents an array, or cannot be instantiated because it is an interface or is declared to be abstract. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class InstantiationException extends Exception { // Public Constructors public InstantiationException(); public InstantiationException( String s); } Thrown By Class.newInstance() Integer CLDC 1.0, MIDP 1.0 java.lang Integer provides an object wrapper for a Java int primitive value. The constructor initializes the wrapper with an int value, after which the object is immutable. The value associated with an Integer object can be retrieved as a byte, short, int or long using the byteValue(), shortValue(), intValue() and longValue() methods, respectively. If the value is too large to fit into a byte or short, the high-order bits of the integer are truncated. The static parseInt() converts a numeric value held in a String into a primitive int. The single-argument variant of this method assumes that the string is encoded in base 10; the two- argument variant can be used to specify a different number base if necessary. A NumberFormatException is thrown if the String does not represent a valid number in the given number base. There are also two static valueOf methods that parse a string and return an Integer object– one assumes that the String is a base 10 number, the other accepts a number base argument. The zero-argument toString() method returns a String representation of the value of the Integer encoded as a base 10 number. There is also a static variant of this method that prints the value of a given int as a base 10 number, as well as a two-argument variant that prints a value using digits from the number base supplied as its second argument. The static toHexString(), toOctalString and toBinaryString() methods return a String that represents the value of a given int as a number in base 16, 8 and 2 respectively. #BREAK# The static variables Integer.MIN_VALUE and Integer.MAX_VALUE are int (not Integer) values that represent the smallest and largest values that can be held in a int primitive. Note that this class is derived from Object and not Number, as the CLDC does not provide the Number class. public final class Integer { // Public Constructors public Integer( int value); // Public Constants public static final int MAX_VALUE; public static final int MIN_VALUE; // Public Class Methods public static int parseInt( String s) throws NumberFormatException; public static int parseInt(String s, int radix) throws NumberFormatException; public static String toBinaryString( int i); public static String toHexString( int i); public static String toOctalString( int i); public static String toString( int i); public static String toString( int i, int radix); public static Integer valueOf( String s) throws NumberFormatException; public static Integer valueOf(String s, int radix) throws NumberFormatException; // Public Instance Methods public byte byteValue(); public int intValue(); public long longValue(); public short shortValue(); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); public String toString(); } // =2147483647// =-2147483648 Returned By Integer.valueOf() InterruptedException CLDC 1.0, MIDP 1.0 java.lang checked In J2SE, this exception is thrown when one thread uses the interrupt() method to interrupt another thread that is blocked due to the Thread sleep() or join() methods. In CLDC, however, the Thread interrupt() method does not exist, so this exception will not actually be thrown in these cases. However, for reasons of compatibility, this exception is still declared to be thrown from the Object wait() and the Thread sleep() and join() methods. #BREAK# The actual use of this exception is in the implementation of the socket support for the Generic Connection Framework, which is not a required part of the specification and is not visible to application code. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class InterruptedException extends Exception { // Public Constructors public InterruptedException(); public InterruptedException( String s); } Thrown By Object.wait(), Thread.{join(), sleep()} Long CLDC 1.0, MIDP 1.0 java.lang Long provides an object wrapper for a Java long primitive. The constructor initializes the wrapper with a long value, after which the object is immutable. The value associated with a Long object can be retrieved using the longValue() method. The static parseLong() converts a numeric value held in a String into a primitive long. The single-argument variant of this method assumes that the String is encoded in base 10; the two-argument variant can be used to specify a different number base if necessary. A NumberFormatException is thrown if the String does not represent a valid number in the given number base. The zero-argument toString() method returns a String representation of the value of the Long encoded as a base 10 number. There is also a static variant of this method that prints the value of a given long as a base 10 number, as well as a two-argument variant that prints a value using digits from the number base supplied as its second argument. The static variables Long.MIN_VALUE and Long.MAX_VALUE are long (not Long) values representing the smallest and largest values, respectively, that can be held in a long primitive. Note that this class is derived from Object and not Number, as it is in the J2SE. This is because the CLDC does not provide the Number class. public final class Long { // Public Constructors public Long( long value); // Public Constants public static final long MAX_VALUE; // =9223372036854775807 public static final long MIN_VALUE; // =-9223372036854775808 #BREAK# // Public Class Methods public static long parseLong( String s) throws NumberFormatException; public static long parseLong(String s, int radix) throws NumberFormatException; public static String toString( long i); public static String toString( long i, int radix); // Public Instance Methods public long longValue(); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); public String toString(); } Math CLDC 1.0, MIDP 1.0 java.lang The CLDC Math class is an extremely small subset of its J2SE counterpart, providing utility methods that work with int and long values. Most of the J2SE methods cannot be included because a CLDC VM does not provide for floating point arithmetic. The abs() methods return the absolute value of an int or long pased as its argument. The max() method returns the larger of two ints or longs, while min() returns the smaller. public final class Math { // No Constructor // Public Class Methods public static int abs( int a); // strictfp public static long abs( long a); // strictfp public static int max( int a, int b); // strictfp public static long max( long a, long b); // strictfp public static int min( int a, int b); // strictfp public static long min( long a, long b); // strictfp } NegativeArraySizeException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals that an attempt has been made to create an array with a negative number of elements. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class NegativeArraySizeException extends RuntimeException { // Public Constructors public NegativeArraySizeException(); public NegativeArraySizeException( String s); } #BREAK# NullPointerException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception is thrown when an application attempts to use a null object reference. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class NullPointerException extends RuntimeException { // Public Constructors public NullPointerException(); public NullPointerException( String s); } NumberFormatException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals that an attempt has been made to convert a String to a numeric type when the String contains a sequence of characters that does not form a valid number. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class NumberFormatException extends IllegalArgumentException { // Public Constructors public NumberFormatException(); public NumberFormatException( String s); } Thrown By Byte.parseByte(), Integer.{parseInt(), valueOf()}, Long.parseLong(), Short.parseShort() Object CLDC 1.0, MIDP 1.0 java.lang This class that represent a Java object. Object is an ancestor of every Java class. Therefore, a variable of type Object can be safely assigned a reference to any Java object, array, or interface type without casting. In addition, the methods of this class can be invoked on all objects, arrays, and interface types. The equals() method determines whether the current object is equal to the object passed in. The default case defines two objects as equivalent if they are the same object instance. #BREAK# However, most subclasses override this method and use it to test for byte-to-byte equivalence, instead of testing for the same object instance. getClass() returns a Class object representing the object’s class or interface. hashCode() returns a hash code that can be used as a non-unique hashing key for the object. Note that invoking this method on different objects that are equivalent according to equals() must result in the same value being returned. Also, it is important to point out that two different objects may return the same hash code. Subclasses may override this method to return a hash code more suitable to particular object types. The value returned by the Objectimplementation of this method can always be obtained by calling the System.identityHashCode() method. The wait() method provides a way for a thread to wait for a specific condition to be met. notify() and notifyAll() allow another thread to signal that either one waiter or all waiters should re-evaluate whether that condition has been met. A thread that wishes to wait should first obtain the monitor of an object. This can be done either by entering an instance method of that object that is declared to be synchronized, or by entering a synchronized block on that object and invoking one of its wait() methods. Depending on the variant of wait() that is used, the calling thread will be suspended until another thread notifies the condition or until a given time interval expires. To notify a condition on an object, a thread must obtain the object’s monitor and invoke the object’s notify() or notifyAll() method. If notify() is used, one thread waiting on the object is resumed and returns from its wait(). If notifyAll() is used, it resumes all waiting threads. Note that the CLDC Object class does not include the J2SE clone() and finalize methods. This is because cloning and finalization are not supported by a CLDC virtual machine. public class Object { // Public Constructors public Object(); // Public Instance Methods public boolean equals( Object obj); public final Class getClass(); public int hashCode(); public final void notify(); public final void notifyAll(); public String toString(); public final void wait() throws InterruptedException; public final void wait( long timeout) throws InterruptedException; public final void wait(long timeout, int nanos) throws InterruptedException; } // empty // native// native// native// native// nativeSubclasses Too many classes to list. Passed To Too many methods to list. #BREAK# Returned By Class.newInstance(), java.util.Enumeration.nextElement(), java.util.Hashtable.{get(), put(), remove()}, java.util.Stack.{peek(), pop(), push()}, java.util.Vector.{elementAt(), firstElement(), lastElement()} Type Of java.io.Reader.lock, java.io.Writer.lock, java.util.Vector.elementData OutOfMemoryError CLDC 1.0, MIDP 1.0 java.lang error An OutOfMemoryError is thrown when an allocation of memory has been attempted, either in Java code or native code, and both the VM and the garbage collector cannot satisfy the request. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class OutOfMemoryError extends VirtualMachineError { // Public Constructors public OutOfMemoryError(); public OutOfMemoryError( String s); } Runnable CLDC 1.0, MIDP 1.0 java.lang runnable This interface is implemented by a class containing code that is to be run either in a thread of its own or with a TimerTask. The code to be scheduled should be implemented in the run() method. public interface Runnable { // Public Instance Methods public abstract void run(); } Implementations Thread, java.util.TimerTask Passed To Thread.Thread(), javax.microedition.lcdui.Display.callSerially() #BREAK# Runtime CLDC 1.0, MIDP 1.0 java.lang The Runtime class contains methods and variables that provide access to low-level facilities provided by the Java virtual machine. In order to access these facilities, application code must first use the static getRuntime() method to obtain an instance of the Runtime class. The CLDC version of this class contains only a small subset of the functionality of its J2SE counterpart. The exit() method causes the virtual machine to terminate. A CLDC application is permitted to use this method. However, a MIDlet will receive a SecurityException if it attempts to do so. The gc() method hints to the garbage collector that it should attempt to reclaim unreferenced memory. Garbage collectors implemented in small-footprint virtual machines (e,g, the KVM) are typically quite agressive at cleaning up unused memory, so the programmer should not have to call this method very often. The totalMemory() method returns the total amount of memory, in bytes, occupied by the Java virtual machine. In some environments, demand for more memory can cause this value to increase as the VM uses extra system resources. The freeMemory() method returns a value that indicates approximately how much of the total memory occupied by the Java VM is free for allocation to new objects. public class Runtime { // No Constructor // Public Class Methods public static Runtime getRuntime(); // Public Instance Methods public void exit( int status); public long freeMemory(); // native public void gc(); // native public long totalMemory(); // native } Returned By Runtime.getRuntime() RuntimeException CLDC 1.0, MIDP 1.0 java.lang unchecked A base class for Exception subclasses that need not be be declared in the throws clause of a method definition and, consequently, application code need not catch. Exceptions of this type are generally caused by programming errors and need to be addressed during application development, rather than attempting recovery at run time. This class is the same as its J2SE equivalent, apart from its inability to be serialized. #BREAK# public class RuntimeException extends Exception { // Public Constructors public RuntimeException(); public RuntimeException( String s); } Subclasses ArithmeticException, ArrayStoreException, ClassCastException, IllegalArgumentException, IllegalMonitorStateException, IllegalStateException, IndexOutOfBoundsException, NegativeArraySizeException, NullPointerException, SecurityException, java.util.EmptyStackException, java.util.NoSuchElementException SecurityException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals that a run time security check has been violated. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class SecurityException extends RuntimeException { // Public Constructors public SecurityException(); public SecurityException( String s); } Short CLDC 1.0, MIDP 1.0 java.lang Short provides an object wrapper for a Java short primitive. The constructor initializes the wrapper with a short value, after which the object becomes immutable. The value associated with a Short object can be retrieved using the shortValue() method. The static parseShort() converts a numeric value held in a String into a primitive short. The single-argument variant of this method assumes that the String is encoded in base 10; the two-argument variant can be used to specify a different number base if necessary. A NumberFormatException is thrown if the String does not represent a valid number in the given number base. The static variables Short.MIN_VALUE and Short.MAX_VALUE are short (not Short) values that represent the smallest and largest values, respectively, that can be held in a short primitive. #BREAK# Note that this class is derived from Object and not Number. This is because CLDC does not provide the Number class. public final class Short { // Public Constructors public Short( short value); // Public Constants public static final short MAX_VALUE; public static final short MIN_VALUE; // Public Class Methods public static short parseShort( String s) throws NumberFormatException; public static short parseShort(String s, int radix) throws NumberFormatException; // Public Instance Methods public short shortValue(); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); public String toString(); } // =32767// =-32768 String CLDC 1.0, MIDP 1.0 java.lang This class represents a immutable character string. Operations on String objects that change their content actually place their results in other String objects. When concatenating strings or changing the values of characters within a string, it is more efficient to use a StringBuffer instead. The CLDC String class is similar to its J2SE equivalent, but lacks the following methods: compareToIgnoreCase(), copyValueOf(), equalsIgnoreCase() and intern(). It also does not contain the variants of lastIndexOf() that accept a String- valued argument, or the valueOf() methods for types float and double. A String can be constructed as a copy of another String, from the content of a StringBuffer, or from an array of characters or bytes. When constructing a String from bytes, the appropriate character encoding must be used; if an encoding is not specified, the platform’s default encoding is assumed. A String can also be created by applying the static valueOf() methods to a boolean, a char, an array of characters (char[]), an int, a long or an arbitrary Java Object. With an Object, the String is created using the return value of the object’s toString() method. The toCharArray() method returns an array of chars initialized with the content of the String. The getChars() method is similar, but requires the caller to allocate the destination array and can be used to extract a subset of the string. The getBytes() methods copy a subset of the String into a pre-allocated byte array, using either a specified encoding or the platform’s default encoding. The charAt() method can be used to retrieve the value of a single character whose location is specified by a zero-based index. The length of the String, in characters, can be obtained using the length() method. #BREAK# There are several methods that can be used to compare strings or search the content of a string. The compareTo() method performs a comparison of one string with another; it returns 0 if they are equal, or a negative or positive value depending on whether the source string is lexicographically less than or greater than the string passed as an argument. The startsWith() and endsWith() method determine whether a string starts or ends with a sequence of characters represented by a second string, while the regionMatches() method determines whether a region of the string matches a given region (of the same length) of another string. The indexOf() method looks for either an individual character or a substring. It returns the offset at which the match was found, or -1 if there was no match, and the search may start either at the beginning of the String or from any specified index within it. The lastIndexOf() method is similar but returns the index of the last match for a given character, searching back either from the end of the string or from a given offset. Note that unlike indexOf(), there is no variant of lastIndexOf() that accepts a string-valued argument. The replace() method returns a new String object in which all occurrences of one character have been replaced by a second character. The substring() methods return a new String created from a given range of characters from the String to which it is applied. The toUpperCase() and toLowerCase() methods create a new String in which the characters of the original have been converted to upper- or lower-case respectively (characters that are not case-dependent are left unchanged.) The trim() method returns a new String formed by removing all leading and trailing white space from the String to which it is applied. public final class String { // Public Constructors public String(); public String( byte[] bytes); public String( String value); public String( char[] value); public String( StringBuffer buffer); public String(byte[] bytes, String enc) throws java.io.UnsupportedEncodingException; public String( byte[] bytes, int off, int len); public String(char[] value, int offset, int count); public String(byte[] bytes, int off, int len, String enc) throws java.io.UnsupportedEncodingException; // Public Class Methods public static String valueOf( char c); public static String valueOf( int i); public static String valueOf( long l); public static String valueOf( boolean b); public static String valueOf( Object obj); public static String valueOf( char[] data); public static String valueOf(char[] data, int offset, int count); // Public Instance Methods public char charAt( int index); // native public int compareTo( String anotherString); public String concat( String str); public boolean endsWith( String suffix); public byte[] getBytes(); #BREAK# public byte[] getBytes( String enc) throws java.io.UnsupportedEncodingException; public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin); public int indexOf( int ch); // native public int indexOf( String str); public int indexOf( int ch, int fromIndex); // native public int indexOf( String str, int fromIndex); public int lastIndexOf( int ch); public int lastIndexOf( int ch, int fromIndex); public int length(); public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len); public String replace( char oldChar, char newChar); public boolean startsWith( String prefix); public boolean startsWith( String prefix, int toffset); public String substring( int beginIndex); public String substring( int beginIndex, int endIndex); public char[] toCharArray(); public String toLowerCase(); public String toUpperCase(); public String trim(); // Public Methods Overriding Object public boolean equals( Object anObject); // native public int hashCode(); public String toString(); } Passed To Too many methods to list. Returned By Too many methods to list. Type Of javax.microedition.io.HttpConnection.{GET, HEAD, POST} StringBuffer CLDC 1.0, MIDP 1.0 java.lang A StringBuffer is an array of characters that can be expanded or contracted as necessary. StringBuffers are typically used to construct an array of characters that is then converted into an immutable String. The characters that make up the content of a StringBuffer are held in an internal array. The number of entries in the array is referred to as the capacity of the StringBuffer, while the actual number of characters in use is referred to as its size. A StringBuffer is constructed with a specific initial capacity (the default is 16 characters). It can also be constructed from #BREAK# the content of a String, in which case an appropriate initial capacity is determined. When the size approaches the capacity, a new character array is allocated and the existing characters are copied into it. Note that this can be a costly operation that may have to be repeated if the StringBuffer’s size grows continuously. If possible, the StringBuffer should be created with sufficient capacity to hold all of the characters that it will contain. Following construction, the ensureCapacity() method is used to ensure that the internal array can hold at least the number of characters specified without needing to be expanded any further. capacity() returns the current capacity of the StringBuffer, while length() returns its actual size. The actual number of characters in use can be changed by calling the setLength() method. If the new length is smaller than the old length, the characters at the end are lost. If it is larger, null characters are appended. A common use of a StringBuffer is to concatenate several Strings. This can be achieved by using one of the overloaded append() methods, which accept arguments of type boolean, char, char[], int, long, Object and String. These methods convert the target data value to character form and add its content to the end of the internal array. Each of these methods returns a reference to the StringBuffer itself, so that the programmer can chain commands together (e.g., sb.append(”x = “).append(x)). The toString() method is used to convert the characters in a StringBuffer into an immutable String. It is also possible to insert content into a StringBuffer using one of the insert() methods, which has the same variants as the append() methods. These methods insert characters before the position given by the specified index, shifting all characters that follow to higher indices. As with append(), these methods also return a reference to the StringBuffer to allow command chaining. The value of a single character can be changed using the setCharAt() method; this method supplies the new character value and the index of the character to replace. Characters can be removed from the StringBuffer using the delete() and deleteCharAt() methods. Finally, the content of the internal array can be reversed efficiently by calling reverse(). Apart from toString(), there are two ways to extract characters from a StringBuffer. To get the value of a single character, invoke the charAt() method with the index of the required character in the internal array. To get a range of characters in the form of a String, use one of the two variants of substring(). public final class StringBuffer { // Public Constructors public StringBuffer(); public StringBuffer( String str); public StringBuffer( int length); // Public Instance Methods public StringBuffer append( char[] str); // synchronized public StringBuffer append( String str); // native synchronized public StringBuffer append( Object obj); // synchronized public StringBuffer append( boolean b); public StringBuffer append( long l); public StringBuffer append( int i); // native public StringBuffer append( char c); // synchronized public StringBuffer append(char[] str, int offset, // synchronized int len); public int capacity(); #BREAK# public char charAt( int index); // synchronized public StringBuffer delete( int start, int end); // synchronized public StringBuffer deleteCharAt( int index); // synchronized public void ensureCapacity( int minimumCapacity); // synchronized public void getChars(int srcBegin, int srcEnd, // synchronized char[] dst, int dstBegin); public StringBuffer insert( int offset, int i); public StringBuffer insert( int offset, Object obj); // synchronized public StringBuffer insert( int offset, long l); public StringBuffer insert( int offset, boolean b); public StringBuffer insert( int offset, char c); // synchronized public StringBuffer insert(int offset, // synchronized char[] str); public StringBuffer insert( int offset, String str); // synchronized public int length(); public StringBuffer reverse(); // synchronized public void setCharAt( int index, char ch); // synchronized public void setLength( int newLength); // synchronized // Public Methods Overriding Object public String toString(); // native } Passed To String.String() Returned By Too many methods to list. StringIndexOutOfBoundsException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception is thrown when an operation is attempted on a String or StringBufferobject involving an index that is either negative or too large. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { // Public Constructors public StringIndexOutOfBoundsException(); public StringIndexOutOfBoundsException( int index); public StringIndexOutOfBoundsException( String s); } #BREAK# System CLDC 1.0, MIDP 1.0 java.lang The System class contains static methods and variables that provide access to low-level facilities. The CLDC version of this class contains only a small subset of the functionality of its J2SE counterpart. The public static variables out and err are PrintStream objects that can be used for standard output and error output. With J2ME, these streams are useful when running code in an emulated environment, where they typically result in the creation of log files. Note that there is no in variable as there is no standard input stream for a CLDC device. The currentTimeMillis() method returns the current time as a millisecond offset from 0:00 UTC on January 1st, 1970. This is the same representation used by the java.util.Date and java.util.Calendar classes. The exit() method causes the virtual machine to terminate. A CLDC application is permitted to invoke this method. However, a MIDlet will receive a SecurityException if it attempts to do so. The gc() method hints to the garbage collector that it should attempt to reclaim unreferenced memory. Note that the garbage collectors implemented in the small-footprint virtual machines (such as the KVM) are aggressive at cleaning up unused memory, so this method should not need to called very often. The identityHashCode() method returns a system-defined hash code for the object passed as its argument. This method returns the same value as the hashCode() method in the Objectclass would for the same object. It is provided as a convienence because many classes override the hashCode() method to return a different hash code. The arraycopy() method provides an efficient means of copying a portion of an array of objects into a separate array. The source and destination arrays may be the same. In addition, the source and target ranges may overlap. The getProperty() method returns the value of a named system property. CLDC does not provide any means to retrieve the complete list of available properties. Instead, an application must know beforehand the names of the properties that it accesses. The properties defined by CLDC are listed in Chapter 2; those for MIDP are listed in Chapter 3. public final class System { // No Constructor // Public Constants public static final java.io.PrintStream err; public static final java.io.PrintStream out; // Public Class Methods public static void arraycopy(Object src, int src_position, // native Object dst, int dst_position, int length); public static long currentTimeMillis(); // native public static void exit( int status); public static void gc(); #BREAK# public static String getProperty( String key); public static int identityHashCode( Object x); // native } Thread CLDC 1.0, MIDP 1.0 java.lang runnable A class that represents a thread of execution in the Java virtual machine. Each thread has its own call stack and its own copy of local variables created by the Java methods that it executes. An application may create a new thread of execution by instantiating a subclass of Thread and overriding the run() method, or by implementing a Runnable interface and passing its reference to the Thread constructor. A new thread is created in an inactive state. To begin execution, its start() method must be invoked. The total number of threads in existence can be obtained by calling the static activeCount() method. Once a thread is running, it continues to do so until the run() of the Thread subclass terminates, or the Runnable returns control to its caller. Note that even though its thread of execution has ended, a Thread object continues to exist until all references to it have been released and the object is removed by the garbage collector. The isAlive() method can be used to determine whether a Thread object still has an active thread of execution. Unlike J2SE, the CLDC Thread class does not provide the stop(), suspend() and resume() methods. However, there are two Thread methods that allow a thread to suspend its own execution. The static sleep() method suspends the thread for a fixed period of time specified in milliseconds. The thread will be scheduled for resumption when the delay period expires, but may not resume immediately if another thread is currently running. The join() method forces the current thread to block until the passed-in Thread thread terminates. Both sleep() and join() can throw an InterruptedException in the event of an interruption. (In practice, this is not likely to happen because the CLDC Thread does not include the J2SE interrupt() method.) The yield() method allows a thread to temporarily yield control to other threads that are waiting to run. Each thread has an execution priority that may be used when determining which thread should be chosen for execution. The setPriority() can be used to set a thread’s priority and the getPriority() method used to retrieve it. Three standard priority levels (MIN_PRIORITY, NORM_PRIORITY and MAX_PRIORITY) are defined. Only priorities in the range of MIN_PRIORITY to MAX_PRIORITY inclusive are valid. Threads with higher priority that are ready to run are chosen in preference over those with lower priority. The algorithm used to choose between threads that have the same priority is not defined and therefore may be platform- and VM-dependent. The static currentThread() is used to obtain a reference to the Thread that is currently executing. This method can be used to allow a thread to perform operations on itself. #BREAK# public class Thread implements Runnable { // Public Constructors public Thread(); public Thread( Runnable target); // Public Constants public static final int MAX_PRIORITY; // =10 public static final int MIN_PRIORITY; // =1 public static final int NORM_PRIORITY; // =5 // Public Class Methods public static int activeCount(); // native public static Thread currentThread(); // native public static void sleep( // native long millis) throws InterruptedException; public static void yield(); // native // Public Instance Methods public final int getPriority(); // default:5 public final boolean isAlive(); // native default:false public final void join() throws InterruptedException; public final void setPriority( int newPriority); public void start(); // native synchronized // Methods Implementing Runnable public void run(); // Public Methods Overriding Object public String toString(); } Returned By Thread.currentThread() Throwable CLDC 1.0, MIDP 1.0 java.lang Throwable is the base class from which all Java exception types are derived. Throwable objects may be constructed with an associated message that provides diagnostic information relating to the cause of the exception. The message, if it is set, can be retrieved using the getMessage() method. Throwable has two subclasses that are base classes for different types of exceptions. The Error class and its subclasses describe errors that application code is not expected to recover from. J2SE has a large number of error subclasses; however, the CLDC supports only two of them. The Exception class is the base class for exceptions that an application can recover from. Application code is required to declare any Exceptions that it throws. It must also catch those exceptions thrown by methods that it invokes, apart from RuntimeExceptionand its subclasses. A Throwable contains a stack backtrace that contains the method call stack at the point at which the exception was thrown. The stack trace may be printed using the printStackTrace() method. Unlike J2SE, the CLDC Throwable class does not include a stack trace when it is created and does not provide a fillInStackTrace() method to force #BREAK# the stack trace to be written to it on demand. The CLDC reference implementation virtual machine fills in the stack trace only when the exception is thrown. public class Throwable { // Public Constructors public Throwable(); public Throwable( String message); // Public Instance Methods public String getMessage(); // default:null public void printStackTrace(); // Public Methods Overriding Object public String toString(); } Subclasses Error, Exception VirtualMachineError CLDC 1.0, MIDP 1.0 java.lang error This is an error that indicates that a fatal condition has been detected with the Java virtual machine. In CLDC, this error is never thrown. Instead, it is used only as the parent class of OutOfMemoryError. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public abstract class VirtualMachineError extends Error { // Public Constructors public VirtualMachineError(); public VirtualMachineError( String s); } Subclasses OutOfMemoryError #BREAK# Chapter 13. java.util Package java.util CLDC 1.0, MIDP 1.0 The java.util package, whose class hierarchy is shown in Figure 13-1, contains several utility classes that are of general use, but not central enough to the Java language to be included in the java.lang package. The Java 2 version 1.3 java.util package contains 54 classes and interfaces. By contrast, the CLDC version contains only 10 classes; MIDP adds another two for timer handling. As a result, these platforms have drastically reduced support for collections and internationalization. The CDC platform provides a much more complete implementation of this package, leaving out only 7 classes, and the Foundation Profile requires that all of the J2SE classes and interfaces be present. As with the other packages in this reference section, we won’t address the CDC and Foundation Profile versions here because the classes they contain are identical to those in J2SE. See Java in a Nutshell (O’Reilly) for more information. The collection classes in this package are a subset of those available with JDK 1.1. All vestiges of the Java 2 collections framework have been removed. One consequence of this is that some classes have been reparented. Vector, for example, is derived from Object in CLDC rather than from AbstractList, as it is in J2SE. Other notable changes are the removal of the Properties class as well as the Dictionary class, the latter being the parent of Hashtable. In CLDC, Hashtable remains, but it is derived from Object instead. CLDC retains the J2SE Calendar and Date classes, but with reduced functionality. See the descriptions of these classes in this chapter for more detailed information. The removal of the Cloneable, Comparable and Serializable interfaces from the CLDC java.lang package means that some of the classes in the java.util can no longer implement these interfaces. In practice, this will have little effect since most of the facilities that use these interfaces have also been removed. A possible minor annoyance is that it is no longer possible to compare two Date objects using the compareTo() method as in J2SE. #BREAK# Figure 13-1. The java.util hierarchy Calendar CLDC 1.0, MIDP 1.0 java.util Calendar is an abstract base class for platform-dependent classes that convert between date and time offsets. Since the rules for converting between an absolute UTC time and a date may depend on local conventions, application code does not directly instantiate a subclass of Calendar. Instead, it uses one of the static getInstance() methods, which returns an object that can handle dates using rules appropriate to the device’s default locale. This arrangement allows an application running in a device in a western locale to obtain a Calendar that uses the rules of the Gregorian calendar, while allowing the same application to work with other calendars (such as Japanese Gregorian) in other locales. The proper conversion of a point in time measured in UTC depends on the time zone in which a device is being used. The Calendar object returned by the zero-argument variant of getInstance() performs the proper conversions for the default time zone of the device it is running on. To create a Calendar for a different time zone, obtain a TimeZone object for that time zone and use the variant of getInstance() that accepts a TimeZone argument. Alternatively, any Calendar offset can be set to work in a different time zone by calling the setTimeZone() method. The date and time associated with a Calendar object can be set from a Date object using the setTime() method, or to an absolute time using the setTimeInMillis() method, which requires a millisecond offset from 0:00 UTC on January 1st, 1970. Once the time has been set, the get() method can be used to get various fields of the associated date. The date or time #BREAK# field that is required is specified using one of the constants defined by the Calendar. For example, to get the year associated with a given date, use the expression get(Calendar.YEAR). Constants are also defined that correspond to days of the week and months of the year. To test whether a date falls on a Thursday, use the expression (cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY), or to check whether the date falls in May, use (cal.get(Calendar.MONTH) == Calendar.MAY). The reverse conversion can be performed by using the set() method to change the individual fields of a Calendar and calling the getTime() or getTimeInMillis() method to obtain the corresponding Date or millisecond time offset. The equals(), after() and before() methods can be used to compare the date and time in a Calendar to another object, which must also be of type Calendar. public abstract class Calendar { // Protected Constructors protected Calendar(); // Public Constants public static final int AM; // =0 public static final int AM_PM; // =9 public static final int APRIL; // =3 public static final int AUGUST; // =7 public static final int DATE; // =5 public static final int DAY_OF_MONTH; // =5 public static final int DAY_OF_WEEK; // =7 public static final int DECEMBER; // =11 public static final int FEBRUARY; // =1 public static final int FRIDAY; // =6 public static final int HOUR; // =10 public static final int HOUR_OF_DAY; // =11 public static final int JANUARY; // =0 public static final int JULY; // =6 public static final int JUNE; // =5 public static final int MARCH; // =2 public static final int MAY; // =4 public static final int MILLISECOND; // =14 public static final int MINUTE; // =12 public static final int MONDAY; // =2 public static final int MONTH; // =2 public static final int NOVEMBER; // =10 public static final int OCTOBER; // =9 public static final int PM; // =1 public static final int SATURDAY; // =7 public static final int SECOND; // =13 public static final int SEPTEMBER; // =8 public static final int SUNDAY; // =1 public static final int THURSDAY; // =5 public static final int TUESDAY; // =3 public static final int WEDNESDAY; // =4 public static final int YEAR; // =1 // Public Class Methods public static Calendar getInstance(); // synchronized public static Calendar getInstance( TimeZone zone); // synchronized // Public Instance Methods public boolean after( Object when); public boolean before( Object when); public final int get( int field); #BREAK# public final Date getTime(); public TimeZone getTimeZone(); public final void set( int field, int value); public final void setTime( Date date); public void setTimeZone( TimeZone value); // Public Methods Overriding Object public boolean equals( Object obj); // Protected Instance Methods protected long getTimeInMillis(); protected void setTimeInMillis( long millis); } Returned By Calendar.getInstance() Date CLDC 1.0, MIDP 1.0 java.util The Date class represents a date and time held internally as a millisecond offset from 0:00 UTC on January 1st, 1970. The default constructor creates a Date that represents the date and time at the time of its creation. A Date object for an arbitrary time can be created by passing the appropriate offset to the Date(long offset) constructor. Negative offsets can be used to represent dates in 1969 and earlier years. The time associated with a Date can be changed using the setTime() method and the time offset for a Date can be obtained using getTime(). The CLDC version of Date is much simpler than the J2SE implementation. Deprecated APIs and constructors have been removed, as have methods that allow two Date objects to be compared. A consequence of this is that it is no longer possible to convert between a Date object and the corresponding parts of a date, such as year, month, day, etc. The Calendar class must be used to perform these conversions instead. Note that a Date object always contains a time offset measured relative to UTC. To work in other time zones, an appropriate TimeZone object must be obtained and used together with an instance of the Calendar class. public class Date { // Public Constructors public Date(); public Date( long date); // Public Instance Methods public long getTime(); // default:1010205995686 public void setTime( long time); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); } #BREAK# Passed To Calendar.setTime(), Timer.{schedule(), scheduleAtFixedRate()}, javax.microedition.lcdui.DateField.setDate() Returned By Calendar.getTime(), javax.microedition.lcdui.DateField.getDate() EmptyStackException CLDC 1.0, MIDP 1.0 java.util unchecked This is an exception that is thrown to signal that an attempt has been made to remove or peek at the top element of an empty Stack. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class EmptyStackException extends RuntimeException { // Public Constructors public EmptyStackException(); } Enumeration CLDC 1.0, MIDP 1.0 java.util Enumeration is an interface that provides methods to access an underlying sequence of objects that can be traversed in an implementation-defined order. An Enumeration is often used to traverse the elements of a Vector as an alternative to directly accessing each element by its index. The hasMoreElements() method returns false if the Enumeration is empty or has already returned its last element. The first call to nextElement() returns the first element in the Enumeration, if it is not empty. Each subsequent invocation of this method returns the following element. Calling this method after the last element has been returned results in a NoSuchElementException. The hasMoreElements() is typically called before each use of nextElement() to check whether the end of the sequence has been reached. Note that the values of an Enumeration can be iterated through only once; there is no way to reset it to the beginning. public interface Enumeration { // Public Instance Methods public abstract boolean hasMoreElements(); public abstract Object nextElement(); } #BREAK# Returned By Hashtable.{elements(), keys()}, Vector.elements() Hashtable CLDC 1.0, MIDP 1.0 java.util Hashtable is a collection class in which objects (referred to as values) are stored with associated keys. An entry is added to the Hashtable using the put() method, which takes a key and a value. Both the key and the value can be arbitrary Java objects, but neither may be null. Only one instance of each key may appear in the Hashtable; an attempt to store a second value with the same key will replace the first value. Key equality is determined by using the equals() method. The value associated with a key can be obtained by passing the key to the get() method. If there is no value in the Hashtable with the supplied key, then null is returned. The contains() method can be used to determine whether an entry with a given key exists. The containsKey() method returns true if at least one entry with the supplied value is found in the table. Since only keys are required to be unique, it is possible for the same value (or values that are equal according to their equals() methods) to appear in the table more than once. The size() method returns the number of entries in the Hashtable. However, to determine whether the Hashtable is empty, it is often more convienent to use the isEmpty() method. To remove an entry from the Hashtable, pass its key to the remove() method. If an entry with the given key was found in the table, the remove() method returns its value, implementing a read-and-clear operation. All of the entries in the Hashtable can be deleted by calling the clear() method. To create a loop that accesses all of the values in the Hashtable, use the elements() method, This method returns an Enumeration with one entry for each value in the table. The order in which the values are returned is not defined. To obtain an Enumeration that iterates over all of the keys in the table, use the keys() method. public class Hashtable { // Public Constructors public Hashtable(); public Hashtable( int initialCapacity); // Public Instance Methods public void clear(); // synchronized public boolean contains( Object value); // synchronized public boolean containsKey( Object key); // synchronized public Enumeration elements(); // synchronized public Object get( Object key); // synchronized public boolean isEmpty(); // default:true public Enumeration keys(); // synchronized public Object put( Object key, Object value); // synchronized public Object remove( Object key); // synchronized #BREAK# public int size(); // Public Methods Overriding Object public String toString(); // Protected Instance Methods protected void rehash(); } // synchronized NoSuchElementException CLDC 1.0, MIDP 1.0 java.util unchecked This exception is thrown to signal that an attempt has been made to access an element of a collection or an enumeration that does not exist. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class NoSuchElementException extends RuntimeException { // Public Constructors public NoSuchElementException(); public NoSuchElementException( String s); } Random CLDC 1.0, MIDP 1.0 java.util This class generates pseudo-random numbers based on an initial seed value. The algorithm used is deterministic in that two instances of this class, initialized with the same seed and subject to the same method calls in the same order, will return identical sequences of numbers. Subclasses can implement a different random number generation algorithm by overriding the protected next() method to return a pseudo-random number with the specified number of bits. The nextInt() and nextLong() methods return the next pseudo-random integer and long values, respectively, from the random number sequence of this generator. The default algorithm generates numbers that are approximately evenly distributed over the total range of values for the return type, which implies that there is an almost equal chance that any given bit in the random value will be 0 or 1. The setSeed() can be used to set a new seed value from which subsequent random numbers will be generated. The seed can also be supplied when an instance of this class is created. A Random object constructed with its default constructor is seeded with the current time, expressed as the number of milliseconds since Jan 1st, 1970. The CLDC implementation of this class does not include the J2SE methods for random floating point numbers (the CLDC VM does not support floating point values), nor does it offer the ability to obtain random boolean values and random-valued byte arrays. #BREAK# public class Random { // Public Constructors public Random(); public Random( long seed); // Public Instance Methods public int nextInt(); public long nextLong(); public void setSeed( long seed); // synchronized // Protected Instance Methods protected int next( int bits); // synchronized } Stack CLDC 1.0, MIDP 1.0 java.util A class that represent a last-in, first-out push down stack. Items on the stack can be arbitrary Java objects. The push() method is used to add another item to the top of the stack. The uppermost item on the stack can be removed using the pop() method, which returns the item to the caller. The peek() method returns the uppermost object without removing it from the stack. If either peek() or pop() is called when the stack is empty, an EmptyStackException is thrown. This situation can be detected in advance by checking the empty() method, which returns true when there are no items on the stack. The search() method can be used to determine whether a given object is in the stack. If the object is found, its distance from the top of the stack is returned, where the topmost object is considered to be at distance 1. If the object is not found in the stack, -1 is returned. The Stack class does not provide any methods that allow direct access to any item other than the topmost element . However, the methods of its Vector superclass can be used to access and remove any item on the stack. (This practice is not recommended, however, since it breaks the encapsulation of the data within the stack.) public class Stack extends Vector { // Public Constructors public Stack(); // Public Instance Methods public boolean empty(); public Object peek(); // synchronized public Object pop(); // synchronized public Object push( Object item); public int search( Object o); // synchronized } #BREAK# Timer CLDC 1.0, MIDP 1.0 java.util A class that allows code to be scheduled for execution in the future. A Timer creates a dedicated thread which it uses to execute code in one or more TimerTask objects. These objects are passed to it using its schedule() and scheduleAtFixedRate() methods. To schedule a task to be run once, use one of the two-argument variants of schedule(), passing it either the delay in milliseconds until its only execution, or a Date object holding the required execution time. The three-argument schedule() methods arrange for the task to be run at a given initial time, or after an initial delay and then subsequently executed with a fixed delay between the start times. If task execution is delayed for any reason, the next execution of the same task will also be delayed. Over time, these delays can increase, so this mode of operation is acceptable when the total number of times that the task is run in a given period is not critical (e.g., polling a mail server for undelivered mail). When it is important that tasks be executed with a given average frequency, such as graphics animation, the scheduleAtFixedRate() method should be used instead. This method does not schedule each execution relative to the start time of the previous one. Instead, it attempts to compensate for delays by scheduling the task more often in order to maintain the desired long-term execution frequency. This might mean that the task will occasionally run more often than an identical task scheduled using the schedule() method. Consequently, successive executions might be separated by a smaller time interval than the delay specified in the scheduleAtFixedRate() call. Since all of the TimerTasks associated with a Timer execute in the same thread, a delay caused by one task may result in other tasks not being executed in a timely manner. In a J2SE system, delays of this type may be avoided by assigning tasks to more than one Timer. A CLDC system, however, may not have native thread support in its operating system. Hence, such a strategy may not achieve the desired effect. The cancel() method can be used to cancel all pending task executions and terminate the thread associated with the Timer. A task that is executing when this method is invoked will be allowed to complete. public class Timer { // Public Constructors public Timer(); // Public Instance Methods public void cancel(); public void schedule( TimerTask task, Date time); public void schedule( TimerTask task, long delay); public void schedule(TimerTask task, Date firstTime, long period); #BREAK# public void schedule(TimerTask task, long delay, long period); public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period); public void scheduleAtFixedRate(TimerTask task, long delay, long period); } TimerTask CLDC 1.0, MIDP 1.0 java.util runnable An abstract class that should be subclassed to provide a unit of work. The TimerTask can then be scheduled for execution through the use of the Timer object. Subclasses should place code to be executed by the Timer in the run() method and use either the schedule() or scheduleAtFixedRate() method to arrange for it to be scheduled. Once a task has been scheduled, future execution can be canceled by calling the cancel() method. If the task is executing when this method is called, however, it will be allowed to complete. A task will not be scheduled for execution again once the cancel() method returns. The scheduledExecutionTime() method can be used to get the time at which the task was most recently scheduled for execution, as a millisecond offset from 0:00 UTC on January 1st, 1970. public abstract class TimerTask implements Runnable { // Protected Constructors protected TimerTask(); // Public Instance Methods public boolean cancel(); public long scheduledExecutionTime(); // Methods Implementing Runnable public abstract void run(); } Passed To Timer.{schedule(), scheduleAtFixedRate()} TimeZone CLDC 1.0, MIDP 1.0 java.util A TimeZone object holds information for a specific time zone, such as its offset from GMT and whether it observes daylight savings. The getDefault() method returns the default TimeZone for the device. A list of the time zones that a device supports can be obtained using the static getAvailableIDs() method. A TimeZone object for a specific time zone can be #BREAK# obtained by calling the getTimeZone() method, passing the time zone’s identifier, which must be one of the strings returned by the getAvailableIDs() method. Note that CLDC devices are only required to support their default time zone. Therefore, it may not be possible for application code to obtain a TimeZone object for any other time zone. A TimeZone object contains a fixed time offset from GMT. This value, which is expressed in milliseconds, can be obtained by calling the getRawOffset() method. This value does not take into account daylight savings time. If a time zone uses daylight savings time, which can be determined from the useDaylightTime() method, the actual offset on any given date depends on whether daylight savings time is in force. The offset from GMT adjusted for daylight savings can be obtained from the getOffset() method, which returns the offset in force at a specified date and time. public abstract class TimeZone { // Public Constructors public TimeZone(); // Public Class Methods public static String[] getAvailableIDs(); public static TimeZone getDefault(); // synchronized public static TimeZone getTimeZone( String ID); // synchronized // Public Instance Methods public String getID(); // constant public abstract int getOffset(int era, int year, int month, int day, int dayOfWeek, int millis); public abstract int getRawOffset(); public abstract boolean useDaylightTime(); } Passed To Calendar.{getInstance(), setTimeZone()}, javax.microedition.lcdui.DateField.DateField() Returned By Calendar.getTimeZone(), TimeZone.{getDefault(), getTimeZone()} Vector CLDC 1.0, MIDP 1.0 java.util Vector is a collection class that behaves like a variable-length array of objects. A Vector can contain an arbitrary number of Java objects, accessed with an integer position index. The first entry is index 0. Since an entry in a Vector is distinguished only by its index, the same object can appear any number of times in the same Vector. Entries can be appended to the end of the Vector using the addElement() method. Entries can be inserted at a given index using the insertElementAt() method. The insertElementAt() method causes all elements at that location and higher to be shifted #BREAK# up by one position. An element at a given index can be replaced using the setElementAt() method. Elements can be removed from a Vector by index or by value. The removeElementAt() method removes the element with the given index, while removeElement(Object obj) removes the element with the lowest index that is equivalent to the object passed in. Both of these methods cause the indices of all elements that follow the removed element to be reduced by 1. The removeAllElements() removes all entries from the Vector. There are several ways to access the elements in a Vector. The elementAt() returns the element at the specified index. The convenience methods firstElement() and lastElement() return the first and last elements (which will be the same if the Vector has only one element). The elements() method returns an Enumeration that iterates over all of the elements in the Vector in order of increasing index. Finally, the contents of the Vector can be copied into a pre-allocated array (which must be large enough to hold it) using the copyInto() method. In many cases, it is quicker to use this method than it is to use the Enumeration returned by the elements(). However, the possible performance gain must be weighed against the memory required for the array if the Vector is large. The number of elements in a Vector can be obtained from the size() method. To determine whether a Vector is empty, use the isEmpty() method. The size of a Vector can be explicitly set using the setSize() method. If the value passed to this method is smaller than the current size, elements with indices greater than or equal to the new size are removed. If the new size is larger than the existing size, then slots with indices greater than or equal to the old size are filled with null. A Vector manages its elements using an internal array that is larger than the number of elements that it contains. The size of this array is referred to as the Vector’s capacity and can be retrieved using the capacity() method. As elements are added, the Vector increases its capacity by allocating a new internal array with additional entries and copying the element list from the old array to the new one. The initial capacity and the amount that it increases when necessary can be supplied to the constructor. Since the process of increasing an array’s capacity is expensive, it is a good idea to set the initial capacity so that it is large enough to hold all of the elements that it may contain in its lifetime, if this is known in advance. The same effect can be obtained at run time by calling the ensureCapacity() method, supplying the expected number of Vector elements. The size of the internal array can be reduced to the number required to actually hold its content using the trimToSize() method. Vector provides methods that allow its content to be searched for a given object. The contains() method returns true if the Vector holds an element that is equivalent to its argument. To find the index of an element that matches a given object, use indexOf(), which has two variants. The first searches from the start of the Vector, while the second searches from a specified starting index. The lastIndexOf() methods are similar, but return the index of the last matching element. Each of these methods return -1 if no match is found. public class Vector { // Public Constructors public Vector(); public Vector( int initialCapacity); public Vector(int initialCapacity, int capacityIncrement); #BREAK# // Public Instance Methods public void addElement( Object obj); // synchronized public int capacity(); public boolean contains( Object elem); public void copyInto( Object[] anArray); // synchronized public Object elementAt( int index); // synchronized public Enumeration elements(); // synchronized public void ensureCapacity( int minCapacity); // synchronized public Object firstElement(); // synchronized public int indexOf( Object elem); public int indexOf( Object elem, int index); // synchronized public void insertElementAt( Object obj, int index); // synchronized public boolean isEmpty(); // default:true public Object lastElement(); // synchronized public int lastIndexOf( Object elem); public int lastIndexOf( Object elem, int index); // synchronized public void removeAllElements(); // synchronized public boolean removeElement( Object obj); // synchronized public void removeElementAt( int index); // synchronized public void setElementAt( Object obj, int index); // synchronized public void setSize( int newSize); // synchronized public int size(); public void trimToSize(); // synchronized // Public Methods Overriding Object public String toString(); // synchronized // Protected Instance Fields protected int capacityIncrement; protected int elementCount; protected Object[] elementData; } Subclasses Stack #BREAK# Chapter 14. javax.microedition.io Package CLDC 1.0, MIDP 1.0, CDC javax.microedition.io 1.0 This package contains the interfaces and classes that form the Generic Connection Framework. This framework provides a simpler and more uniform interface for accessing external devices, such as networks and serial communication ports, than the corresponding classes in J2SE. The key elements of this package are the Connector class and the Connection interface. The Connector class contains static methods that create specialized connections (i.e. objects that implement the Connection interface) to various types of device or network protocol. The Connector open() method accepts a name argument that describes the connection target; it then returns an instance of a class that implements a sub-interface of Connection suitable for the specified protocol or device. Note that the actual classes that are returned are not part of the public API, but the interfaces that they implement (e.g., HttpConnection) are all contained in this package. The Generic Connection Framework is part of the CLDC specification. Although it defines the framework and most of the interfaces in this package, it does not require the implementation of any specific protocols. The HttpConnection interface is introduced by the MID profile rather than being part of CLDC. MIDP requires only that the HTTP protocol be supported, although device vendors are free to implements sockets, datagrams and other protocols according to the requirements of their devices. Although intended for CLDC and its associated profiles, this package is also included in the Connected Device Configuration (CDC) and the Foundation Profile, for reasons of compatibility. Figure 14-1 shows the class hierarchy of this package. See Chapter 6 for more details about the Generic Connection Framework. #BREAK# Figure 14-1. The java.microedition.io hierarchy Connection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io Connection is a base interface that represents a generic connection to a device or remote object accessed over a network. This interface defines only a close() method. A class that implements this interface is obtained from the open() method of the Connector class. These connections are already in the open state, so there is no open() method in the Connection interface. public interface Connection { // Public Instance Methods public abstract void close() throws java.io.IOException; } Implementations DatagramConnection, InputConnection, OutputConnection, StreamConnectionNotifier Returned By Connector.open() #BREAK# CLDC 1.0, MIDP 1.0, CDC ConnectionNotFoundException 1.0 javax.microedition.io checked This exception reports an error related to the Generic Connection Framework. It is thrown when the Connector open() method is invoked requesting a protocol that is not supported by the implementation. public class ConnectionNotFoundException extends java.io.IOException { // Public Constructors public ConnectionNotFoundException(); public ConnectionNotFoundException( String s); } Connector CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io The Connector class is a factory that creates Connection objects, which encapsulate a protocol connection with another target device. Note that the communications mechanism that each device supports is implementation-dependent. The CLDC specification does not require any protocols to be supported, and MIDP 1.0 requires only HTTP. The three open() methods create and return a Connection to an entity that is defined by the name argument. The legal values of the name argument and their precise interpretations are implementation-dependent. However, they always take the form of a URL. The most common forms of this argument are: http://host:port/path Creates an HTTP connection to a server at port number port on the given host, to access the resource named by path. Some implementations may also support secure communications using HTTPS, which would use https: as the protocol selector. socket://host:port Creates a socket connection to a server at port number port on the given host. socket://:port Creates a server socket to receive connections addressed to port port on the local host. #BREAK# datagram://host:port Creates a connection to send datagrams to port port on the given host. datagram://:port Creates a connection to receive datagrams addressed to port port on the local host. comm://port;params Opens a serial port on the local host. The params argument may supply optional parameters such as the required baud rate. file://path Opens a file in the filestore of the host system. If the value of the name argument is not recognized or support for the underlying communication mechanism is not provided, the method throws a ConnectionNotFoundException. The mode takes the values READ, WRITE or READ_WRITE and specifies the type of access required to the connection. Some connection types may place restrictions on the values of this argument that they accept. For example, a connection to a printer may not allow read access. If this argument is not specified, the value READ_WRITE is assumed. A timeout argument can be also supplied to the method. By default, this parameter has the value false. When timeouts are requested and supported, a connection timeout causes this method to throw an InterruptedIOException. The type of object returned by the open() method is implementation-dependent. This object, however, always implements an interface derived from Connection that is appropriate for the device or communication protocol being used. For example, if the name argument indicates an HTTP connection, then the returned object will implement the HttpConnection interface. Similarly, sockets return either a StreamConnection or StreamConnectionNotifier object. Datagrams return a DatagramConnection. The openInputStream(), openOutputStream(), openDataInputStream() and openDataOutputStream() methods return I/O streams without returning the underlying Connection object to the caller. The name argument is interpreted in the same way as if it were passed to the open() method. These methods succeed only if the name argument is valid and supported on the local system, and the underlying communication mechanism allows reading or writing (depending on whether an input or output stream is requested). public class Connector { // No Constructor // Public Constants public static final int READ; // =1 public static final int READ_WRITE; // =3 public static final int WRITE; // =2 #BREAK# // Public Class Methods public static Connection open( String name) throws java.io.IOException; public static Connection open(String name, int mode) throws java.io.IOException; public static Connection open(String name, int mode, boolean timeouts) throws java.io.IOException; public static java.io.DataInputStream openDataInputStream( String name) throws java.io.IOException; public static java.io.DataOutputStream openDataOutputStream( String name) throws java.io.IOException; public static java.io.InputStream openInputStream( String name) throws java.io.IOException; public static java.io.OutputStream openOutputStream( String name) throws java.io.IOException; } ContentConnection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io ContentConnection is a StreamConnection whose data is some kind of identifiable object. The type of object depends on the communicating entities and must either be known in advance or be identifiable from the value returned by the getType() method. A ContentConnection may convey one object, or a sequence of objects. The getType() method returns a String that identifies the type of the data in the input stream. In most cases, the object type will be identified by its MIME type, but any arbitrary string that has meaning to both the sender and the receiver can be used. When the connection between sender and receiver is implemented using HTTP, the type is conveyed in the HTTP Content-Type header field. The getLength() method returns the number of bytes that make up the object’s representation in the data stream. This method may return -1 if the protocol used to carry the data does not include a mechanism for conveying the length of the object. In this case, the receiver should continue to read data until an end-of-file indication is received or some characteristic of the data indicates that a complete object has been read. Where a stream may carry several objects in succession, the value returned by this method may be used to mark the boundary between them. When the connection between sender and receiver is implemented using HTTP, the length is conveyed in the HTTP Content-Length header field. The getEncoding() method returns a String that indicates the character set in which the bytes are encoded. This method is useful when the data consists of a sequence of bytes that represent strings that need to be converted into Unicode by the receiver, rather than binary data that needs no conversion. When the connection between sender and receiver is implemented using HTTP, the length is conveyed in the HTTP Content-Encoding header field. #BREAK# public interface ContentConnection extends StreamConnection { // Public Instance Methods public abstract String getEncoding(); public abstract long getLength(); public abstract String getType(); } Implementations HttpConnection Datagram CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io A Datagram represents a message to be sent from a sender to a receiver. A Datagram consists of an arbitrary sequence of bytes together with an address. Datagram objects are created using the newDatagram() method of the DatagramConnection class. When preparing a Datagram for transmission, the data content must be set using the setData() method, which requires the data to be supplied in the form of an array of bytes, where the offset and len arguments specify the portion of the array that is to be used to form the message body. The maximum permitted length of a Datagram can be obtained from the DatagramConnection object. The data length associated with the Datagram can be changed using the setLength() method, but it cannot be increased beyond the end of the buffer supplied by the setData method. The reset() method is used to set the offset and length values to zero. This method is often used when creating the message body using the DataOutput interface methods. A Datagram must have a destination address, which is set using one of the two setAddress() methods. One variant allows the address to be copied from another Datagram, which is a convenient when creating a response to a received Datagram. The other variant accepts a string of the form datagram://host:port, where host is the host name or IP address of the destination and port is the destination’s port number. A Datagram without a destination address to be sent using a DatagramConnection in client mode (see the description of DatagramConnection for more information) will use the DatagramConnection’s address. If the Datagram address is set, however, it temporarily overrides the address associated with the DatagramConnection. When a Datagram is received, the address of the sender can be obtained by calling the getAddress() method. This returns a String encoded in the form datagram://host:port. The message content is obtained by calling the getData(), getLength(), and getOffset() methods. The first of these methods returns an array of bytes, while the other two return the offset of the first byte that contains the message data and the length of that data. (In other words, the first valid data byte is given by dgram.getData()[dgram.getOffset()] and the last valid byte by dgram.getData()[dgram.getOffset() + dgram.getLength() - 1]. #BREAK# For convenience when creating or reading the body of a message, Datagram implements both the DataInput and DataOutput interfaces. This is primarily a convienence when reading or writing to the message body. For example, one way to create a datagram is to use the setData() method to supply the output buffer, passing the offset and length arguments as zero, and then call methods of the DataOutput interface (such as writeInt() or writeUTF()) to store data in the buffer. When these methods are used, the length of the outgoing Datagram is automatically set to match that of the data written to the buffer. The same Datagram can be used to create more than one message by calling the reset() method to empty the buffer after the Datagram has been sent. Similarly, on receiving a Datagram, the DataInput methods (such as readInt() and readUTF()) can be used to extract fields from the message body. These methods automatically update the offset value so that subsequent methods read from the next available byte in the buffer. Note that the reset() method should never be called in this case, as it would have the effect of making the received message appear to be empty. public interface Datagram extends java.io.DataInput, java.io.DataOutput { // Public Instance Methods public abstract String getAddress(); public abstract byte[] getData(); public abstract int getLength(); public abstract int getOffset(); public abstract void reset(); public abstract void setAddress( Datagram reference); public abstract void setAddress( String addr) throws java.io.IOException; public abstract void setData(byte[] buffer, int offset, int len); public abstract void setLength( int len); } Passed To Datagram.setAddress(), DatagramConnection.{receive(), send()} Returned By DatagramConnection.newDatagram() DatagramConnection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io DatagramConnection is a Connection that is used to send Datagram objects to one or more receivers. A datagram is a sequence of bytes that is delivered together in the form of a message. Datagrams are not guaranteed to be delivered. In addition, the order of delivery of successive datagrams does not always match the order in which they were sent. Since a #BREAK# DatagramConnection deals in discrete messages, it does not have any associated input or output streams. A DatagramConnection receiver is obtained by calling the Connector open() method with a name argument of the form datagram://:port, where port is the port number to which senders should address messages. DatagramConnections created in this way can also be used to send Datagrams, often as responses. A DatagramConnection created in this way is said to be in server mode. A DatagramConnection sender is obtained by supplying a name argument of the form datagram://host:port. This type of DatagramConnection is said to be in client mode. The difference between server and client modes is that the port number for server mode is known in advance (and must be known by senders so that they can address messages). In client mode, the port number is dynamically allocated, and it may be different each time the client executes. The client port number will appear in the messages received by the server and can be used to address the reply message. There is currently no direct way for a client to find out the port number that has been allocated to it. Once a DatagramConnection has been obtained, Datagrams can be created by calling one of the newDatagram() methods. There are four variants of this method that either specify or omit the data and the address. If either one is not specified with newDatagram(), they can be supplied later using the setData() and setAddress() methods provided by the Datagraminterface. To send a Datagram, use the send() method. Note that the send() method requires that the destination address in the Datagram has been set. The receive() retrieves a message addressed to the specified DatagramConnection, stores it in the Datagram passed to it, and returns the number of bytes copied. If the buffer associated with the Datagram is not large enough to receive the entire message, the excess bytes are discarded and no error is reported. The address field of the Datagram should represent the host and port number of the message sender. public interface DatagramConnection extends Connection { // Public Instance Methods public abstract int getMaximumLength( ) throws java.io.IOException; public abstract int getNominalLength( ) throws java.io.IOException; public abstract Datagram newDatagram( int size) throws java.io.IOException; public abstract Datagram newDatagram(byte[] buf, int size) throws java.io.IOException; public abstract Datagram newDatagram(int size, String addr) throws java.io.IOException; public abstract Datagram newDatagram(byte[] buf, int size, String addr) throws java.io.IOException; public abstract void receive( Datagram dgram) throws java.io.IOException; public abstract void send( Datagram dgram) throws java.io.IOException; } #BREAK# HttpConnection CLDC 1.0, MIDP 1.0, Foundation 1.0 javax.microedition.io HttpConnection is a ContentConnection that uses HTTP 1.1 as its underlying protocol. An instance of HttpConnection is obtained by invoking the Connector open() with a name argument of the form http://host:port/path. Some implementations may also support a secure connection using HTTPS. The usual sequence of events when using an HttpConnection is to first call setRequestMethod() to set the request method type to either GET (the default), HEAD or POST. Next, add any optional HTTP headers using the setRequestProperty() method. Finally, if this is a POST request, write any data to be sent to an output stream obtained from the openOutputStream() or openDataOutputStream() methods (inherited from ContentConnection). The getResponseCode() method can be called to retrieve the server’s response, which will indicate whether the request was successful (HTTP_OK). Some response codes, such as HTTP_MOVED_TEMP or HTTP_UNAUTHORIZED, require the application to take further action before the request can be performed. The getResponseMessage() method returns any message sent by the server to further explain or qualify the response code. HTTP headers sent by the server can be retrieved in several ways. The getHeaderFieldKey() and getHeaderField() methods can be used to access all of the headers in the request by supplying a zero-based index. These methods return null when the last header has been reached. Given the name of a header, its value can either be retrieved in string form using an overloaded form of getHeaderField() that accepts the header name, or decoded as a Java int or Date object using the getHeaderFieldInt() and getHeaderFieldDate methods. Finally, some fields can be obtained using convenience methods such as getDate() and getExpiration(). The reply data can be read from an InputStream obtained from the openInputStream() or openDataInputStream() methods. The getType() and getEncoding() methods can be used to get the MIME type and character encoding of the data, respectively. Both of these methods may return null, in which case the application will need to make suitable default assumptions. The number of bytes available to be read can be obtained from the getLength() method, which returns the value of the Content-Length header. If this header was not included by the server, the application must repeatedly read the input stream until an end-offile condition is returned. public interface HttpConnection extends ContentConnection { // Public Constants public static final String GET; // =”GET” public static final String HEAD; // =”HEAD” public static final int HTTP_ACCEPTED; // =202 #BREAK# public static final int HTTP_BAD_GATEWAY; // =502 public static final int HTTP_BAD_METHOD; // =405 public static final int HTTP_BAD_REQUEST; // =400 public static final int HTTP_CLIENT_TIMEOUT; // =408 public static final int HTTP_CONFLICT; // =409 public static final int HTTP_CREATED; // =201 public static final int HTTP_ENTITY_TOO_LARGE; // =413 public static final int HTTP_EXPECT_FAILED; // =417 public static final int HTTP_FORBIDDEN; // =403 public static final int HTTP_GATEWAY_TIMEOUT; // =504 public static final int HTTP_GONE; // =410 public static final int HTTP_INTERNAL_ERROR; // =500 public static final int HTTP_LENGTH_REQUIRED; // =411 public static final int HTTP_MOVED_PERM; // =301 public static final int HTTP_MOVED_TEMP; // =302 public static final int HTTP_MULT_CHOICE; // =300 public static final int HTTP_NO_CONTENT; // =204 public static final int HTTP_NOT_ACCEPTABLE; // =406 public static final int HTTP_NOT_AUTHORITATIVE; // =203 public static final int HTTP_NOT_FOUND; // =404 public static final int HTTP_NOT_IMPLEMENTED; // =501 public static final int HTTP_NOT_MODIFIED; // =304 public static final int HTTP_OK; // =200 public static final int HTTP_PARTIAL; // =206 public static final int HTTP_PAYMENT_REQUIRED; // =402 public static final int HTTP_PRECON_FAILED; // =412 public static final int HTTP_PROXY_AUTH; // =407 public static final int HTTP_REQ_TOO_LONG; // =414 public static final int HTTP_RESET; // =205 public static final int HTTP_SEE_OTHER; // =303 public static final int HTTP_TEMP_REDIRECT; // =307 public static final int HTTP_UNAUTHORIZED; // =401 public static final int HTTP_UNAVAILABLE; // =503 public static final int HTTP_UNSUPPORTED_RANGE; // =416 public static final int HTTP_UNSUPPORTED_TYPE; // =415 public static final int HTTP_USE_PROXY; // =305 public static final int HTTP_VERSION; // =505 public static final String POST; // =”POST” // Property Accessor Methods (by property name) public abstract long getDate() throws java.io.IOException; public abstract long getExpiration( ) throws java.io.IOException; public abstract String getFile(); public abstract String getHost(); public abstract long getLastModified( ) throws java.io.IOException; public abstract int getPort(); public abstract String getProtocol(); public abstract String getQuery(); public abstract String getRef(); public abstract String getRequestMethod(); public abstract void setRequestMethod( String method) throws java.io.IOException; public abstract int getResponseCode( ) throws java.io.IOException; public abstract String getResponseMessage( ) throws java.io.IOException; public abstract String getURL(); // Public Instance Methods public abstract String getHeaderField( int n) throws java.io.IOException; #BREAK# public abstract String getHeaderField( String name) throws java.io.IOException; public abstract long getHeaderFieldDate(String name, long def) throws java.io.IOException; public abstract int getHeaderFieldInt(String name, int def) throws java.io.IOException; public abstract String getHeaderFieldKey( int n) throws java.io.IOException; public abstract String getRequestProperty( String key); public abstract void setRequestProperty(String key, String value) throws java.io.IOException; } InputConnection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io InputConnection is an interface implemented by connections that can provide an input stream from the data source. Most connections allow input, but in exceptional cases, such as a connection to a printer, this might not be the case. The openInputStream() method obtains an input stream that can be used to read an ordered sequence of bytes from the data source, while openDataInputStream() returns a stream that can also be used to decode Java primitive data types written to the connection using a DataOutputStream. The result of calling these methods more than once is not defined by the specification. Sun’s reference implementations treat a second call as an error and throw an IOException. The openInputStream() and openDataInputStream() methods will also throw an IOException if the InputConnection was obtained from a Connector open() call which specified a mode of Connector.WRITE. public interface InputConnection extends Connection { // Public Instance Methods public abstract java.io.DataInputStream openDataInputStream( ) throws java.io.IOException; public abstract java.io.InputStream openInputStream( ) throws java.io.IOException; } Implementations StreamConnection #BREAK# OutputConnection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io OutputConnection is an interface implemented by connections that can provide an output stream to the data source. The openOutputStream() obtains an output stream that can be used to write an ordered sequence of bytes from the data source, while openDataOutputStream returns a stream that can be used to write Java primitive data types to the connection in a platform-independent format. Data written using the latter method can be retrieved on the other side using a DataInputStream. The result of calling these methods more than once is not defined by the specification. Sun’s reference implementations treat a second call as an error and throw an IOException. The openOutputStream() and openDataOutputStream() methods will also throw an IOException if the OutputConnection was obtained from a Connector open() call which specified a mode of Connector.READ. public interface OutputConnection extends Connection { // Public Instance Methods public abstract java.io.DataOutputStream openDataOutputStream( ) throws java.io.IOException; public abstract java.io.OutputStream openOutputStream( ) throws java.io.IOException; } Implementations StreamConnection StreamConnection CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io StreamConnection is an interface that combines the methods of InputConnection and OutputConnection, allowing a connection that is capable of both input and output. Although there is no method that explicitly returns a StreamConnection, most invocations of Connector open() will return an object that implements this interface, as most connection types support both input and output. Even though a StreamConnection is capable of allowing both input and output, it is an error to obtain an input stream from a StreamConnection that was obtained using the Connector #BREAK# open() method with Connector.WRITE, or to obtain an output stream if Connector.READ mode was used. public interface StreamConnection extends InputConnection, OutputConnection { } Implementations ContentConnection Returned By StreamConnectionNotifier.acceptAndOpen() StreamConnectionNotifier CLDC 1.0, MIDP 1.0, CDC 1.0 javax.microedition.io StreamConnectionNotifier is a type of Connection returned when the application invokes the Connector open() method with the name argument of the form socket://:port. This creates a server socket, which listens for connections from clients and creates a StreamConnection for each connection received. Connections can be retrieved by calling the acceptAndOpen() method, which blocks until a connection is available. Application code will normally loop through calling this method and creating a new thread to service each connection. Invoking the StreamConnectionNotifier close() method causes acceptAndOpen() to throw an IOException, which can be used to break out of such a loop. public interface StreamConnectionNotifier extends Connection { // Public Instance Methods public abstract StreamConnection acceptAndOpen( ) throws java.io.IOException; } #BREAK# Chapter 15. javax.microedition.lcdui Package javax.microedition.lcdui MIDP 1.0 This package, whose class hierarchy is shown in Figure 15-1, contains the user interface classes for the Mobile Information Device Profile. Each MIDlet is associated with an instance of the Display class, which represents the MIDlet’s view of the screen. At any given time, at most one MIDlet has access to the actual screen and the keyboard and pointer, if the device has them. This MIDlet is said to be in the foreground. While a MIDlet is in the foreground, the content of its Display object will be visible to the user and any changes to it will be seen some time after they are made. A Display shows an object derived from the abstract class Displayable, of which there are two types: Screen and Canvas. Screen is a base class for a set of form-based screens that are part of the the high-level user interface API, while Canvas is a drawing surface for the low- level API. The high-level API provides a set of components, derived from the Item class, that allow the construction of simple user interfaces containing text fields, check boxes, radio buttons and lists. Since the range of devices for which MIDP is intended has a wide variety of input and output capabilities, these classes deliberately provide a programming interface that hides the details of the platform itself and very little customization of the appearance of these components is possible. In particular, it is not possible to change the colors or fonts used to render these components. Items are arranged on a Screen subclass called a Form, which is somewhat like the AWT Frame class. The layout of Items within a Form cannot be directly controlled by the application and may vary from device to device, subject to certain rules that are described in the reference material for the Form class. The ListBox and TextBox classes are full-screen lists and text entry components that, like Form, are derived from Screen. All of these components have the ability to display a title and a ticker, a scrolling text string that works in the same way as a stock price ticker. The same capabilities are also inherited by the Alert class, which behave like a dialog and is usually used to display error, warning and informational messages. #BREAK# Figure 15-1. The java.microedition.lcdui hierarchy The low-level API allows the developer to access the screen at the pixel level, but does not provide any GUI components other than the Canvas class, which the developer must subclass to provide painting logic and to handle keyboard and pointer input events. Both the low-level Canvas class and the Screens of the high-level API can be associated with one or more Commands. Commands are usually represented in the user interface in the form of buttons, but may also appear in the menu system, if the device has one. When the user activates a Command, an event is generated to which application code can respond by performing some action. Several standard Commands, such as OK, EXIT and CANCEL, are defined. Both the high- and low-level APIs allow the display of images, with a fidelity that depends on the capabilities of the screen. MIDP 1.0 supports images encoded in Portable Network Graphics (PNG) format, via the Image and ImageItem classes. User interface operations that are initiated by the device itself, such as event notification and screen repainting operations, take place in a dedicated thread and therefore application code that executes in response to these events should be written in such a way that it executes quickly and delegates time-consuming operations to a separate thread. All of the user interface classes are thread-safe, so it is safe to call their methods in arbitrary threads. #BREAK# Alert MIDP 1.0 javax.microedition.lcdui Alert is a subclass of Screen that behaves somewhat like a dialog. There are several standard Alert styles that can be used; the style is specified using an AlertType object which may be supplied when the Alert is constructed or using the setType() method. An Alert has a title, a message, and an image. These attributes may be set at construction time or using the setTitle(), setString() and setImage() methods. An Alert with no image may be created by calling setImage() with argument null. The way in which the Alert is rendered is platform-dependent. A device is not required to display an image and, even if it does, need not display the image suggested by the application. However, if the platform displays an image at all, changing the AlertType results in a different image being drawn on the Alert. An image explicitly supplied at construction time or using setImage() would override the default one associated with the AlertType. An Alert will usually be displayed for a fixed length of time, after which it will be removed from the display and the screen previously on view will be restored. The display time may be specified using the setTimeout() method, which requires an argument in milliseconds. The special value Alert.FOREVER may be used to create an Alert that remains visible until the user explicitly dismisses it using a control (usually a button) provided by the platform for that purpose. The default time for which an Alert will be displayed (if no explicit timeout is provided) can be obtained using the getDefaultTimeout() method. Devices that have sound capability may play a sound when displaying an Alert. The sound may be a default supplied by the platform, or a specific sound that is determined by the AlertType associated with the Alert. Unlike other Displayables, an Alert may not have application-supplied Commands or CommandListeners and an attempt to call methods that set these attributes will result in an IllegalStateException. public class Alert extends Screen { // Public Constructors public Alert( String title); public Alert(String title, String alertText, Image alertImage, AlertType alertType); // Public Constants public static final int FOREVER; // =-2 // Property Accessor Methods (by property name) public int getDefaultTimeout(); public Image getImage(); public void setImage( Image img); public String getString(); public void setString( String str); public int getTimeout(); #BREAK# public void setTimeout( int time); public AlertType getType(); public void setType( AlertType type); // Public Methods Overriding Displayable public void addCommand( Command cmd); public void setCommandListener( CommandListener l); } Passed To Display.setCurrent() AlertType MIDP 1.0 javax.microedition.lcdui This is a class that provides a set of type-safe constants that are used to specify the type of an Alert. The AlertType provides a hint to the platform as to how it should render the Alert and typically causes an appropriate icon to be included along with the application-supplied message. On devices that have a sound capability, a sound (which might be type-dependent) may also be played when the alert is displayed. The playSound() method may be used to play the sound associated with the AlertType, even when no Alert is displayed. Since not all devices will be able to play sounds, the playSound() method returns a boolean indicating whether a sound was produced, to allow the application to use an alternate mechanism to attract the user’s attention if sound is not available. public class AlertType { // Protected Constructors protected AlertType(); // Public Constants public static final AlertType ALARM; public static final AlertType CONFIRMATION; public static final AlertType ERROR; public static final AlertType INFO; public static final AlertType WARNING; // Public Instance Methods public boolean playSound( Display display); } Passed To Alert.{Alert(), setType()} Returned By Alert.getType() #BREAK# Type Of AlertType.{ALARM, CONFIRMATION, ERROR, INFO, WARNING} Canvas MIDP 1.0 javax.microedition.lcdui Canvas is a Displayable that serves as the most fundamental class of the low-level user interface API. A Canvas can be thought of as a blank sheet of paper that covers the accessible area of a device’s screen. In order to use the Canvas class, a MIDlet must subclass it to provide drawing and event handling logic. When such a subclass is installed as a MIDlet’s current screen (using the Display.setCurrent() method) and the MIDlet is in the foreground, the paint() method will be called as necessary to cause the content of the Canvas to be drawn onto the screen. Similarly, events from the keyboard or a pointing device, if there is one, will be notified to the Canvas and can be handled appropriately by the MIDlet. The abstract paint() method must be implemented to draw the content of the canvas onto the screen, using the Graphics object supplied as its argument. The clipping rectangle in this Graphics object may only cover a subset of the entire Canvas if only part of the screen needs to be repainted. In general, the paint() method should query the clipping rectangle and only perform graphics operations that would affect this part of the screen, where this can be economically determined. A device may or may not double-buffer its screen to provide smoother updates and eliminate flashing caused by partial updates that are visible to the user. The process of double-buffering is transparent to the paint() method, but a MIDlet can determine whether double-buffering is being used by calling isDoubleBuffered(). If this method returns false, a MIDlet may choose to implement its own double-buffering by allocating an Image with the same dimensions as the Canvas (or its clipping rectangle), getting a Graphics object for the image using its getGraphics() method, painting into the image and then copying it to the screen using the Graphics.drawImage() method. The size of the Canvas can be obtained by calling the getWidth() and getHeight() methods. Note that the Canvas may be smaller than the screen because the device may reserve some space for command buttons and soft keypads. Painting operations are always performed in a thread that is dedicated to servicing the user interface. MIDlet code in any thread can request that part or all of the screen be repainted by calling one of the Canvas repaint() methods, which will cause the paint() method to be called in turn at some time in the future. Multiple calls to repaint() may be coalesced into a single paint() call to minimize painting overhead. Code that needs to flush all pending repaint operations may call the serviceRepaints() method, which blocks until all such operations have been completed. The showNotify() and hideNotify() methods may be overridden to receive notification when the Canvas becomes visible to the user or is hidden. These methods may, for example, be used by a MIDlet that performs background calculations to update the contents of a Canvas to temporarily suppress them while the Canvas is not visible. #BREAK# The keyPressed(), keyReleased() and keyRepeated() methods can be overridden to handle events from the keyboard or keypad, if the device has one. Some devices that do not have a physical keypad may provide an on-screen emulation that will result in the generation of the same events. On some platforms, holding a key down for a short period will cause it to repeat and call the keyRepeated(). A MIDlet can determine whether these events are supported by calling the hasRepeatEvents() method. The argument passed to the key handling methods is an integer key code. Some key codes are standardized over all platforms, while others are not. For portability, a MIDlet should only directly test the values of the standard key codes, which correspond to the digits 0 through 9 and the star and pound keys found in cell phone keypads. The values of these key codes are available as numeric constants, such as KEY_NUM0 and KEY_STAR. Support is also provided for game actions, which are mapped to platform-dependent keys or buttons. Each game action has a corresponding numeric constant, such as LEFT, RIGHT, FIRE or GAME_A that should be used by application code instead of hard-coding non-portable key code values. The game action for a key code can be obtained by calling the getGameAction() method so that, for example, the expression (getGameAction(keyCode) == Canvas.LEFT) can be used to check whether the key that corresponds to LEFT has been pressed (or released). An alternative is to use the getKeyCode() method to get the key code for a game action, as in the expression (getKeyCode(Canvas.LEFT) == keyCode). There is no portable way to handle keys that are not numeric and do not map to a game action. In particular, proper handling of text input, including shift states, is difficult and is better handled by using high-level components such as TextField on separate screens. On devices that have a pointing device, the pointerPressed(), pointerDragged() and pointerReleased() methods can be overridden to react to pointer actions. All of these methods receive the coordinates of the pointer relative to the top left-hand corner of the Canvas at the time that the event occurred. The hasPointerEvents() method can be used to determine whether pressed and release events will be notified, and hasPointerMotionEvents() indicates whether pointer drag events are available. public abstract class Canvas extends Displayable { // Protected Constructors protected Canvas(); // Public Constants public static final int DOWN; // =6 public static final int FIRE; // =8 public static final int GAME_A; // =9 public static final int GAME_B; // =10 public static final int GAME_C; // =11 public static final int GAME_D; // =12 public static final int KEY_NUM0; // =48 public static final int KEY_NUM1; // =49 public static final int KEY_NUM2; // =50 public static final int KEY_NUM3; // =51 public static final int KEY_NUM4; // =52 public static final int KEY_NUM5; // =53 public static final int KEY_NUM6; // =54 public static final int KEY_NUM7; // =55 public static final int KEY_NUM8; // =56 #BREAK# public static final int KEY_NUM9; // =57 public static final int KEY_POUND; // =35 public static final int KEY_STAR; // =42 public static final int LEFT; // =2 public static final int RIGHT; // =5 public static final int UP; // =1 // Property Accessor Methods (by property name) public boolean isDoubleBuffered(); public int getHeight(); public int getWidth(); // Public Instance Methods public int getGameAction( int keyCode); public int getKeyCode( int gameAction); public String getKeyName( int keyCode); public boolean hasPointerEvents(); public boolean hasPointerMotionEvents(); public boolean hasRepeatEvents(); public final void repaint(); public final void repaint(int x, int y, int width, int height); public final void serviceRepaints(); // Protected Instance Methods protected void hideNotify(); // empty protected void keyPressed( int keyCode); // empty protected void keyReleased( int keyCode); // empty protected void keyRepeated( int keyCode); // empty protected abstract void paint( Graphics g); protected void pointerDragged( int x, int y); // empty protected void pointerPressed( int x, int y); // empty protected void pointerReleased( int x, int y); // empty protected void showNotify(); // empty } Choice MIDP 1.0 javax.microedition.lcdui Choice is an interface that contains the methods common to user interface components that allow the user to choose from several possible alternatives. This interface is implemented by the full-screen List control and by ChoiceGroup, which is an Item. A Choice can operate in one of three different modes: EXCLUSIVE Only one alternative can be selected. If the user selects one item from the set of offered alternatives, any item already selected is deselected. In this mode, the control behaves as (and is usually rendered to look like) a set of radio buttons. MULTIPLE Any number of alternatives can be selected. Selecting one item from the list has no effect on the selected state of other entries. In this, the control behaves like a collection of check boxes. #BREAK# IMPLICIT This mode is available only with the List control. It allows only one item to be selected at any given time and is typically used to create a menu. The difference between this mode and EXCLUSIVE, apart from the visual differences, lies in the way in which selection changes are notified to application code. See the description of the List control for details. Each entry in a Choice consists of one or both of an image provided in the form of an Imageobject and a text string. The image, if provided, is rendered in addition to any icon, such as a check box or radio button, supplied by the control itself. The number of entries can be obtained by calling the size() method. An entry is distinguished by its index, where the first entry has index 0 and the last has index size() - 1. New entries can be added to the end of the list using the append() method, or inserted before an existing entry with a given index by calling insert(). The set() method replaces the text and image associated with an entry at a specified index and the delete() method removes an entry. The platform will provide some means for the user to navigate the entries in the Choice. Usually, one entry will be considered to have the input focus and will be highlighted in some way to distinguish it from the other entries. The platform will also supply a mechanism for the user to toggle the selected state of the highlighted entry. It is important to realize that selection and highlighting are different, in that highlighting is used only for the convenience of the user, whereas selection changes the state of the control. Changing the selection may cause a notification to be delivered to a listener. The specifics of event notification depend on the control itself and are described in the reference entries for the ChoiceGroup and List controls. There are three methods that application code can use to access the selected state of entries in the Choice. The getSelectedIndex() method returns the index of the selected entry, or -1 if no entry is selected. In MULTIPLE mode, this method always returns -1 because more than one entry could be selected. The isSelected() method returns true if the entry with a given index is selected, false if it is not. Finally, the getSelectedFlags() method returns the selected state of each entry in an array of booleans that must be allocated by the caller and must have at least as many entries as there are entries in the Choice. The entry at index n in the array is returned with value true if the entry at index n in the Choice is selected, false if it is not. The return value of this method is the total number of selected entries. There are two methods that allow the selection in the Choice to be programmatically changed. The setSelectedIndex() method sets the selected state of an entry with a given index according to the boolean value supplied as its second argument. In MULTIPLE mode, this method simply changes the selected state of the given entry and has no effect on other entries. In EXCLUSIVE and IMPLICIT modes, this method has an effect only if the boolean argument is true. In both modes, the given entry is selected and any previously selected entry is deselected. The setSelectedFlags() method sets the state of every element in the Choice from the corresponding entry in an array of boolean values supplied as its argument. In EXCLUSIVE and IMPLICIT modes, only one entry in the array can have value true. If this is not the case, then the first entry in the Choice will be selected and all other entries will be deselected. #BREAK# Programmatic changes to the selection do not generate notifications to listeners. public interface Choice { // Public Constants public static final int EXCLUSIVE; // =1 public static final int IMPLICIT; // =3 public static final int MULTIPLE; // =2 // Public Instance Methods public abstract int append(String stringElement, Image imageElement); public abstract void delete( int elementNum); public abstract Image getImage( int elementNum); public abstract int getSelectedFlags( boolean[] selectedArray_return); public abstract int getSelectedIndex(); public abstract String getString( int elementNum); public abstract void insert(int elementNum, String stringElement, Image imageElement); public abstract boolean isSelected( int elementNum); public abstract void set(int elementNum, String stringElement, Image imageElement); public abstract void setSelectedFlags( boolean[] selectedArray); public abstract void setSelectedIndex(int elementNum, boolean selected); public abstract int size(); } Implementations ChoiceGroup, List ChoiceGroup MIDP 1.0 javax.microedition.lcdui This class is an Item that presents a list of alternatives to the user and allows one or more of them to be selected. Most of the methods of the ChoiceGroup class are implementations of those specified by the Choice interface, which it implements, and are described in the reference entry for Choice. A ChoiceGroup can be constructed in either