2

What is the best practice to declaring a long string in java? Should I use:

static final String MY_STRING = "my very very long string that spans a more than a page.";

or

static final String MY_STRING = "my very very long string "
    + "that spans more than a page.";

Is there any performance hit for one or the other? What if this were not a static final and the declaration were in a method. I know this should be a really easy question for some of you guys.

simgineer
  • 1,754
  • 2
  • 22
  • 49
  • 4
    Nope. They are concatenated at compile time. – Gurwinder Singh Jul 07 '18 at 02:35
  • It's an impossible question because there's no one correct answer. Do whatever you think reads better. Or follow your company's standards. – shmosel Jul 07 '18 at 02:35
  • 2
    @shmosel - There is an answer; he's asking if there is a performance hit for doing it this way. The answer is no, unless you are also doing it this way with variables. In that case, there is a slight performance hit with concatenating strings. If it becomes a long string, its best to use a `StringBuilder`. But you likely would not notice much of a difference, if any, either way. – Zephyr Jul 07 '18 at 02:38
  • @Zephyr It's not clear whether the question was primarily about best practice or performance. I went with the former. – shmosel Jul 07 '18 at 02:40
  • 1
    The other question didn't come up in my search. Thank you for pointing out that duplicate question. Looks like because my string is a constant making it readable is the right way to go because the compiler will optimize the performance for us. You guys rock, again Thank you! – simgineer Jul 07 '18 at 02:48
  • 1
    @simgineer That's a pretty general rule: The compiler optimizes a lot and usually, you don't have to care. Write readable code using small methods, that's what the compiler (and you colleagues) love most. – maaartinus Jul 18 '18 at 11:30

0 Answers0