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<args.length; i++) {
// process args[i];
}
// Output a message to the console
System.out.println("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
System.exit(errorCode);
3. Computing Elapsed Time
// Get current time
long start = System.currentTimeMillis();
// Do something ...
// Get elapsed time in milliseconds
long elapsedTimeMillis = System.currentTimeMillis()-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 Collections.sort(), 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);
this.out = out2;
}
public void write(byte buf[], int off, int len) {
try {
super.write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
super.flush();
out.flush();
}
}
Here's an example that uses the class:
try {
// Tee standard output
PrintStream out = new PrintStream(new
FileOutputStream("out.log"));
PrintStream tee = new TeeStream(System.out, out);
System.setOut(tee);
// Tee standard error
PrintStream err = new PrintStream(new
FileOutputStream("err.log"));
tee = new TeeStream(System.err, err);
System.setErr(tee);
} catch (FileNotFoundException e) {
}
// Write to standard output and error and the log files
System.out.println("welcome");
System.err.println("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)myObject.clone();
Arrays are automatically cloneable:
int[] ints = new int[]{123, 234};
int[] intsClone = (int[])ints.clone();
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 = refBoolean.booleanValue();
byte b = refByte.byteValue();
char c = refChar.charValue();
short s = refShort.shortValue();
int i = refInt.intValue();
long l = refLong.longValue();
float f = refFloat.floatValue();
double d = refDouble.doubleValue();
Classes
8. Getting a Class Object
There are three ways to retrieve a Class object.
// By way of an object
Class cls = object.getClass();
// By way of a string
try {
cls = Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
}
// By way of .class
cls = java.lang.String.class;
9. Determining If a Class Object Represents a Class or Interface
Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false
10. Getting the Package of a Class
Class cls = java.lang.String.class;
Package pkg = cls.getPackage();
String name = pkg.getName(); // java.lang
// getPackage() returns null for a class in the unnamed package
cls = MyClass.class;
pkg = cls.getPackage(); // null
// getPackage() returns null for a primitive type or array
pkg = int.class.getPackage(); // null
pkg = int[].class.getPackage(); // 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
buf.append(" Sunny v1/"); // Java Sunny v1/
buf.append(3); // Java Sunny v1/3
// Set
int index = 15;
buf.setCharAt(index, '.'); // Java Sunny v1.3
// Insert
index = 5;
buf.insert(index, "Developers ");// Java Developers Sunny v1.3
// Replace
int start = 27;
int end = 28;
buf.replace(start, end, "4"); // Java Developers Sunny v1.4
// Delete
start = 24;
end = 25;
buf.delete(start, end); // Java Developers Sunny 1.4
// Convert to string
String s = buf.toString();
12. Comparing Strings
String s1 = "a";
String s2 = "A";
String s3 = "B";
// Check if identical
boolean b = s1.equals(s2); // false
// Check if identical ignoring case
b = s1.equalsIgnoreCase(s2); // true
// Check order of two strings
int i = s1.compareTo(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 = s1.compareToIgnoreCase(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 = s1.contentEquals(sbuf); // true
13. Determining If a String Contains a Substring
String string = "Madam, I am san";
// Starts with
boolean b = string.startsWith("Mad"); // true
// Ends with
b = string.endsWith("dam"); // true
// Anywhere
b = string.indexOf("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 = string.indexOf('a'); // 1
// Last occurrence
index = string.lastIndexOf('a'); // 14
// Not found
index = string.lastIndexOf('z'); // -1
// Substrings
// First occurrence
index = string.indexOf("dam"); // 1
// Last occurrence
index = string.lastIndexOf("dam"); // 13
// Not found
index = string.lastIndexOf("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 = string.replace('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 = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
18. Converting a String to Upper or Lower Case
// Convert to upper case
String upper = string.toUpperCase();
// Convert to lower case
String lower = string.toLowerCase();
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 String.valueOf(). The implicit way is to use the string concatenation operator `+'.
// Use String.valueOf()
String s = String.valueOf(true); // true
s = String.valueOf((byte)0x12); // 18
s = String.valueOf((byte)0xFF); // -1
s = String.valueOf('a'); // a
s = String.valueOf((short)123); // 123
s = String.valueOf(123); // 123
s = String.valueOf(123L); // 123
s = String.valueOf(1.23F); // 1.23
s = String.valueOf(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 (s.length() == 0 || !
Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i=1; i<s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
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 = Byte.parseByte("123");
short s = Short.parseShort("123");
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");
double d = Double.parseDouble("123.4e10");
23. Parsing and Formatting a Number into Binary, Octal, and
Hexadecimal
int i = 1023;
// Parse and format to binary
i = Integer.parseInt("1111111111", 2); // 1023
String s = Integer.toString(i, 2); // 1111111111
// Parse and format to octal
i = Integer.parseInt("1777", 8); // 1023
s = Integer.toString(i, 8); // 1777
// Parse and format to decimal
i = Integer.parseInt("1023"); // 1023
s = Integer.toString(i); // 1023
// Parse and format to hexadecimal
i = Integer.parseInt("3ff", 16); // 1023
s = Integer.toString(i, 16); // 3ff
// Parse and format to arbitrary radix <= Character.MAX_RADIX
int radix = 32;
i = Integer.parseInt("vv", radix); // 1023
s = Integer.toString(i, radix); // vv