java – a = a.trim()和a.trim()之间有什么区别?
我遇到了一点混乱.
我知道String对象是不可变的.这意味着如果我从String类调用一个方法,比如replace(),那么String的原始内容不会改变.相反,将根据原始字符串返回新的String.但是,可以为同一变量分配新值. 基于这个理论,我总是写一个a = a.trim(),其中a是一个String.一切都很好,直到我的老师告诉我,也可以使用a.trim().这搞砸了我的理论. 我和老师一起测试了我的理论.我使用了以下代码: String a = " example "; System.out.println(a); a.trim(); //my teacher's code. System.out.println(a); a = " example "; a = a.trim(); //my code. System.out.println(a); 我得到以下输出: example example example 当我向老师指出时,她说,
请告诉我谁有正确的理论,因为我完全不知道! 解决方法
字符串在java中是不可变的.而trim()返回一个新字符串,所以你必须通过赋值来获取它.
String a = " example "; System.out.println(a); a.trim(); // String trimmed. System.out.println(a);// still old string as it is declared. a = " example "; a = a.trim(); //got the returned string,now a is new String returned ny trim() System.out.println(a);// new string 编辑:
请找一位新的java老师.这完全是一个没有证据的虚假陈述. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |