layout: post
title: Java String作為參數(shù)的情況
date: 2015-05-28
categories: blog
tags: [Java,String]
category: Java
description: java中的String作為參數(shù)是需要特別的注意.
String是不可以被修改的
一旦String對象創(chuàng)建之后,我們是不能修改他的值的(這里的修改是指在內(nèi)存的同一位置).我們可以從JDK的String類里看到
比如substring()方法
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
在最后,我們發(fā)現(xiàn)他返回的String是重新new的一個對象,而不是在原對象的基礎(chǔ)上修改
基本類型做參數(shù)傳的是值,對象傳遞的是相當(dāng)于引用
傳值是不會導(dǎo)致數(shù)據(jù)的改變的,但是當(dāng)傳遞的是引用,在方法中改變了對象的某字段,會導(dǎo)致方法外部的變量也改變
example:
public class Test {
public int i = 0;
public void chaneg(Test t) {
t.i = 10;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.i);
test.chaneg(test);
System.out.println(test.i);
}
}
output: 0 10
說明在方法內(nèi)改變變量值導(dǎo)致外部改變
但是對于String當(dāng)值的改變是,內(nèi)存地址已改變
則相當(dāng)于下面的example:
public class Test {
public int i = 0;
public void chaneg(Test t) {
t = new Test();//改變內(nèi)存地址
t.i = 10;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.i);
test.chaneg(test);
System.out.println(test.i);
}
}
output: 0 0
也就是說沒有改變外部的值
總結(jié)
當(dāng)在方法中該變量對象的內(nèi)存地址之后,是不會影響外部的值,但是如果只是改變了某字段的值,外部的值會跟著改變.