toUpperCase in Java does not work

后端 未结 5 1463
星月不相逢
星月不相逢 2020-11-28 15:27

I have a string:

String c = \"IceCream\";

If I use toUpperCase() function then it returns the same string, but I want to get <

相关标签:
5条回答
  • 2020-11-28 15:46

    The code

    String c = "IceCream";
    String upper = c.toUpperCase();
    System.out.println(upper);
    

    correctly prints "ICECREAM". However, the original string c isn't changed. Strings in Java are immutable so all operations on the string return a new copy.

    0 讨论(0)
  • 2020-11-28 15:46

    Are you expecting the original variable, c, to have been changed by toUpperCase()? Strings are immutable; methods such as .toUpperCase() return new strings, leaving the original un-modified:

    String c = "IceCream";
    String d = c.toUpperCase();
    System.out.println(c); // prints IceCream
    System.out.println(d); // prints ICECREAM
    
    0 讨论(0)
  • 2020-11-28 15:52

    It could be a problem with your locale. Try:

    String c = "IceCream";
    return c.toUpperCase(Locale.ENGLISH);
    
    0 讨论(0)
  • The object can't be changed, because String is immutable. However, you can have the reference point to a new instance, which is all uppercase:

    String c = "IceCream";
    c = c.toUpperCase();
    
    0 讨论(0)
  • 2020-11-28 15:57

    You're supposed to use it like this:

    String c = "IceCream";
    String upper_c = c.toUpperCase();
    
    0 讨论(0)
提交回复
热议问题