Java: Why-oh-why still no multi-line strings?

Over the last year or two I’ve been doing a lot of PHP (which I really like).One of the things I use a lot is heredoc syntax eg:

$query = <<<END
FROM tablename
WHERE condition1 = $field
AND condition2 = 345

This is much more convenient than, say:

String query =
  "SELECT * " + // MUST remember to put a space here!
  "FROM tablename " +
  "WHERE condition1 = " + field + " " + 
  "AND condition2 = 345";

I’ve been doing quite a bit of Java recently and it’s really starting to bug me. I don't understand why pretty much every other imperative language invented in the last 15 years can have some form of multi-line string syntax but Java still doesn’t.

Java 6 was released over three years ago. Java 7—thanks largely to the unexpected (yet welcome) inclusion of closures—isn’t due for nearly another year. Four years between releases.

Surely Java could have gotten something in that time. Even if it’s the rather ugly (imho) triple-quote syntax of Scala/Groovy it’d be better than nothing.

Anyway, I just needed to get that out.

Happy New Year for 2010.


Fred Blasdel said...

In your concatenative example, you should use in-string indentation on lines 1..n instead of trailing spaces on lines 0..n-1!

Something I often do when declaring literal arguments / lists / dictionaries / etc. is to put each element on its own line with an aligned leading comma, with the first item lead by the open-bracket. It's legal in Python but not in Ruby...

Anonymous said...

It depends what you are doing. If it is writing queries then query externalisation is something that should be natively supported by the query API such as JDBC or Spring. Writing queries in code or strings makes it a maintenance and testing nightmare. If it is other non-query related strings then depending on the case this can also be externalised. Still I see your point. It would be nice to have. Maybe this can be done in Scala within Java :-)

Nathan Crause said...

That's a fairly good question, I think. To be fair, though, it does make it a lot easier to spot when you haven't closed your string correctly (something which doesn't report so well in other languages, if I recall). Sort of a toss up, I'd say. I imagine it might just be because of the C/C++ heritage (they don't support multi-line strings, either). I honestly couldn't think of a technical reason why it couldn't be supported.

This isn't really a huge issue for me, because using NetBeans, ending a line with an open string automatically does the '" + ' business for you. Doesn't help in the "ugly" department, but it's something anyway.

Scott Schulthess said...

Seriously, this is why java kind of bites.

I prefer c# where you can just do String sql = @"BLAHBLABHALJ



And it just works.

Post a Comment