-2

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?

10
  • 6
    Strings are immutable. Commented Aug 10, 2014 at 13:46
  • PS 'new String' is not needed. Do String str = "I like Java" instead. Commented Aug 10, 2014 at 13:48
  • @JeroenVannevel what is meant by immutable? as far as I know strings are taken as object in java. Commented Aug 10, 2014 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. Commented Aug 10, 2014 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. Commented Aug 10, 2014 at 13:55

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.