JAVA:
As we know call by value and call by reference is an important features of c/c++. JAVA eliminate the call by reference features because if security reasons. But still, if we work with JAVA objects, we can use something similar to call by references. Try the following java code snippet:
public static void main(String[] args) {
// TODO code application logic here
A a = new A();
a.a = 1;
changeValue(a);
System.out.println(a.a);
}
public static void changeValue(A obj){
obj.a = 10;
}
public static class A{
public int a;
}
this will print 10. Here it seems like doing call by reference, but actually not. obj object is initiating a new object space where its placing a objects location. By this way, we just having a ways to access and change the properties of a object.
Try with the following example for more understanding:
public static void main(String[] args) {
// TODO code application logic here
A a = new A();
a.a = 1;
changeValue(a);
System.out.println(a.a);
}
public static void changeValue(A obj){
obj = new A();
obj.a = 15;
}
public static class A{
public int a;
}
Now, you will see, output is 1 rather than 15. Because, whenever obj is making a new object its loosing a's location and allocating another space, so now, obj has no effect on a' object.
C#:
Same like JAVA, C# will also doing the same. In addition, its also reserving the reference features. This is accomplished by a 'ref' keyword before the both parameter and argument. Try the following code:
public class A
{
public int x = 10;
}
static void Main(string[] args)
{
A obj = new A();
Change(ref obj);
Console.WriteLine(obj.x.ToString());
Console.ReadLine();
}
public static void Change(ref A obj)
{
obj = new A();
obj.x = 1;
}
Now, its going to print 1 as obj is referring to a's location and creating a new object at the same location.
Hope you have understood this call by value and call by reference features in these two major programming language.
Subscribe to:
Post Comments (Atom)










0 comments:
Post a Comment