0

I have an object called MyDate and it return three methods String getDay(), String getYear(), String getMonth()

For example Sep 24 2013 will 2013, 24, 9 .. I want to join these three strings using a common separator which is DASH "-". How do I join without using StringBuilder or "+" operator ? What would be the most compact code form ?

For e.g I know I can do this but is there a more compact form ? Because I know + operator is expensive.

MyDate myDate = new MyDate();
myDate.getYear()+"-"+myDate.getMonth()+"-"+myDate.getDay();
2
  • You don't want to use + or StringBuilder? Commented Sep 25, 2013 at 0:54
  • I'd say use a StringBuilder, but you exluded that. How come? Commented Sep 25, 2013 at 0:55

4 Answers 4

2

You could use String.format(...)

For example, if your getXXX() methods return a Strings:

String dateStr = String.format("%s-%s-%s", 
      myDate.getYear(), myDate.getMonth(), myDate.gateDay());

Else if they return an int:

String dateStr = String.format("%4d-%02d-%02d", 
      myDate.getYear(), myDate.getMonth(), myDate.gateDay());

For more on this, check out any tutorial on the printf(...) method or the Formatter object.

Sign up to request clarification or add additional context in comments.

Comments

2

You can be cool and use Guava

public static void main(String[] args) {
    Date myDate = new Date();
    Object[] objects = new Object[] {
            myDate.getYear(), myDate.getMonth(), myDate.getDay()
    };
    String message = Joiner.on("-").join(objects);
    System.out.println(message);
}

4 Comments

One suspects that Guava uses StringBuilder.
@user949300 Yeah, but it's hidden!
I like your solution, or the Apache commons suggestions, assuming that OP is already using them in his codebase.
Wish Joiner.on("-").join(objects); was named Joiner.join(objects).using("-");
2

If you're not opposed to using Apache commons.

StringUtils#join

Comments

0

If you can use apache commons then String concatenate(Object[] array) would be perfect. You can give your strings in one go :

StringUtils.concatenate([myDate.getYear(), myDate.getMonth(), myDate.gateDay()])

More info here : http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

1 Comment

Don't you need a separator somewhere in there? Also that method is deprecated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.