Tallan's Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Posts Tagged "Pass by Reference in Java"

Java could be a pain to C# developers (Pass by Reference)

In C++ and C#, developers have freedom to modify variables by directly having access to memory location.
In C++,
#include <stdio.h>
void swapnum(int &i, int &j)
{
int temp = i;
i = j;
j = temp;
}

int main(void)
{
int a = 10;
int b = 20;
swapnum(a, b);
printf(“A is %d and B is %d\n”, a, b);
return 0;
}
In C#,
int a = 1;
modify(ref a); //now a=2
void modify(ref int a)
{
a = 2;
}
In Java, however, there’s no such thing as pass by reference. Even the so-called pointers (created by ‘new’ operator) are passed by copy of the reference.
Thus, if you do the following,
String a…

\\\