Menu

How to swap two variable without using temporary variable in java?

Swap two integer variable a and b without using any temporary variable.
Set the initial value for two variable and then swap the value from a to b and b to a. Below is the code snippet written in Java programming to swap two variable without using third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package jorvee;

public class SwapTwoIntegerVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  int a=5, b=3;
  System.out.println("Before swap value of a: "+a +" and value of b: "+b);
  a = a*b;
  b = a/b;
  a = a/b;
  System.out.println("After swap value of a: "+a +" and value of b: "+b);
 }
}

Output:

Before swap value of a: 5 and value of b: 3
After swap value of a: 3 and value of b: 5

Another approach to do the same. Swap two variable without using third variable

How to swap two Integer variables without using the third variable?

Swap two integer variable a and b without using any temporary variable.
Set the initial value for two variable and then swap the value from a to b and b to a. Below is the code snippet written in Java programming to swap two variable without using third variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package jorvee;

public class SwapTwoIntegerVariableWithoutUsingTheThirdVariable {

 public static void main(String[] args) {
  int a=5, b=3;
  System.out.println("Before swap value of a: "+a +" and value of b: "+b);
  a = a+b;
  b = a-b;
  a = a-b;
  System.out.println("After swap value of a: "+a +" and value of b: "+b);
 }
}

Output:

Before swap value of a: 5 and value of b: 3
After swap value of a: 3 and value of b: 5

Another approach to do the same. Swap two variable without using third variable 

regex to match only number with n digit



^[0-9]*$



import java.util.regex.Matcher; import java.util.regex.Pattern; final String regex = "^[0-9]*$"; final String string = "12333\n" + "sgd123\n" + "sefgwer46546\n" + "486464se\n" + "486464545656"; final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); final Matcher matcher = pattern.matcher(string); while (matcher.find()) { System.out.println( System.out.println( System.out.println("Full match: " + matcher.group(0)); for (int i = 1; i <= matcher.groupCount(); i++) { System.out.println( System.out.println( System.out.println("Group " + i + ": " + matcher.group(i)); } }