Archive

Archive for November, 2009

How to write exception stack trace on a String

November 27, 2009 Leave a comment

Sometimes, we have the necessity to transform the exception stack trace in a string (e.g. for using a log method whose parameter is a string).

This is the code I use:

StringWriter sw = new StringWriter();
PrintWriter printWriter = new PrintWriter(sw);
ex.printStackTrace(printWriter);
log.write(sw.toString());
Categories: Uncategorized

When == return true in String comparison?

November 5, 2009 1 comment

In java String objects are pooled for performance issue. There are two different moments during which new strings are inserted into the pool. During compile time, literals are inserted into the pool so you could(but you must not) use == to compare two literals. At runtime, strings aren’t pull back from the pool… So e comparison between a literal value and a runtime value MUST use equals(). To decrease the memory footprint we can use the intern() method, which returns the string from the pool if it exists otherwise it will be inserted.

public class Test {
//to run with a a
public static void main(String[] args) throws Exception{

String literal1 = "a";
System.out.println("arg[0] = " + args[0]);
System.out.println("arg[1] = " + args[1]);
String runtime1 = args[0];
String intern1 = args[1].intern(); //retrieved from pool
String literal2 = "a";
System.out.println("literal1==runtime1: "+(literal1==runtime1)); //false
System.out.println("literal1==literal2: "+(literal1==literal2)); //true
System.out.println("runtime1==intern1: "+(runtime1==intern1)); //false
System.out.println("literal1==intern1: "+(literal1==intern1)); //true
System.out.println("literal1.equals(runtime1): "+(literal1.equals(runtime1))); //true

}
}

http://forums.sun.com/thread.jspa?threadID=669414


Categories: Uncategorized