值传递引用传递java_Java严格按值传递

值传递引用传递java

In Java, it is very confusing whether java is pass by value or pass by reference.

在Java中,是按值传递还是按引用传递Java,这非常令人困惑。

When the values of parameters are copied into another variable, it is known as pass by value and when a reference of a variable is passed to a method then it is known as pass by reference.

将参数的值复制到另一个变量中时,称为按值传递;当将变量的引用传递至方法时,则称为按引用传递。

It is one of the feature of C language where address of a variable is passed during function call and that reflect changes to original variable.

它是C语言的功能之一,在函数调用期间传递变量的地址,并反映对原始变量的更改。

In case of Java, we there is no concept of variable address, everything is based on object. So either we can pass primitive value or object value during the method call.

在Java的情况下,我们没有变量地址的概念,一切都基于对象。 因此,我们可以在方法调用期间传递原始值或对象值。

Note: Java is strictly pass by value. It means during method call, values are passed not addresses.

注意: Java严格按值传递。 这意味着在方法调用期间,值传递的不是地址。

例: (Example:)

Below is an example in which value is passed by value and changed them inside the function but outside the function changes are not reflected to the original variable values.

下面是一个示例,其中按值传递值并在函数内部对其进行更改,但在函数外部对其进行更改不会反映到原始变量值。

class Add
{ 
	int x, y; 
	Add(int i, int j) 
	{ 
		x = i; 
		y = j;
	}  
} 
class Demo
{ 
	public static void main(String[] args) 
	{ 
		Add obj = new Add(5, 10); 
		// call by value
		change(obj.x, obj.y);
		System.out.println("x = "+obj.x); 
		System.out.println("y = "+obj.y);
		
	} 
	public static void change(int x, int y) 
	{  
		x++;
		y++;
	} 
}

x = 5 y = 10

x = 5 y = 10

Lets take another example in which an object is passed as value to the function, in which we change its variable value and the changes reflected to the original object. It seems like pass by reference but we differentiate it. Here member of an object is changed not the object.

让我们再举一个例子,其中将一个对象作为值传递给函数,在其中我们更改其变量值,并将更改反映到原始对象。 似乎是通过引用,但我们对其进行了区分。 在这里,对象的成员被更改,而不是对象。

例: (Example:)

Below is an example in which value is passed and changes are reflected.

下面是一个传递值并反映更改的示例。

class Add
{ 
	int x, y; 
	Add(int i, int j) 
	{ 
		x = i; 
		y = j;
	}  
} 
class Demo
{ 
	public static void main(String[] args) 
	{ 
		Add obj = new Add(5, 10); 
		// call by value (object is passed)
		change(obj);
		System.out.println("x = "+obj.x); 
		System.out.println("y = "+obj.y);
		
	} 
	public static void change(Add add) 
	{  
		add.x++;
		add.y++;
	} 
}

6 11

6 11

翻译自: https://www.studytonight.com/java/java-is-strictly-pass-by-value.php

值传递引用传递java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值