Friday 27 March 2015

PROGRAM 13 : TO ACCEPT TWO DIFFERENT STRINGS AND SWAP THE VALUES WITHOUT USING THE CALL BY VALUE OR CALL BY REFERENCE MECHANISM.

(Swapping values means to interchange values of two different variables with each other.)

Example:


PROGRAM :

import java.util.Scanner;
public class swappingstrings
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first string S1:");
        String s1 = sc.nextLine();
        s1 = s1.trim(); // REMOVES ALL EXTRA SPACES BEFORE AND AFTER THE STRING
        int len = s1.length();
        System.out.println("Enter the second string S2:");
        String s2 = sc.nextLine();
        s2 = s2.trim();
        System.out.println("------------------------------------------------");
        System.out.println("Value of s1 before swapping: " + s1);
        System.out.println("Value of s2 before swapping: " + s2);
        System.out.println("------------------------------------------------");
        s1 = s1 + s2; // WE ARE JOINING BOTH THE STRINGS
        s2 = s1.substring(0 , len); // USING STRING METHOD TO EXTRACT A PARTICULAR PART OF STRING
        s1 = s1.substring(len); // TO EXTRACT THE REMAINING PART.
        System.out.println("------------------------------------------------");
        System.out.println("Value of s1 after swapping: " + s1);
        System.out.println("Value of s2 after swapping: " + s2);
        System.out.println("------------------------------------------------");
    }
}

No comments:

Post a Comment