I can use either concatenation operator(+) or concat() method for string concatenation
String myData = "a"+"b"; // using concatenation operator
String myData = "a".concat("b"); // using concat() of String
But to concate a string with integer I cannot use concat() directly. SO I have to use either of the following logic
String myData = "a"+5;
String myData = "a".concat(String.valueOf(5));
But I found some thing strange in the following line when I want to use concatenation operator and concat
String myData = "a"+null; //output = anull
String myData = "a".concat(String.valueOf(5)); // output = NullPointerException
or
String myData = "a".concat(null); // output = NullPointerException
I have below question arised in my mind
1) How concat() method and concatenation operator works what is the difference in their logic of performing any task?
2) Can we really concat a null using (+) if so why concat() method cannot achieve the same
Thanks
1) The
+operator (to produceStrings) always goes through an intermediateStringBuilder(orStringBufferif targeting old platforms before 1.5 (released 7 (seven) years ago)). For concatenating two or perhaps threeStringsconcatwill generally be faster due to the lack of intermediate. However, for longer concatenations+will win because there will be fewer intermediate allocations.2)
nullgenerally indicates an error (quite possibly a design error). In general, errors should be reported as early as possible, whichString.concatdoes. However,+orStringBuilderconcatenation is often used to produce debug strings, so thenullis tolerated and produces a result suitable for debugging (but not UI!).