Java Program to Demonstrate the Call By Value
Last Updated :
28 Jan, 2022
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
import java.io.*;
public class GFG {
static void swap( int a, int b)
{
int temp = a;
a = b;
b = temp;
}
public static void main(String[] args)
{
int x = 5 ;
int y = 7 ;
System.out.println( "before swapping x = " + x
+ " and y = " + y);
swap(x, y);
System.out.println( "after swapping x = " + x
+ " and y = " + y);
}
}
|
Output
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
import java.io.*;
class GFG {
static void change( int a)
{
a = a + 50 ;
}
public static void main(String[] args)
{
int a = 30 ;
System.out.println( "before change a = " + a);
change(a);
System.out.println( "after change a = " + a);
}
}
|
Output
before change a = 30
after change a = 30
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...