June 28th, 2006

Making System.out.println() return a String

At some point, recently, I needed to do both of these things in one little Java expression:
- output a String to stdout
- return the same String

System.out.println() returns ‘void’, and you can’t cast void to String, so I struggled with this for a little while. Here’s what I came up with (download here if it looks ugly in the blog):

public class VoidToString
{
public static void main(String[] args)
{
System.out.println(”returned value: [” +
new Object()
{
public String q(String p)
{
System.out.println(”stdout: [” + p + “]”);
return p;
}
}.q(”blah”) + “]”);
}
}


It ended up not working in the context I was trying to use it in, because the 3rd-party API I was using did not appreciate the inner class, but I still thought it was a neat little trick.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>