简体   繁体   English

连接运算符和 concat() 如何执行任何任务

[英]How concatenation operator and concat() performs any task

I can use either concatenation operator (+) or concat() method for string concatenation我可以使用连接运算符(+)concat()方法进行字符串连接

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.但是要将字符串与 integer 连接,我不能直接使用 concat() 。 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但是当我想使用连接运算符和 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 produce String s) always goes through an intermediate StringBuilder (or StringBuffer if targeting old platforms before 1.5 (released 7 (seven) years ago)). 1) +运算符(用于生成String s)始终通过中间StringBuilder (或StringBuffer ,如果针对 1.5 之前的旧平台(7(七)年前发布))。 For concatenating two or perhaps three String s concat will generally be faster due to the lack of intermediate.对于连接两个或三个Stringconcat通常会更快,因为缺少中间体。 However, for longer concatenations + will win because there will be fewer intermediate allocations.但是,对于更长的串联+将获胜,因为中间分配会更少。

2) null generally indicates an error (quite possibly a design error). 2) null一般表示错误(很可能是设计错误)。 In general, errors should be reported as early as possible, which String.concat does.一般来说,应该尽早报告错误, String.concat就是这样做的。 However, + or StringBuilder concatenation is often used to produce debug strings, so the null is tolerated and produces a result suitable for debugging (but not UI.).但是, +StringBuilder连接通常用于生成调试字符串,因此null是可以容忍的,并且会生成适合调试的结果(但不是 UI。)。

There's no difference in the semantics, you just got your example wrong.语义上没有区别,只是你的例子错了。

String myData = "a"+null;              //output =  anull

String myData = "a".concat(String.valueOf( (Object)null ) ); // output = anull

And this will compile and work.这将编译并工作。 + behaves as if String.valueOf() was invoked for every operand. +表现得好像为每个操作数调用了String.valueOf()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM