Computer Science, asked by kosugutiaxom, 1 month ago

write a java program to intialize two integer variables a and b with 5 and 6 ,respectively ,and interchange them .Thus after interchanging,a and b will be 6 and 5,respectively​

Answers

Answered by ItzMeSam35
3

//Program Using Only Assigned Value:

import java.util.*;

public class Swapping

{

public static void main (String args [])

{

int a = 5 ;

int b = 6 ;

System.out.println("Before Swapping");

System.out.println(" "+a+" "+b);

System.out.println();

//Swapping

int a = a + b ; // int a = a+b => 5 + 6 = 11

int b = a - b ; // int b = a-b => 11 - 6 = 5

int a = a - b ; // int a = a-b => 11 - 5 = 6

System.out.println("After Swapping");

System.out.println(" "+a+" "+b);

}

}

//Program Using Third Variable:

import java.util.*;

public class Third_Var

{

public static void main(String args [])

{

int a = 5;

int b = 6;

int var ;

System.out.println("Before Swapping");

System.out.println(" "+a+" "+b);

System.out.println();

a = var ;

b = a ;

a = b ;

System.out.println("After Swapping");

System.out.println(" "+a+" "+b);

}

}

Similar questions