Tom and Jerry found two bags of apples. The bag that Jerry chose contains 5 apples and the bag chosen by Tom has 3 apples. Tom wants to have more apples, so he swaps the bags. Write a program to display the apples in the two bags before and after swapping. Hint :-( Try using call by value and call by reference; Write which can be used to swap)
/* Swap two numbers using Pass by object */
import java.io.*;
import java.util.*;
class Swap_Obj_3A
{
public static void main(String args[])
{
Test te = new Test();
System.out.println("Enter a Value : ");
Scanner s = new Scanner(System.in);
te.a = s.nextInt();
System.out.println("Enter b Value : ");
te.b = s.nextInt();
te.swap(te);
}
}
class Test
{
int a,b,t;
void swap(Test te)
{
System.out.println("Before swapping a = "+te.a+" and b = "+te.b);
t = te.a;
te.a = te.b;
te.b = t;
System.out.println("After swapping a = "+te.a+" and b = "+te.b);
}
}
-----------------------------------------------------------------------------------------------------------------------------
/* Swap two numbers using Pass by value */
import java.io.*;
import java.util.*;
class Swap_Obj_3A2
{
public static void main(String args[])
{
Test te = new Test();
System.out.println("Enter a Value : ");
Scanner s = new Scanner(System.in);
te.a = s.nextInt();
System.out.println("Enter b Value : ");
te.b = s.nextInt();
te.swap(te.a,te.b);
}
}
class Test
{
int a,b,t;
void swap(int a,int b)
{
System.out.println("Before swapping a = "+a+" and b = "+b);
t = a;
a = b;
b = t;
System.out.println("After swapping a = "+a+" and b = "+b);
}
}
Comments
Post a Comment