Why is possible to concatenate Char and String in Java?

自古美人都是妖i 提交于 2020-01-11 08:05:38

问题


this is what I've tried;

public String frontBack(String str) {
      char begin = str.charAt(0);
      char end = str.charAt(str.length()-1);
      return begin+str.substring(1,str.length()-1)+end;
}

I've thought it would fail since begin and end are chars but it doesn't. How is that possible? Can anyone explain me please? Thanks!


回答1:


Java's '+' operator also serves as a concatenation operator. It can concatenate primitives and objects and would return you a string which is its result.

The following explanation assumes that you are familiar with Java's wrapper classes. In case you are not familiar with them, please give it a read.

Java's '+' operator converts all the primitive data types used in the statement to their equivalent Wrapper classes and invokes toString() method on those instances and uses that result, which is a string in the expression.

Ex: In Java, a statement like System.out.println( 3 + " Four " + 'C' ); ends up creating a String with the content "3 Four C".

In the above statement, 3 is a primitive int variable. " Four " is a String object and 'C' is a primitive char variable.

During '+' concat operation, 3 gets converted to its corresponding Wrapper class -> Integer. And then toString() method is called on it. Output is String 3 i.e., "3" " Four " is already a String and needs no further processing. 'C' gets converted to Character wrapper class and toString() method results in returning the String "C".

So finally, these three are added so that you get "3 Four C".

To Sum up:

  1. If a primitive is used in '+' operator, it would be converted to its Wrapper class and then toString() method is called on it and the result would be used for appending.
  2. If an object other than String is used, its toString() method would be called and its result would be used for appending.
  3. If a String is called, well, there is not much to do and the string itself gets used for appending.


来源:https://stackoverflow.com/questions/33067516/why-is-possible-to-concatenate-char-and-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!