java中String类型变量的赋值问题介绍

时间:2016-03-23    点击:118   

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

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';
  }
  
}

结果如下:

good
gbc

解说:

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' };
  }
  
}

结果如下:

good
abc

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

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

简述JavaScript提交表单的方式 (Using JavaScript Submit Form)
Angular.js如何从PHP读取后台数据
常用的JQuery函数及功能小结
JS中setTimeout的巧妙用法前端函数节流
AngularJS 让人爱不释手的八种功能
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved