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
- Example 2: illustrates the swapping of numbers by sum and deletion mathematics computations without creating any auxiliary space.
before swaping x = 5 and y = 7 after swaping 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.
before change a = 30 after change a = 30
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.