java中String类型变量的赋值问题介绍_基础知识

WBOY
Release: 2016-05-16 15:08:18
Original
1740 people have browsed it

运行下面这段代码,其结果是什么?

package com.test; public class Example { String str = new String("good"); char[] ch = { 'a', 'b', 'c' }; public static void main(String[] args) { Example ex = new Example(); ex.change(ex.str, ex.ch); System.out.println(ex.str); System.out.println(ex.ch); } public void change(String str, char ch[]) { str = "test ok"; ch[0] = 'g'; } }
Copy after login

结果如下:

good gbc
Copy after login

解说:

java 中String是 immutable的,也就是不可变,一旦初始化,其引用指向的内容是不可变的(注意:是内容不可变)。

也就是说,假设代码中有String str = “aa”;str=“bb”;,则第二条语句不是改变“aa”原来所在存储地址中的内容,而是另外开辟了一个空间用来存储“bb”;同时由于str原来指向的“aa”现在已经不可达,jvm会通过GC自动回收。

在方法调用时,String类型和数组属于引用传递,在上述代码中,str作为参数传进change(String str, char ch[]) 方法,方法参数str指向了类中str指向的字符串,但str= "test ok"; 语句使得方法参数str指向了新分配的地址,该地址存储“test ok”,而原来的str仍然指向“good”。对于数组而言,在change方法中,方法参数ch指向了类中ch指向的数组,ch[0] = 'g';语句改变了类中ch指向的数组的内容

我们再来看下面这段代码,它的运行结果是什么?

package com.test; public class Example { String str = new String("good"); char[] ch = { 'a', 'b', 'c' }; public static void main(String[] args) { Example ex = new Example(); ex.change(ex.str, ex.ch); System.out.println(ex.str); System.out.println(ex.ch); } public void change(String str, char ch[]) { str = str.toUpperCase(); ch = new char[]{ 'm', 'n' }; } }
Copy after login

结果如下:

good abc
Copy after login

有了前面的解释,这个结果是不是在意料之中?!

以上这篇java中String类型变量的赋值问题介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!