Functions can be summoned in two ways: Call by Value and Call by Reference. Call by Value method parameters values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value where actual value does not change
User cases: Calling methods in programming where the method needs to be called for using its functionality. There can be three situations when a method is called or the method returns to the code that invoked it in conditions depicted below:
- It completes all the statements in the method
- It reaches a return statement
- Throws an exception
Remember: Java is Call By Value always
Implementation: Swapping of numbers is called by value is taken as example to illustrate call by value method
- Example 1: illustrates the swapping of numbers by creating an auxiliary space in memory known as temporary variable
// Java Program showcasing uses of call by value in examples // Importing java input output classes import java.io.*;
// Class public class GFG {
// Method to swap numbers
static void swap( int a, int b)
{
// Creating a temporary variable in stack memory
// and updating values in it.
// Step 1
int temp = a;
// Step 2
a = b;
// Step 3
b = temp;
// This variables vanishes as scope is over
}
// Main driver method
public static void main(String[] args)
{
// Custom inputs/numbers to be swapped
int x = 5 ;
int y = 7 ;
// Display message before swapping numbers
System.out.println( "before swapping x = " + x
+ " and y = " + y);
// Using above created method to swap numbers
swap(x, y);
// Display message after swapping numbers
System.out.println( "after swapping x = " + x
+ " and y = " + y);
}
} |
before swapping x = 5 and y = 7 after swapping x = 5 and y = 7
Output explanation: After calling method swap(5,7), integer values 5 and 7 are got copied into another variable. That’s why original value does not change.
- Example 2: illustrates the swapping of numbers by sum and deletion mathematics computations without creating any auxiliary space.
// Java Program showcasing uses of call by value in examples // Importing java input output classes import java.io.*;
// Class class GFG {
// Method to update value when called in main method
static void change( int a)
{
// Random updation
a = a + 50 ;
}
// Main driver method
public static void main(String[] args)
{
// Random assassination
int a = 30 ;
// Printing value of variable
// before calling change() method
System.out.println( "before change a = " + a);
// Calling above method in main() method
change(a);
// Printing value of variable
// after calling change() method
System.out.println( "after change a = " + a);
}
} |
before change a = 30 after change a = 30