Lecture 4. Essential java Classes
Download
Report
Transcript Lecture 4. Essential java Classes
Java Programming
Essential Java Classes
Cheng-Chia Chen
Transparency No. 1
Essential Java classes
Contents
1. Java.lang.*
1.
2.
3.
4.
5.
6.
7.
Wrapper classes for primitive types
String, StringBuffer, StringBuilder
Math
Thread
System
Process
Runtime
2. Java.util.*
1. java collection classes
2. other classes
Transparency No. 2
Essential Java classes
The java.lang package
Transparency No. 3
Essential Java classes
The java.lang package
loc: http://java.sun.com/j2se/1.5/docs/api/java/lang/packagesummary.html
contains classes and interfaces that are essential to the Java
language.
String processing: String, StringBuffer, StringBuilder
Classes that encapsulate the primitive data types in Java.
Boolean, Character, Void
Number Byte, Short, Integer, Long, Float, Double
Mathematical operations: Math, StrictMath
Thread supports:
Thread, ThreadGroup, ThreadLocalInheritableThreadLocal
4 interfaces:
Clonable, Runnable, Comparable, CharSequence
Transparency No. 4
Essential Java classes
The java.lang package (continued)
Platform or OS-related classes:
Runtime, Process, System
Classes that represent objects, classes, packages,…
Object, Class, Package, Compiler, ClassLoader
Security-related classes:
SecurityManager, RuntimePermission
Errors and Exceptions: Throwable
Error ThreadDeath
VirtualMachineError …
LinkageError …
Exception RuntimeException ( …), ClassNotFoundException,
CloneNotSupportedException,
IllegalAccessException,InstantiationException,
InterruptedException,NoSuchFieldException,NoSuchMethodException
Transparency No. 5
Essential Java classes
The String and StringBuffer classes
Differences: String instances are immutable (i.e., cannot be
modified in place) while StringBuffer instances are not.
The String class:
public final , implements Serializable, Comparable, CharSequence.
Constructors: (non-strings to strings)
public String(); // empty stirng
// byte array string;
public String(byte[] [ [,int offset, int length] [,String charsetName]] )
// charsetName given by the “file.encoding” property
// charsetName = “MS950” or “Big5” for zh_TW
public String(char[] [, offset, length] ); // char array string
public String(String); // create a new copy
public String(StringBuffer); // StringBuffer2String
Transparency No. 6
Essential Java classes
The java.lang.String class
Class Methods : Converting values of other types to strings
// = new String(char[], [offset, count] )
public static String copyValueOf(char[] [, int offset, int count] );
// = copyValueOf(char[] [offset, count] )
public static String valueOf(char[] [, int offset,int count ] );
public static String valueOf(Type x);
// where Type is boolean, char, int, long, float, double or Object.
// ex: String.valueOf(false) return “false”
//
String.valueOf(null) return “null”
//
String.valueOf(Object obj) returns obj.toString()
Transparency No. 7
Essential Java classes
The java.lang.String class
Instance methods:
// Comparisons
public int compareTo(String | Object);
public boolean equals(Object);
public boolean equalsIgnoreCase(String);
public boolean startsWith(String [,int from] );
public boolean endsWith(String suffix);
public boolean regionMatches([boolean ignoreCase,]
int toffset, String other, int ooffset, int len);
// return false if substring : (tooffset, len ) or (ooffset, len)
// does not exist.
Transparency No. 8
Essential Java classes
The java.lang.String class
// find substring:
public char charAt(int index); // impl. of CharSequence
public CharSequence subsequence(int beginIndex , int endIndex );
public String substring(int beginIndex [, int endIndex] );
// String byte/char array
public byte[] getBytes([String charsetName]);
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
public char[] toCharArray();
// find position of substring/char
public int indexOf(int ch [, int from]);
public int indexOf(String str [,int from]);
public int lastIndexOf(int ch [,int from]);
// searching backward starting at the specified index
public int lastIndexOf(String str [, int fromIndex]);
Transparency No. 9
Essential Java classes
The java.lang.String class
Immutable String modification:
public String concat(String str), replace(char oldChar, char newChar);
public String toLowerCase([java.util.Locale]);
public String toUpperCase([Locale]); // def is Locale.getDefault()
Auxiliary methods:
public int hashCode(); // if s = s[0] s[1] … s[n-1] => returns
// s[0]x 31n-1 + s[1]x 31n-2+ … + s[n-1]
public native String intern(); // if there is an instance s in the system
string pool equal to this => return s, o/w put this to the pool and return
this.
public int length();
// impl. of CharSequence
public String toString(); // return this; note: s.toString() == s
public String trim(); // remove all whitespaces (as well as all control
char < ‘ ‘( \u0021)) from both ends
Transparency No. 10
Essential Java classes
The java.lang.String class
public String[] split(String regex [, int limit])
since jdk 1.4
= Pattern.compile(regex).split(this, limit)
See the package java.util.regex for details
Ex1:
this = "boooo:and:foo:", ==>
this.split(“:”, 2) yields {“boooo”, “and”}
this.split(“:”, 5) yields {“boooo”, “and”, “foo”, “”}
Meaning of limit:
negative ==> return all splits
0 (default)=> tailing empty string not returned
positive ==> only the first nth splits return
Ex2: this = "boooo:and:foo“
==> this.split(“oo”, 0 ) yields {“b”,””, “:and:f”}
Transparency No. 11
Essential Java classes
The java.lang.StringBuffer and StrignBuilder class
public final class StringBuffer, StringBuilder implements
Serializable, CharSequence
Description:
1. implements a mutable sequence of characters.
2. like a String, but can be modified; length and content can be changed
through method calls.
3. thread safe (methods are synchronized) StrignBuffer
Save but less efficient
4. not thread-safe (mothods not synchronized) StringBuilder
Efficient but danger
5. used by the compiler to implement the binary string concatenation
operator +.
x = "a" + 4 + "c“ is compiled to the equivalent of:
x = new StringBuffer().append("a").append(4).append("c").toString()
6. main (overloaded) methods: insert(…), append(…)
7. has an internal buffer; overflow => automatically made larger (twice)
Transparency No. 12
Essential Java classes
The java.lang.StringBuffer class
// Constructors
public StringBuffer(); // initial buffer size = this.capacity() = 16
public StringBuffer(int length);
public StringBuffer(String str);
// Instance Methods
public int length();
public int capacity(); // return buffer size
public synchronized void ensureCapacity(int minCap);
// if buffer size < minCap =>
//
change buffer size to max(minCapacity, 2 x this.capacity())
public [synchronized] StringBuffer append(<Type>);
// where <Type> can be any primitive type , String or Object
public synchronized StringBuffer append(char[] str, int offset, int len);
public [synchronized] StringBuffer insert(int offset, <Type>);
Transparency No. 13
Essential Java classes
The java.lang.StringBuffer class
// instance methods
public synchronized char charAt(int index);
public synchronized void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin);
public synchronized StringBuffer reverse();
public synchronized void setCharAt(int index, char ch);
public synchronized void setLength(int newLength);
// newLength < this.length() => truncate
// newLength > this.length() => append null chars \u0000.
public String toString();
Transparency No. 14
Essential Java classes
The java.util.StringTokenizer class
provides support for parsing a string into a sequence of words,
or tokens, that are separated by some set of delimiter
characters.
can use java.util.Scanner as well, which is more powerful and handy
and can fetch primitive data as well as String from the input.
Example:
StringTokenizer s = new StringTokenizer("This is it");
while (s.hasMoreTokens())
System.out.println(s.nextToken());
Default delimiters are whitespaces: space, tab ('\t'), carriage
return ('\r'), and newline ('\n').
StringTokenizer s = new StringTokenizer(“fruits: apple, banana.",
“:,. “); // output => fruits apple banana
Transparency No. 15
Essential Java classes
Scanner Examples:
Ex1:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
out.println(s.nextInt()); // 1
out.println(s.nextInt()); // 2
out.println(s.next()); // “red”
out.println(s.next()); // “blue”
s.close();
Ex2 : // white space is the default delimiter
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
Transparency No. 16
Essential Java classes
Wrapper classes for primitive types
Number Byte, Short, Integer, Long, Float, Double
Boolean, Character, Void
Descriptions:
are wrapper classes for byte, short, int, long, float, double,
boolean, char and void, respectively.
each class contains a single field storing a value of the
wrapped type. useful when we must or want to treat a value of
primitive type as an object.
provides methods for conversion between each type and
String.
provides useful methods and related constants for each type.
eg: MAX_VALUE, MIN_VALUE, TYPE, etc.
Transparency No. 17
Essential Java classes
The java.lang.Number class
public abstract class java.lang.Number
implements java.io.Serializable
// Instance Methods
this value of various primitive numeric types:
byte byteValue()
{ return (byte) this.intValue();}
short shortValue()
{ return (short) this.intValue();}
// implemeted by subclasses
abstract int intValue();
abstract long longValue();
abstract float floatValue();
abstract double doubleValue();
Transparency No. 18
Essential Java classes
naming conventions
Let <Type> be a wrapper class of primitive type <type>:
Then the following static methods are provided in class
<Type>:
String <Type>
<Type> decode(String s) // radix info in s : “0x12”= “#12”=“18”=“022”
<Type> valueOf(String s [,int radix]) // radix info not in s.
String <type>
<type> parse<type*>(String s [,int]) // s a value of type <type>
<type> String : String toString(<type> [, int radix]); // r in [2,36]
<Type> String : (instance method); toString(); //decimal assumed
Ex: if <Type> = Integer => <type> = int, and provided classes
methods include:
Integer decode(String);
int parseInt(String, int);
Integer valueOf(String, int)
String toString(int [,int radix]);
Transparency No. 19
Essential Java classes
Summary of conversion methods among primitive types,
String and their Wrapper classes
----- class methods
toString() ; String.valueOf(.)
----- instance method
String
Type1.decode(String)
Type1.valueOf(s [,radix])
new Type1(s [,radix]) Type1
----- constructor
t2Value()
t2
new Type1(t1)
Type1.parseT1(s [,r])
Type1.toString(t1 [, r])
Type1.toBinaryString()
Type1.toOctalString()
Type1.toHexString()
Note:
t1 = int =>
t1
• Type1 = Integer
• T1 = Int
For integer types only
Transparency No. 20
Essential Java classes
Converting methods among int, String and Integer
----- class methods
toString() ;
String.valueOf(.)
----- instance method
----- constructor
String
Integer.decode(String)
Integer.valueOf(s [,radix])
Integer longValue()
new Integer(s [,radix])
intValue()
long
new Integer(int)
Integer.parseInteger(s [,r])
int
Integer.toString(t1 [, r])
Integer.toBinaryString()
Integer.toOctalString()
Integer.toHexString()
Note:
t1 = int =>
• Type1 = Integer
• T1 = Int
For non-floating types only
Transparency No. 21
Essential Java classes
The java.lang.Integer class
public final class Integer extends Number
implementsComparable
Description:
wrap an int value into an object.
An object of type Integer contains a single field whose type
is int.
provides several methods for: int String and String int,
as well as other constants and methods useful when dealing
with an int.
Transparency No. 22
Essential Java classes
Integer class summary
// Constants
public static final int MAX_VALUE, MIN_VALUE;
public final static Class TYPE; // representing primitive int
// Constructors: Integer(int), Integer(String);
// Class Methods
Stringint:
parseInt(String s [,int radix])
StringInteger:
decode(String nm) // decode(“-0x12”) -18
valueOf(String s [, int radix]) // equ. to new Integer(parseInt(s, radix))
String Integer via system property:
getInteger(String nm [, (int | Integer ) val ]) // val is the default.
// = decode(System.getProperty(nm [,val]))
int String : toBinaryString(int),toHexString(int), toOctalString(int),
toString(int i [, int radix] );
// cf: Integer.toHexString(-10) = “fffffff6”; toString(-10,16) = “-a”
Transparency No. 23
Essential Java classes
The java.lang.Integer class
// Instance Methods
// implements Number methods
this value of primitive types :
pubic byte byteValue();
public short shortValue();
public int intValue();
public long longValue();
public float floatValue();
public double doubleValue();
// implements or overrides Object methods
this String: toString(); // = Integer.toString(this.intValue())
comparison:
boolean equals(Object obj); // true iff obj.intvalue() = this.intValue())
int compareTo(Object | Integer);
hash:
int hashCode(); // = this.intvalue()
Transparency No. 24
Essential Java classes
the java.lang.Long class summary
// Constants
public static final int MAX_VALUE, MIN_VALUE;
public final static Class TYPE;
// Constructors
Long(long), Long(String);
// Class Methods // parseLong(“12”, 16) 18
Stringlong: parseLong(String s [,int radix]) //parseLong(“0x12”) err
StringLong: decode(String nm) // decode(“-0x12”) -18
valueOf(String s [, int radix]) // equ. to new Long(parseLong(s, radix))
String Long via system property: getLong(String nm [, (int | Long )
val ])
// System property named nm; val is the default.
// = Long.decode(System.getProperty(nm, val))
long String : toBinaryString(long), toHexString(long),
toOctalString(long), toString(long [,int]);
Transparency No. 25
Essential Java classes
The java.lang.Long class
// Instance Methods
// implements Number methods
this value of various numeric primitive types :
pubic byte byteValue();
public short shortValue();
public int intValue();
public long longValue();
public float floatValue();
public double doubleValue();
// implements or overrides Object methods
this String: toString(); // = Long.toString(this.intValue())
comparison:
boolean equals(Object obj); // true iff obj.intvalue() = this.intValue())
int compareTo(Object | Long);
hash:
int hashCode(); // = this.intvalue()
Transparency No. 26
Essential Java classes
The java.lang.Byte class
public final class java.lang.Byte extends java.lang.Number
// Constants
public static final byte MAX_VALUE = 127, MIN_VALUE = -128;
public static final Class TYPE;
Constructors: public Byte(byte); public Byte(String);
// Class Methods: StringByte, byte; byte String
public static Byte decode(String nm);
public static Byte valueOf(String s [, int radix]); // valueOf(“0x12”) err
public static byte parseByte(String s [, int radix]);
public static String toString(byte b); // radix is 10
// Instance Methods : same as Integer.
// implements Number methods: omitted here
// implemetns or override Object methods
boolean equals(Object obj);
public int hashCode();
String toString();
compareTo(Byte | Object)
Transparency No. 27
Essential Java classes
The java.lang.Short class
public final class java.lang.Byte extends java.lang.Number
// Constants
public static final short MAX_VALUE = 32767, MIN_VALUE = -32768;
public static final Class TYPE;
Constructors: public Short(short); public Short(String);
// Class Methods: StringShort, short; short String
public static Short decode(String nm);
public static Short valueOf(String s [, int radix]); // valueOf(“0x12”) err
public static short parseByte(String s [, int radix]);
public static String toString(short b); // radix is 10
// Instance Methods : same as Integer.
// implements Number methods: omitted here
// implemetns or override Object methods
boolean equals(Object obj);
public int hashCode();
String toString();
compareTo(Short | Object)
Transparency No. 28
Essential Java classes
the java.lang.Float class
// Constants
public static final int MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY,
POSITIVE_INFINITY, NaN;
public final static Class TYPE;
// Constructors
Float( float | double | String) ;
// Class Methods
Stringfloat: parseFloat(String)
StringFloat: valueOf(String)
float String : toString(float);
float int : floatToIntBits(float), floatToRawIntBits(float)
int float: intBitsToFloat (int)
isNan(float);
isInfinity(float)
Transparency No. 29
Essential Java classes
The java.lang.Float class
// Instance Methods
isNan(),
isInfinity()
// implements Number methods
this value of various numeric primitive types :
pubic byte byteValue();
public short shortValue();
public int intValue();
public long longValue();
public float floatValue();
public double doubleValue();
// implements or overrides Object methods
this String: toString(); // = Long.toString(this.intValue())
comparison:
boolean equals(Object obj); // true iff obj.intvalue() = this.intValue())
int compareTo(Object | Float);
hash:
int hashCode(); // = this.intvalue()
Transparency No. 30
Essential Java classes
IEEE 754 float-point single precision layout
0x7f800000 => positive infinity.
0xff800000 => negative infinity.
0x7f800001 ~ 0x7fffffff or 0xff800001~0xffffffff => NaN.
Java use 0x7fc00000 as the canonical value of NaN.
Distinct values of NaN are only accessible by use of the
Float.floatToRawIntBits(float)
In all other cases, let s, e, and m be three values that can be
computed from the argument:
int s = ((bits >> 31) == 0) ? 1 : -1;
int e = ((bits >> 23) & 0xff); // s bit is ignored by mask of 0xff
int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000;
the floating-point result is s · m · 2 e-150.
Transparency No. 31
Essential Java classes
IEEE 754 float-point single precision layout
s
(exponent)
e
b31 b30 b29 b28 b27 b26 b25 b24 b23 b22 b21 b20 b19 b18 b17 b16
(mantissa)
m
b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 b1 b0
value is determined as follows:
0. s = (b31 == 0 ? 1: -1);
1. 255> e > 0 => value = s x (1.m)2 x 2 e –127 = s x (1m) x 2 e - 150
2. e = 0
=> value = s x (b22.b21---b00)2 x 2 e-127 = s x (m 0)2 x 2 e - 127-23
3. e=255 && m == 0 => value = ( s == 0 ? Infinity : -Infinity)
4. e = 255 && m != 0 => value = NaN; canonical NaN = 0181022
Transparency No. 32
Essential Java classes
the java.lang.Double class
// Constants
public static final double MAX_VALUE, MIN_VALUE,
NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN;
public final static Class TYPE;
// Constructors
Double( double | String) ;
// Class Methods
Stringdouble: parseDouble(String)
StringDouble: valueOf(String)
double String : toString(double);
double long : doubleToLongBits(double),
doubleToRawLongBits(double)
long double: longBitsToDouble (long)
isNan(long);
isInfinity(long)
Transparency No. 33
Essential Java classes
The java.lang.Float class
// Instance Methods
isNan(),
isInfinity()
// implements Number methods
this value of various numeric primitive types :
pubic byte byteValue();
public short shortValue();
public int intValue();
public long longValue();
public float floatValue();
public double doubleValue();
// implements or overrides Object methods
this String: toString(); // = Long.toString(this.intValue())
comparison:
boolean equals(Object obj); // true iff obj.intvalue() = this.intValue())
int compareTo(Object | Double);
hash:
int hashCode(); // = this.intvalue()
Transparency No. 34
Essential Java classes
IEEE 754 float-point double precision layout
0x7ff0000000000000L => positive infinity.
0xfff0000000000000L => negative infinity.
0x7ff0000000000001L~ 0x7fffffffffffffffLor 0xfff0000000000001L~
0xffffffffffffffffL=> NaN.
Java use 0x7ff8000000000000L as the canonical value of NaN.
Distinct values of NaN are only accessible by use of the
Double.doubleToRawLongBits(double)
In all other cases, let s, e, and m be three values that can be
computed from the argument:
int s = ((bits >> 63) == 0) ? 1 : -1;
int e = ((bits >> 52) & 0xff);
int m = (e == 0) ? (bits & 0xfffffffffffffL) << 1 : (bits & 0xfffffffffffffL) |
0x10000000000000L;
the floating-point result is s · m · 2 e-1075.
Transparency No. 35
Essential Java classes
The java.lang.Character class
public final class java.lang.Character implements java.io.Serializable
// Constants :
// byte constants: Names for various UNICODE character categories
COMBINING_SPACING_MARK, CONNECTOR_PUNCTUATION;
CONTROL;
CURRENCY_SYMBOL;
DASH_PUNCTUATION;
DECIMAL_DIGIT_NUMBER;
ENCLOSING_MARK;
END_PUNCTUATION;
FORMAT; LETTER_NUMBER; LINE_SEPARATOR; LOWERCASE_LETTER;
MATH_SYMBOL;
MODIFIER_LETTER;
MODIFIER_SYMBOL;
NON_SPACING_MARK;
OTHER_LETTER;
OTHER_NUMBER;
OTHER_PUNCTUATION;
OTHER_SYMBOL;
PARAGRAPH_SEPARATOR; PRIVATE_USE;
SPACE_SEPARATOR;
START_PUNCTUATION; SURROGATE;
TITLECASE_LETTER;
UNASSIGNED;
UPPERCASE_LETTER;
public final static Class TYPE;
public final static int MAX_RADIX;
public final static int MIN_RADIX;
public final static char MAX_VALUE;
public final static char MIN_VALUE;
Transparency No. 36
Essential Java classes
The java.lang.Character class
Constructors: public Character(char value);
Class Methods:
int digit(char ch, int radix);
// digit(‘a’, 16) == 10
int getNumericValue(char ch);
char toTitleCase(char ch);
char forDigit(int digit, int radix);
// forDigit(11, 16) == ‘b’
char toLowerCase(char ch);
char toUpperCase(char ch);
// Character category checking
public static int getType(char ch); // return category ch belongs to
isDefined(char ch); isDigit(char ch); isIdentifierIgnorable(char ch);
isISOControl(char ch);
isJavaIdentifierPart(char ch);
isJavaIdentifierStart(char ch);
isLetter(char ch); isLetterOrDigit(char ch);
isLowerCase(char ch); isSpaceChar(char ch);
isTitleCase(char ch); isUnicodeIdentifierPart(char ch); // New in 1.1
isUnicodeIdentifierStart(char ch); isUpperCase(char ch); isWhitespace(char ch);
// Instance Methods
public char charValue(); equals(Object obj); hashCode(); String toString();
Transparency No. 37
Essential Java classes
The java.lang.Math classes
public final class java.lang.Math
// Constants
public static final double E, PI;
// Class Methods
abs(int | long | float |double );
ceil(double a);
floor(double a);
double sqrt(double a); int round(float a);
long round(double
a);
max(<type>,<type>); min(<type>,<type>); // <type> = int, long, float or double
// double trigonometric functions:
asin(double);
acos(double);
atan(double ); atan2(double a, double b);
sin(double a);
cos(double);
tan(double)
// exponential functions
pow(double a, double b);
exp(double);
log(double a); // base e
IEEEremainder(double f1, double f2);
double random(); // 0.0 ~1.0
double rint(double a); // math integer closest to a
Transparency No. 38
Essential Java classes
Some java collection classes
utility classes that help you to manage a collection of objects.
java.util.Vector
represents a dynamic array of objects.
java.util.Stack:
represents a dynamic stack of objects.
java.util.Dictionary:
abstract class that manages a collection of objects by associating a key with each
object.
java.util.Hashtable
a subclass of java.util.Dictionary that implements a specific algorithm to associate
keys with objects.
java.util.Properties
a subclass of Hashtable where all keys and values are String objects.
java.util.Enumeration (deprecated)
interface supporting sequential access to a set of elements.
Transparency No. 39
Essential Java classes
The java.util.Vector class
implements a variable-length array that can hold any kind of object.
Constructors:
Vector( [[ int initCapacity] [, int incrCapacity]]) // default: 10, 0(double)
Ex: Vector v = new Vector(100);
Vector<Person> gv = new Vector<Person>();
append elements:
v.addElement("abc"); v.addElement( new int[2] {1,2} );
v.addElement(123); // error since 123 is not an Object instance
// fine after jdk 1.5 due to autoboxing
insert element: but gv.add(“abc”) –(x), gv.add(new Person()) – (0).
v.insertElementAt(“123”, 2) or v.add(2, “123” ).
vector size: v.size();
Retrieve elements:
firstElement(); lastElement(), elementAt(int), get(int) // all return Object
Enumeration elements(); Iterator iterator()
Transparency No. 40
Essential Java classes
set/remove element:
Object setElementAt(Object, int), Object set(int, Object)
void removeElementAt(int),
remove(int)
// removes the first element in the Vector that refers to the given
boolean removeElement(Object) , remove (Object)
removeRange(int from,int to)
removeAllElements().
Vector to array:
toArray( [ Object[] a ]) // return an array whose component type is that
of a.
check if an object is in the vector:
boolean contains(Object),
int indexOf(Object), int lastIndexOf(Object) // return –1 if not found
Transparency No. 41
Essential Java classes
The java.util.Stack class
a subclass of Vector implementing a last-in-first-out
(LIFO) object stack.
Constructor:
Stack() // create an empty stack
instance methods:
boolean empty() // returns true if and only if the stack is
empty.
Object push(Object) // same as addElement(Object)
Object pop() throws EmptyStackException.
Object peek() throws EmptyStackException.
// throws an EmptyStackException if empty()
Transparency No. 42
Essential Java classes
The Hashtable and Dictionary classes in java.util
Dictionary ( implements Map )
an abstract class that defines methods for associating key objects with
value objects.
Given a key, an instance of Dictionary is able to return its associated
value.
Hashtable
a concrete subclass of Dictionary that uses a data structure called a
hashtable and a technique called chained hashing to allow values
associated with keys to be fetched with minimal searching.
Transparency No. 43
Essential Java classes
The Dictionary Class
constructor: Dictionary();
// Instance Methods
public abstract Enumeration elements(); // return values
public abstract Enumeration keys(); // return keys
public abstract Object get(Object key);
public abstract Object put(Object key, Object value);
public abstract Object remove(Object key);
public abstract int size();
key
public abstract boolean isEmpty();
Java
value
SUN
…
…
C#
MOSFT
Transparency No. 44
Essential Java classes
The hashtable class
public class java.util.Hashtable extends java.util.Dictionary
implements java.lang.Cloneable, java.io.Serializable
Constructors
public Hashtable( [[ int initialCapacity ] [, float loadFactor]] );
// Instance Methods : 1. Dictionary implementation
get(Object); put(key, value); keys(); elements();
isEmpty(); size(); remove(Object)
// 2. special synchronized methods:
void clear(); Object clone();
boolean contains(Object value); containsKey(Object key);
String toString();
// Protected Instance Methods
protected void rehash();
Transparency No. 45
Essential Java classes
The java.util.Properties class
Special hashtable whose key and value must be strings and support
persistence.
public class java.util.Properties extends java.util.Hashtable {
// Variables
protected Properties defaults; // parent properties
// Constructors
public Properties( [ Properties defaults] );
// Instance Methods
public String getProperty(String key [, String defaultValue ]);
pubilc String setProperty(String key, String val);
public Enumeration propertyNames();
public void list( PrintStream | PrintWriter); // list this to out
public synchronized void load(InputStream in); // load from in
public synchronized void store(OutputStream out, String header);
}
Transparency No. 46
Essential Java classes
Accessing the Environment
java.lang.System and java.lang.Runtime classes
provide a variety of methods that allow a Java program to access
information and resources for the environment in which it is running.
This environment includes the Java virtual machine (Runtime) and the
native operating system (System).
System
interface to OS
contains several useful class fields and methods.
standard input, standard output, and error output streams;
access to externally defined "properties";
a means of loading files and libraries; and
a utility method for quickly copying a portion of an array.
Transparency No. 47
Essential Java classes
The System class
public final class java.lang.System extends java.lang.Object
// Constants
public static final PrintStream err, out; // system error and system output
public static final InputSteram in; // system input
// Class Methods
void setOut(PrintStream); setIn(InputStream); setErr(PrintStream);
// note: setOut(out1) is not the same as System.out = out1 (illegal operation!)
Properties getProperties();
void
setProperties(Properties props); // set system properties
String
getProperty(String key [, String default]);
arraycopy(Object src, int srcOffset, Object dst, int dstOffset, int length);
long currentTimeMillis();
void exit(int status);
void gc();
public static void load(String filename); // same purpose as loadLibrary
public static void loadLibrary(String libname);
…
Transparency No. 48
Essential Java classes
Some Standard system properties
file.encoding,
file.encoding.pkg
The character encoding for the default locale
The package that contains the converters that handle converting between local
encodings and Unicode
file.separator,
line.separator,
path.separator
The platform-dependent file separator (e.g., "/" on UNIX, "\" for Windows)
The platform-dependent line separator (e.g., "\n" on UNIX, "\r\n" for Windows)
The platform-dependent path separator (e.g., ":" on UNIX, “;" for Windows)
java.class.path
The value of the CLASSPATH environment variable
java.class.version
The version of the Java API
java.compiler
The just-in-time compiler to use, if any.
java.home
The directory in which Java is installed
Transparency No. 49
Essential Java classes
Some Standard system properties
java.version, java.vendor, java.vendor.url
The version of the Java interpreter
vendor-specific string
vendor URL
os.name, os.arch, os.version
The name, architecture and version of the operating system
user.dir, user.home, user.name
The current working directory when the properties were initialized
The home directory of the current user
The username of the current user
user.language, user.region, user.timezone
The two-letter language code of the default locale: zh
The two-letter country code of the default locale : TW
The default time zone : empty
Transparency No. 50
Essential Java classes
The Runtime class
public class java.lang.Runtime extends java.lang.Object
// Class Methods ;
interface to JVM
public static Runtime getRuntime();
// Instance Methods
public Process exec(String command [, String[] envp [,File workingdir]]);
public Process exec(String[] cmdarray [, String[] envp [,File workingdir]]);
public native long freeMemory(); // in the system
public native long totalMemory(); // in JVM
public native void gc();
public void exit(int status);
public synchronized void load(String filename); // load non-class code file
public synchronized void loadLibrary(String libname); //load system code
public native void runFinalization();
public native void traceInstructions(boolean on); // enable/diable trace
public native void traceMethodCalls(boolean on);
Transparency No. 51
Essential Java classes
The java.lang.Process class
public abstract class Process extends Object
returned by Runtime.exec(…)
Method Summary
abstract void destroy()
Kills the subprocess. Process p = Runtime.getRuntime().exec(“test.exe”); p.destroy();
abstract int exitValue()
Returns the exit value for the subprocess.
abstract InputStream getErrorStream()
Gets the error stream of the subprocess.
abstract InputStream getInputStream()
Gets the output stream of the subprocess as an input stream of the current process.
abstract OutputStream getOutputStream()
Gets the input stream of the subprocess as my outputStream.
abstract int waitFor() // wait until termination
causes the current thread to wait, if necessary, until the process represented
by this Process object has terminated.
Transparency No. 52
Essential Java classes
The java.lang.Class class
Instances represent classes and interfaces in a running Java
application. including
Every array; All arrays with the same element type and number of
dimensions share a same Class instance.
The primitive Java types (boolean, byte, char, short, int, long, float, and
double), and the keyword void are also represented as Class objects.
Different ways to get a Class object for a particular data type:
o.getClass() // o is any Object instance
t.class
// t is any type
ex: Class s = String.class; Class i = int.class;
Class v = java.util.Vector.class;
Class v = Class.forName("java.util.Vector");
Transparency No. 53
Essential Java classes
The java.lang.Class class
public final class Class extends Object implements java.io.Serializable {
// Class Methods
public static native Class forName(String className);
// Instance Methods
Package getPackage();
Class getDeclaringClass(); // return the class of which this is a member
String getName();
// class name
int getModifiers();
Class getSuperclass();
Class[] getInterfaces();
Object newInstance();
ClassLoader getClassLoader();
URL getResource(String name);
InputStream getResourceAsStream(String name);
boolean isInstance(Object obj);
boolean isArray(); isInterface(); isPrimitive(); String toString();
Transparency No. 54
Essential Java classes
The java.lang.Class class
public Constructor[] getConstructors(), getDeclaredConstructors();
public Constructor getConstructor(Class[] parameterTypes);
public Constructor getDeclaredConstructor(Class[] parameterTypes);
Class[] getClasses(); // return all public [even inherited] member classes
// all non-inherited (even privated) members classes
Class[] getDeclaredClasses();
Class getComponentType(); // return component class of this array
Field[] getFields(),
getDeclaredFields();
Field getField(String name); getDeclaredField(String name);
Method[] getMethods();
getDeclaredMethods()
Method getMethod(String name, Class[] parameterTypes);
Method getDeclaredMethod(String, Class[])
Object[] getSigners(); boolean isAssignableFrom(Class cls);
Transparency No. 55
Essential Java classes
The java.lang.Package class
contain version information about the implementation and
specification of a Java package.
information is retrieved and made available by the classloader
that loaded the class(es).
Typically, it is stored in the manifest that is distributed with the classes.
may contain the specification title, version number, and vendor
strings if the package implement a particular specification.
An application can ask if the package is compatible with a
particular version.
Transparency No. 56
Essential Java classes
The java.lang.Package Method Summary
String getImplementationTitle()
Return the title of this package.
String getImplementationVendor()
Returns the name of the organization, vendor or company that provided this
implementation.
String getImplementationVersion()
Return the version of this implementation.
String getName()
Return the name of this package.
static Package getPackage(String name)
Find a package by name in the caller’s classloader.
static Package[] getPackages()
Get all the packages currently known for the caller's class loader.
String
getSpecificationTitle()
Return the title of the specification that this package implements.
Transparency No. 57
Essential Java classes
The java.lang.Package Method Summary
String getSpecificationVendor()
Return the name of the organization, vendor, or company that owns and
maintains the specification of the classes that implement this package.
String getSpecificationVersion()
Returns the version number of the specification that this package
int
implements.
hashCode()
Return the hashcode computed from the package name.
boolean isCompatibleWith(String desired)
Compare this package's specification version with a desired version.
boolean isSealed()
boolean
Returns true if this package is sealed.
isSealed(URL url)
Returns true if this package is sealed with respect to the specified code
source url.
String toString()
Returns the string representation of this Package.
Transparency No. 58