Java - Lang: 1. The Basic Java Application
Java - Lang: 1. The Basic Java Application
Java - Lang: 1. The Basic Java Application
LANG
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];
}
// An error occurred
errorCode = -1;
// Terminate
System.exit(errorCode);
// Do something ...
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);
System.setErr(tee);
} catch (FileNotFoundException e) {
}
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();
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.
Classes
// By way of a string
try {
cls = Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
}
// By way of .class
cls = java.lang.String.class;
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false
Strings
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();
// Check if identical
boolean b = s1.equals(s2); // false
// Starts with
boolean b = string.startsWith("Mad"); // true
// Ends with
b = string.endsWith("dam"); // true
// Anywhere
b = string.indexOf("I am") > 0; // true
// 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
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');
// 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
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");