You are on page 1of 4

Java Methods: passing

Parameters
Swap program
public class Main {

/**
* @param args the command line arguments
*/

public static void swap(int number1, int number2)


{
System.out.println("Entering swap() method");
int temp=0;
temp = number1;
number1 = number2;
number2 = temp;
System.out.println("In swap() method swapped values are"+number1+" "+number2);
}

public static void main(String[] args) {


System.out.println("Enter 2 numbers:");
Scanner s = new Scanner(System.in);
int number1 = s.nextInt();
int number2 = s.nextInt();
System.out.println("The values of number1 and number2 user entered are:"+number1+"and"+number2);
swap(number1, number2);
System.out.println("After executing swap method");
System.out.println("The value of number1 is:"+number1+" and number2 is: "+number2);

}
}
Swap program
public class Main {

/**
* @param args the command line arguments
*/

public static void swap(int n1, int n2)


{
System.out.println("Entering swap() method");
int temp=0;
temp = n1;
n1 = n2;
n2 = temp;
System.out.println("In swap() method swapped values are"+n1+" "+n2);
}

public static void main(String[] args) {


System.out.println("Enter 2 numbers:");
Scanner s = new Scanner(System.in);
int number1 = s.nextInt();
int number2 = s.nextInt();
System.out.println("The values of number1 and number2 user entered are:"+number1+"and"+number2);
swap(number1, number2);
System.out.println("After executing swap method");
System.out.println("The value of number1 is:"+number1+" and number2 is: "+number2);

}
}
Pass By Value
• In Java primitive variables are always passed by
value. That means, a copy of the variable is
passed into the method.
• If you make a change to the variable within the
method, then that change is not visible
elsewhere.
• In our swap() method, number1 and number2
were passed as parameters. Then they were
swapped. But when we tried printing the values
in our main method after swapping, they weren’t
changed.

You might also like