MainMenu

Home Java Overview Maven Tutorials

Sunday, 22 April 2018

Swap Two variable in Java


Hello friends,

In this article we will discuss about swap variable without using third variable:

For Video :- Click Here



public class Swap
{
int x = 10;
int y = 15;
public static void main(String args[])
{
Swap object = new Swap();
object.g();
}
public void g()
{
x = x+y;
y = x-y;
x = x-y;
System.out.println("After Swap Value of y : " + y);
System.out.println("After Swap Value of x : " + x);
}
}


output :
After Swap Value of y : 10
After Swap Value of x : 15

Code Explanation : Suppose we have two variable x, y and they have value 10, 15 respectively and we want to swap these two variables value.
HOW IT WOULD BE DONE ?
1). First , i will join these two variables value & store it in variable x.
Now the value of x is 25.
2). Now, we will minus the value of y(15) from this x(25).
we will get 10 & will store in variable y
3). Now the value on y is 10 & value of x is 25.
again we will minus this y value from & store it in variable x so value of variable of x will become 15.

Congratulation You have swapped the value of two variable without using third variable. :)





1. Write a program to swap two string without using any third string/variable

Answer :- First add both the string and store in a existing variable then use String method Substring to get the string


Below is program


public class PracticeA {

public static void main(String args[]) {

String x = "chandan";
String y = "singh";

System.out.println("Value of x: " +x + " , " + "Value of y :" + y + " ," +"before swapping");
x = x+y;

y = x.substring(0, x.length()-y.length());

x = x.substring(y.length());
System.out.println("Value of x: " +x + " , " + "Value of y :" + y + " ," +"after swapping");
}
}



Output :- Value of x: chandan, Value of y :singh ,before swapping Value of x: singh, Value of y :chandan ,after swapping

---------------------------------------------------------------------------




Tags :

Swap two variable without using third variable in Java

how two swap two variable in java without using third variable

No comments:

Post a Comment