为什么在Java中的String.Replace之后String值没有改变? [英] Why isn't the String value changed after String.Replace in Java?

查看:532
本文介绍了为什么在Java中的String.Replace之后String值没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下程序有疑问

请参阅以下程序

public class Kiran {

    public static void main(String args[]) {

        String str = "Test";

        str.replace('T', 'B');

        System.out.println("The modified string is now " + str);
    }

}

我所期待的是,一旦我运行这个程序,我应该看到putput为Best,但令我惊讶的是输出是Test。

What i was expecting is that , once i run this program , i should see the putput as Best , but to my surprise the output was Test .

有人请告诉我,为什么会这样? ?

Could anybody please tell me , why is it this way ??

提前致谢。

推荐答案

字符串在Java中是不可变的,这意味着你无法改变它们。当您调用replace方法时,实际上是在创建一个新的String。

String are immutable in Java, which means you cannot change them. When you invoke the replace method you are actually creating a new String.

您可以执行以下操作:

String str = "Test";
str = str.replace('T', 'B');

这是重新分配。

这篇关于为什么在Java中的String.Replace之后String值没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆