关于Java的传值和传址问题

package com.jstyle.demo;

import java.util.ArrayList;
import java.util.List;

public class ParaPassingTest {

	public void test1() {
		int[] x = new int[2];
		x[0] = 1;
		x[1] = 2;
		test2(x);
		System.out.println("x[0]=" + x[0]);
		System.out.println("x[1]=" + x[1]);

		int[] xx = new int[2];
		xx[0] = 1;
		xx[1] = 2;
		test3(xx);
		System.out.println("xx[0]=" + xx[0]);
		System.out.println("xx[1]=" + xx[1]);

		int y = 12;
		test4(y);
		System.out.println("y=" + y);

		String str = new String("hello");
		List<String> list = new ArrayList<String>();
		list.add("hello");
		test5(str, list);
		System.out.println("str=" + str);
		System.out.println("list.get(0)= " + list.get(0));

		Integer i = new Integer(5);
		Double d = new Double(78);
		Float f = new Float(45.36);
		Character c = new Character('c');
		test6(i, d, f, c);
		System.out.println("i=" + i);
		System.out.println("d=" + d);
		System.out.println("f=" + f);
		System.out.println("c=" + c);
	}

	public void test2(int[] x) {
		x = new int[2];
		x[0] = 5;
		x[1] = 6;
	}

	public void test3(int[] x) {
		x[0] = 5;
		x[1] = 6;
	}

	public void test4(int y) {
		y = y + 10;
	}

	public void test5(String str, List<String> list) {
		str = "world";
		list.set(0, "world");
	}

	public void test6(Integer i, Double d, Float f, Character c) {
		i = 6;
		d = 789D;
		f = 45.363f;
		c = 'd';
	}

	public static void main(String[] args) {
		ParaPassingTest test = new ParaPassingTest();
		test.test1();
	}
}


前几天遇到一个问题,一个方法中传入了String型的变量str,在方法内修改str的值,但是方法没有返回这个str,而是在调用后直接使用这个str。本以为str的值应该改变,但是实际上没有。可参照以上代码。

在Java中,对象的传递,String和包装类除外,是按址传递。

String和包装类以及基本数据类型,是按值传递。包装类的特质之一是对其值进行操作时会体现出其对应的基本类型的性质。String的存储实际上通过char[]来实现,相当于是char[]的包装类。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值