call by value and call by reference in java code example
Example 1: call by value and call y refrence in java
public class JavaTester {
public static void main(String[] args) {
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be different here**:");
System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}
public class Tester{
public static void main(String[] args){
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
Example 2: calling by reference and pointers c++
#include <iostream>
using namespace std;
void swap(int&, int&);
int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a, b);
cout << "\nAfter swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int& n1, int& n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}