当前位置: 动力学知识库 > 问答 > 编程问答 >

Different behavior between String.value0f and Character.toString in Java

问题描述:

In the following example, this program snippet does not compile, but if we replace the method Character.toString(char) by String.valueOf(char), everything is fine. What is the issue why Character.toString here ? In the documentation, these methods seem to have the same behavior. Thanks for explanation.

 public static void main (String args[]) {

String source = "19/03/2016 16:34";

String result = Character.toString(source.substring(1,3));

System.out.print(result);

}

网友答案:

Character.toString(char c) method accepts char value as an argument and you are passing a String class instance which is produced from source.substring(1,3) method. String and char are incompatible types, so compiler can't create correct method call and pass the value

Your code should be rewritten as:

public static void main (String args[]) {
    String source = "19/03/2016 16:34";
    String result = source.substring(1, 3);
    System.out.print(result);
    //equivalent to the previous System.out.println call
    System.out.print(source.substring(1, 3));
}

Also note that the first substring argument is an inclusive start index, the second one is exclusive end index and the leading index in Java String is 0 (not 1) exactly like in arrays (which is not a coincidence - String characters are stored in char array). So if you want to get a "19" String you should write source.substring(0, 2)

网友答案:

What does the compiler error message say? Anyway, source.substring(1,3) gives you a String while Character.toString() needs a char and does not accept a String.

String.valueOf(source.substring(1,3)) would call String.valueOf(Object), not String.valueOf(char).

You may obtain the same even simpler:

String result = source.substring(1,3);
分享给朋友:
您可能感兴趣的文章:
随机阅读: