Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP EL String concatenation [duplicate]

Tags:

jsp

el

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

like image 576
Kyle Avatar asked Jul 06 '10 19:07

Kyle


People also ask

How do you concatenate 2 strings?

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.

Why is string concatenation 2?

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.

Why is string concatenation in a loop bad?

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.

Is StringBuilder better than concatenation?

It is always better to use StringBuilder. append to concatenate two string values.


1 Answers

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"))} 
like image 80
Mike Haefele Avatar answered Oct 13 '22 05:10

Mike Haefele