How do I concatenate strings in EL?
I want to do something like this but it doesn't work:
${var1 == 0 ? 'hi' : 'hello ' + var2}
It throws an exception trying to cast 'hello'
to a Double
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
String concatenation It can be a bit surprising, but this code actually runs in O(N2) time. The reason is that in Java strings are immutable, and as a result, each time you append to the string new string object is created. The loop in the code does 1 + 2 + 3 + ... + N = N * (N + 1) / 2 = O(N2) operations.
Avoid using the + and += operators to accumulate a string within a loop. Since strings are immutable, this creates unnecessary temporary objects and results in quadratic rather than linear running time.
It is always better to use StringBuilder. append to concatenate two string values.
Using java string concatenation works better.
#{var1 == 0 ? 'hi' : 'hello'.concat(var2)}
The benefit here is you can also pass this into a function, for instance
#{myCode:assertFalse(myVar == "foo", "bad myVar value: ".concat(myVar).concat(", should be foo"))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With