Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toUpperCase in Java does not work

Tags:

java

string

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?

like image 363
user1091510 Avatar asked Dec 11 '11 14:12

user1091510


2 Answers

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.

like image 179
Andreas Wederbrand Avatar answered Oct 20 '22 18:10

Andreas Wederbrand


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
like image 41
smendola Avatar answered Oct 20 '22 19:10

smendola