This question already has an answer here:

Following is my code:

 class program{

    public static void main(String[]args){

    String str = new String("I like Java ");
    str.concat("the most");
    str.toUpperCase();
    str.replace("LIKE","LOVE");
    System.out.println(str);

        }
   }

As I expect the output should be as:

I LOVE JAVA THE MOST

But, It isn't showing an error but also not showing the expected output...Instead it is only showing the original string:

cmd screen

Am I missing something or may be is it something else?

marked as duplicate by Jeroen Vannevel, Robby Cornelissen, home, Óscar López java Aug 10 '14 at 13:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 6
    Strings are immutable. – Jeroen Vannevel Aug 10 '14 at 13:46
  • PS 'new String' is not needed. Do String str = "I like Java" instead. – Erik Pragt Aug 10 '14 at 13:48
  • @JeroenVannevel what is meant by immutable? as far as I know strings are taken as object in java. – Krupal Shah Aug 10 '14 at 13:48
  • @krupalshah: that's when you use google. I just gave you the term 2 minutes ago, I don't think you have read up on it yet. – Jeroen Vannevel Aug 10 '14 at 13:49
  • 2
    @krupalshah: that doesn't make it any less of a duplicate. Don't take it personally but do take it as a sign that you should refine your searching before you ask a question. For example when I google for "java string doesn't change" I get the answer in each of the first few results. – Jeroen Vannevel Aug 10 '14 at 13:55
up vote 4 down vote accepted

The String class is immutable. This means that every method does not change the original String instance, but it creates a new object and returns it, but you are not saving their reference. You could do:

String str = "I like Java";
str = str.concat("the most");
str = str.toUpperCase();
str = str.replace("LIKE","LOVE");

Or even better:

String str = "I like Java"
    .concat("the most")
    .toUpperCase()
    .replace("LIKE","LOVE");

This works because the methods are returning new String objects, so you can concatenate them.

Now when you use System.out.println(str); the result will be I LOVE JAVATHE MOST (because you forgot the space when concatenating the two strings).

The line:

str.replace("LIKE","LOVE"); 

returns a String that holds the answer that you want, which you throw away. One easy fix is to change the last line:

System.out.println(str.concat("the most").toUpperCase().replace("LIKE","LOVE"));

and delete the useless calls above it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.