Write a Java swap method that could swap values of two integer variables. Do not use any predefined method. Also write a method call that swaps the values of the following two variables.
int first = 7, second = 5;
import java.util.*;
public class Main {
int x,y;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
Main m=new Main();
System.out.println("Enter the value of two
number");
m.x = sc.nextInt();
m.y = sc.nextInt();
System.out.println("first and second number are before swap: "+m.x
+" "+ m.y);
swap(m);
System.out.println("After swap: "+m.x +" " +
m.y);
}
public static void swap(Main m){
int t=m.x;
m.x=m.y;
m.y=t;
}
}
//Main is class name and m is its object
Get Answers For Free
Most questions answered within 1 hours.