Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

public class DPassByValueTest

{
public static void main(String[] args)
{
int number = 8, result;

System.out.println("main method number is: " + number); // 8


result = increment(number); // invoke method with primitive-type parameter

System.out.println("In caller, after calling the method, number is: " + number); // 8

System.out.println("The result is " + result); // 9


}

// Return number + 1
public static int increment(int no)
{
System.out.println("Inside method, before operation, number is " + no); // 8
++no; // change the parameter

System.out.println("Inside method, after operation, number is " + no); // 9


return no;
}
}

// Example - Pass by Reference


import java.util.Arrays; // for Arrays.toString()
public class EPassByReferenceTest
{
public static void main(String[] args)
{
int[] testArray = {9, 5, 6, 1, 4};
/* for (int num : testArray)
{
System.out.println(num);
} */
System.out.println("In caller, before calling the method, array is: "
+ Arrays.toString(testArray)); // [9, 5, 6, 1, 4]

// Invoke method with an array parameter


increment(testArray);

System.out.println("In caller, after calling the method, array is: "


+ Arrays.toString(testArray)); // [10, 6, 7, 2, 5]
}
// Increment each of the element of the given int array
public static void increment(int[] rarray)
{
System.out.println("Inside method, before operation, array is "
+ Arrays.toString(rarray)); // [9, 5, 6, 1, 4]

// Increment each elements


for (int i = 0; i < rarray.length; ++i)
{
++rarray[i];
}

System.out.println("Inside method, after operation, array is "


+ Arrays.toString(rarray)); // [10, 6, 7, 2, 5]
}
}

You might also like