15

I have a string:

String c = "IceCream";

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

Where is the problem?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
user1091510
  • 247
  • 2
  • 4
  • 8

5 Answers5

34

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.

Andreas Wederbrand
  • 38,065
  • 11
  • 68
  • 78
  • See also http://stackoverflow.com/questions/22397861/why-is-string-immutable-in-java – Raedwald Jul 21 '14 at 13:08
  • You could also just reassign the variable **String c = "IceCream"; c = c.toUpperCase();** This should be included in the accepted answer. – ViaTech Apr 29 '18 at 16:07
13

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
Shantha Kumara
  • 3,272
  • 4
  • 40
  • 52
smendola
  • 2,273
  • 1
  • 15
  • 14
10

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();
Grzegorz Rożniecki
  • 27,415
  • 11
  • 90
  • 112
Zohaib
  • 7,026
  • 3
  • 26
  • 35
3

You're supposed to use it like this:

String c = "IceCream";
String upper_c = c.toUpperCase();
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 2
    an alternative would also be `String c = "IceCream".toUpperCase();` –  Dec 11 '11 at 14:51
1

It could be a problem with your locale. Try:

String c = "IceCream";
return c.toUpperCase(Locale.ENGLISH);
Zwade
  • 1,682
  • 4
  • 17
  • 28