views:

56

answers:

1

I've got a small Java program that I'm developing for a project, which pulls a user's inbox from a specified URI using JavaMail, and then begins processing the messages.

In Outlook, there's a function in the properties menu to set an expiry date for the message, which adds (for example):

Expiry-Date: Thu, 14 Jan 2010 17:00:00 -0000

To the message header.

Retrieving that from the email header is simple using the getHeader(String header) method from javax.mail.Message, and it returns a String[], in which happens to be the part after the colon, tokenised by spaces.

What I want to do is make this String[] into a single String, to later make into a Date. So setting up a simple foreach loop as follows:

String date = "";
for(String part : header){
  date.concat(part);
}
System.out.println(date);

Now for some reason, this code returns an empty string, not entirely sure why, as this should be valid Java.

However, the following code does work, and I don't know why, as it seems illogical to me

String date = "";
for(String part : header){
   date = date + part;
}
System.out.println(date);

Which prints out the correct date. Can someone tell me if this is the correct way of doing this, and if not, what's going wrong with the concat(String append) method?

TIA,

JimiF

+3  A: 

String is immutable. Its internals will never be changed from outside (leaving reflection aside). As per the API docs, the String#concat() returns a new String containing the concatenatred parts, but you're ignoring it. You need to get a handle of it and continue using it in the loop:

String date = "";
for(String part : header){
    date = date.concat(part);
}
System.out.println(date);

That said, your second example can also be shortened to:

String date = "";
for(String part : header){
    date += part;
}
System.out.println(date);

That in turn said, in real world you'd like to use a StringBuilder for this to save the memory, because constructing a new String in a loop isn't cheap if you do this too often:

StringBuilder date = new StringBuilder();
for(String part : header){
    date.append(part);
}
System.out.println(date.toString());
BalusC
+1 Yay for `StringBuilder`! You don't need to call `toString` if calling `PrintWriter` methods; it handles that for you. :-)
Chris Jester-Young
Doh.... Now I feel like an idiot.... I can see what I was doing wrong now. Thanks for the help!
JimiF