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

Popular posts from this blog

Design GUI to handle Choice Control event.

Write a Java program that reads an integer number (between 1 and 255) from the user and prints the binary representation of the number. The answer should be printed as a String. Note: The output displayed should contain 8 digits and should be padded with leading 0s(zeros), in case the returned String contains less than 8 characters. For example, if the user enters the value 16, then the output should be 00010000 and if the user enters the value 100, the output should be 01100100 (Hint : You may use String.format() method for the expected output)