JAVA.
LANG
1. The Basic Java Application
The parameters to the application are made available in args. This example simply prints
out Hello World!.
public class BasicApp {
public static void main(String[] args) {
// Process each parameter
for (int i=0; i<[Link]; i++) {
// process args[i];
}
// Output a message to the console
[Link]("Hello World!");
}
}
Here's the command to run the program:
> java BasicApp param1 param2 ...
2. Terminating the Application
// No errors
int errorCode = 0;
// An error occurred
errorCode = -1;
// Terminate
[Link](errorCode);
3. Computing Elapsed Time
// Get current time
long start = [Link]();
// Do something ...
// Get elapsed time in milliseconds
long elapsedTimeMillis = [Link]()-start;
// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;
// Get elapsed time in minutes
float elapsedTimeMin = elapsedTimeMillis/(60*1000F);
// Get elapsed time in hours
float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);
// Get elapsed time in days
float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);
4. Implementing a Class That Can Be Sorted
In order for a class to be used in a sorted collection such as a SortedTree or for it to be
sortable by [Link](), the class must implement Comparable.
public class MyClass implements Comparable {
public int compareTo(Object o) {
// If this < o, return a negative value
// If this = o, return 0
// If this > o, return a positive value
}
}
5. Redirecting Standard Output, and Error
This example replaces standard output and error with a print stream that copies its output
to both the console and to a file.
// All writes to this print stream are copied to two print streams
public class TeeStream extends PrintStream {
PrintStream out;
public TeeStream(PrintStream out1, PrintStream out2) {
super(out1);
[Link] = out2;
}
public void write(byte buf[], int off, int len) {
try {
[Link](buf, off, len);
[Link](buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
[Link]();
[Link]();
}
}
Here's an example that uses the class:
try {
// Tee standard output
PrintStream out = new PrintStream(new
FileOutputStream("[Link]"));
PrintStream tee = new TeeStream([Link], out);
[Link](tee);
// Tee standard error
PrintStream err = new PrintStream(new
FileOutputStream("[Link]"));
tee = new TeeStream([Link], err);
[Link](tee);
} catch (FileNotFoundException e) {
}
// Write to standard output and error and the log files
[Link]("welcome");
[Link]("error");
Objects
6. Cloning an Object
class MyClass implements Cloneable {
public MyClass() {
}
public Object clone() {
Cloneable theClone = new MyClass();
// Initialize theClone.
return theClone;
}
}
Here's some code to create a clone.
MyClass myObject = new MyClass();
MyClass myObjectClone = (MyClass)[Link]();
Arrays are automatically cloneable:
int[] ints = new int[]{123, 234};
int[] intsClone = (int[])[Link]();
7. Wrapping a Primitive Type in a Wrapper Object
In the Java language, the eight primitive types --- boolean, byte, char, short, int,
long, float, double --- are not objects. However, in certain situations, objects are
required. For example, collection classes such as Map and Set only work with objects.
This issue is addressed by wrapping a primitive type in a wrapper object. There is a
wrapper object for each primitive type.
This example demonstrates how to wrap the value of a primitive type in a wrapper object
and then subsequently retrieve the value of the primitive type.
// Create wrapper object for each primitive type
Boolean refBoolean = new Boolean(true);
Byte refByte = new Byte((byte)123);
Character refChar = new Character('x');
Short refShort = new Short((short)123);
Integer refInt = new Integer(123);
Long refLong = new Long(123L);
Float refFloat = new Float(12.3F);
Double refDouble = new Double(12.3D);
// Retrieving the value in a wrapper object
boolean bool = [Link]();
byte b = [Link]();
char c = [Link]();
short s = [Link]();
int i = [Link]();
long l = [Link]();
float f = [Link]();
double d = [Link]();
Classes
8. Getting a Class Object
There are three ways to retrieve a Class object.
// By way of an object
Class cls = [Link]();
// By way of a string
try {
cls = [Link]("[Link]");
} catch (ClassNotFoundException e) {
}
// By way of .class
cls = [Link];
9. Determining If a Class Object Represents a Class or Interface
Class cls = [Link];
boolean isClass = ![Link](); // true
cls = [Link];
isClass = ![Link](); // false
10. Getting the Package of a Class
Class cls = [Link];
Package pkg = [Link]();
String name = [Link](); // [Link]
// getPackage() returns null for a class in the unnamed package
cls = [Link];
pkg = [Link](); // null
// getPackage() returns null for a primitive type or array
pkg = [Link](); // null
pkg = int[].[Link](); // null
Strings
11. Constructing a String
If you are constructing a string with several appends, it may be more efficient to construct
it using a StringBuffer and then convert it to an immutable String object.
StringBuffer buf = new StringBuffer("Java");
// Append
[Link](" Sunny v1/"); // Java Sunny v1/
[Link](3); // Java Sunny v1/3
// Set
int index = 15;
[Link](index, '.'); // Java Sunny v1.3
// Insert
index = 5;
[Link](index, "Developers ");// Java Developers Sunny v1.3
// Replace
int start = 27;
int end = 28;
[Link](start, end, "4"); // Java Developers Sunny v1.4
// Delete
start = 24;
end = 25;
[Link](start, end); // Java Developers Sunny 1.4
// Convert to string
String s = [Link]();
12. Comparing Strings
String s1 = "a";
String s2 = "A";
String s3 = "B";
// Check if identical
boolean b = [Link](s2); // false
// Check if identical ignoring case
b = [Link](s2); // true
// Check order of two strings
int i = [Link](s2); // 32; lowercase follows
uppercase
if (i < 0) {
// s1 precedes s2
} else if (i > 0) {
// s1 follows s2
} else {
// s1 equals s2
}
// Check order of two strings ignoring case
i = [Link](s3); // -1
if (i < 0) {
// s1 precedes s3
} else if (i > 0) {
// s1 follows s3
} else {
// s1 equals s3
}
// A string can also be compared with a StringBuffer;
StringBuffer sbuf = new StringBuffer("a");
b = [Link](sbuf); // true
13. Determining If a String Contains a Substring
String string = "Madam, I am san";
// Starts with
boolean b = [Link]("Mad"); // true
// Ends with
b = [Link]("dam"); // true
// Anywhere
b = [Link]("I am") > 0; // true
14. Getting a Substring from a String
int start = 1;
int end = 4;
String substr = "aString".substring(start, end); // Str
15. Searching a String for a Character or a Substring
String string = "madam, i am san";
// Characters
// First occurrence of a c
int index = [Link]('a'); // 1
// Last occurrence
index = [Link]('a'); // 14
// Not found
index = [Link]('z'); // -1
// Substrings
// First occurrence
index = [Link]("dam"); // 1
// Last occurrence
index = [Link]("dam"); // 13
// Not found
index = [Link]("z"); // -1
16. Replacing Characters in a String
Since strings are immutable, the replace() method creates a new string with the
replaced characters.
// Replace all occurrences of 'a' with 'o'
String newString = [Link]('a', 'o');
17. Replacing Substrings in a String
static String replace(String str, String pattern, String replace) {
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();
while ((e = [Link](pattern, s)) >= 0) {
[Link]([Link](s, e));
[Link](replace);
s = e+[Link]();
}
[Link]([Link](s));
return [Link]();
}
18. Converting a String to Upper or Lower Case
// Convert to upper case
String upper = [Link]();
// Convert to lower case
String lower = [Link]();
19. Converting a Primitive Type Value to a String
There are two ways to convert a primitive type value into a string. The explicit way is to
call [Link](). The implicit way is to use the string concatenation operator `+'.
// Use [Link]()
String s = [Link](true); // true
s = [Link]((byte)0x12); // 18
s = [Link]((byte)0xFF); // -1
s = [Link]('a'); // a
s = [Link]((short)123); // 123
s = [Link](123); // 123
s = [Link](123L); // 123
s = [Link](1.23F); // 1.23
s = [Link](1.23D); // 1.23
// Use +
s = ""+true; // true
s = ""+((byte)0x12); // 18
s = ""+((byte)0xFF); // -1
s = ""+'a'; // a
s = ""+((short)123); // 123
s = ""+123; // 123
s = ""+123L; // 123
s = ""+1.23F; // 1.23
s = ""+1.23D; // 1.23
20. Determining If a String Is a Legal Java Identifier
Briefly, a valid Java identifier must start with a Unicode letter, underscore, or dollar sign
($). The other characters, if any, can be a Unicode letter, underscore, dollar sign, or digit.
// Returns true if s is a legal Java identifier.
public static boolean isJavaIdentifier(String s) {
if ([Link]() == 0 || !
[Link]([Link](0))) {
return false;
}
for (int i=1; i<[Link](); i++) {
if ()) {
return false;
}
}
return true;
}
// Some examples
boolean b = isJavaIdentifier("my_var"); // true
b = isJavaIdentifier("my_var.1"); // false
b = isJavaIdentifier("$my_var"); // true
b = isJavaIdentifier("\u0391var"); // true
b = isJavaIdentifier("_"); // true
b = isJavaIdentifier("$"); // true
b = isJavaIdentifier("1$my_var"); // false
Numbers
22. Converting a String to a Number
byte b = [Link]("123");
short s = [Link]("123");
int i = [Link]("123");
long l = [Link]("123");
float f = [Link]("123.4");
double d = [Link]("123.4e10");
23. Parsing and Formatting a Number into Binary, Octal, and
Hexadecimal
int i = 1023;
// Parse and format to binary
i = [Link]("1111111111", 2); // 1023
String s = [Link](i, 2); // 1111111111
// Parse and format to octal
i = [Link]("1777", 8); // 1023
s = [Link](i, 8); // 1777
// Parse and format to decimal
i = [Link]("1023"); // 1023
s = [Link](i); // 1023
// Parse and format to hexadecimal
i = [Link]("3ff", 16); // 1023
s = [Link](i, 16); // 3ff
// Parse and format to arbitrary radix <= Character.MAX_RADIX
int radix = 32;
i = [Link]("vv", radix); // 1023
s = [Link](i, radix); // vv