0

I am currently trying to write code that has a long character array. A requirement is that code should be at most 100 characters long.

For simplicity and readability in this question this requirement is 60 characters

e.g. The would fail

         1        2        3        4        5        6        7
0123467890123467890123467890123467890123467890123467890123467890

private static String s= "dghjkfkfdhkhkjhdfkjhfdkjhdfdfdfddfdfkhd";

One solution is to use the + operator i.e.

         1        2        3        4        5        6        7
0123467890123467890123467890123467890123467890123467890123467890

private static String s = "dghjkfkfdhkhkjhdf" +
                   "kjhfdkjhdfdfdfddfdfkhd";

My gut feeling is that the operator will be executed at run time. Is this true and if so what overheads are incurred?

OR

Is there an alternative mechanism as in C where you can do?

 char s[] = "fjhdfdkjhfk"
            "kjfdhfkjdhkh";

This mechanism does not appear to work in Java

Ed Heal
  • 59,252
  • 17
  • 87
  • 127

1 Answers1

2

First of all, a string literal is not a character array in Java as it is in C, so your code doesn't compile because you can't assign a String object to a variable of type char[]. Fixing that by making the variable a String, then:

When you concatenate string literals with +, the Java compiler is smart enough to do the concatenation at compile time. So whether you break the string literal and concatenate the parts, or keep it as a single string literal, does not matter for the compiled code - the compiled code will be exactly the same.

You can verify this with the javap command. Compile your example class, and then use javap on it. For example: javap -v Example (if your class is named Example). You'll see the string literal in the output as one of the values in the constant pool:

Constant pool:
    ...
    #5 = String             #25            // dghjkfkfdhkhkjhdfkjhfdkjhdfdfdfddfdfkhd

Now change your code to concatenating two string literals, recompile and run javap again. You'll see that the constant pool still contains a single string literal.

You can also use the -c flag with javap to decompile your code; you'll see that there is no difference in the byte code, there will be no string concatenation done at runtime.

Jesper
  • 202,709
  • 46
  • 318
  • 350