1.

Write A Program To Swap Two Given Strings Without Using Any Third Variable ?

Answer»

FOLLOWING is a program for swapping two strings without using the third variable in Java

1. public class SWAP {

2. public STATIC void MAIN(String args[]) {

3. String a = "Hello";

4. String b = "WORLD";

5. System.out.println("Before swap: " + a + " " + b);

6. a=a+b;

7. b = a.substring(0, a.length() - b.length());

8. a = a.substring(b.length());

9. System.out.println("After swap: " + a + " " + b);

10. } }

Output:

Before swap: Hello world

After swap: world Hello

Following is a program for swapping two strings without using the third variable in Java

1. public class Swap {

2. public static void main(String args[]) {

3. String a = "Hello";

4. String b = "world";

5. System.out.println("Before swap: " + a + " " + b);

6. a=a+b;

7. b = a.substring(0, a.length() - b.length());

8. a = a.substring(b.length());

9. System.out.println("After swap: " + a + " " + b);

10. } }

Output:

Before swap: Hello world

After swap: world Hello



Discussion

No Comment Found