Java Programming

Swapping

Java example for swapping value of variables using call by reference

9/14/2021
0 views
swapping.javaJava
/* Call by reference */

import java.io.*;

class swap {
	int i, j;

	/* Constructor */
	swap(int a, int b) {
		int c;

		/* Swapping Values */
		c = a;
		a = b;
		b = c;
		i = a;
		j = b;
	}
}

class callbyref {
	public static void main(String args[ ]) {
		int x = Integer.parseInt(args[0]);
		int y = Integer.parseInt(args[1]);
		swap swp = new swap(x, y);
		System.out.println("Before Swapping");
		System.out.println("x = "+x+"\ny = "+y.j);
		System.out.println("After Swapping");
		System.out.println("x = "+swp.i+"\ny = "+swp.j);
	}
}




/* Output */
java callbyref 4 8
Before Swapping
x = 4
y = 8

After Swapping
x = 8
y = 4
Call By ReferenceSwapping valuesJava tutorial

Related Examples