Pass by value vs Pass by reference in JAVA
Theory:
Java is strictly pass-by-value. In Java, you can't directly pass variables by reference as you would in languages like C/C++. However, you can achieve a similar effect by passing an array or an object reference.
Code:
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
//Pass by value example in JAVA
System.out.println("PASS by value example in JAVA");
int n = 1;
passByValue(n);
System.out.println(n); // You can see O/P of n is unmodified by passByValue func
System.out.println("PASS by reference example in JAVA");
// Pass by reference example in JAVA
int num[] = new int[1];
num[0] = 10;
doSomething(num); // Passing the array reference
System.out.println(num[0]); // Print the modified value
}
// Pass by value example in JAVA
public static void passByValue(int num)
{
num = num + 10;
System.out.println(num);
}
// Pass by reference example in JAVA
public static void doSomething(int num[]) {
num[0] = num[0] + 10;
System.out.println(num[0]);
}
}
No comments:
Post a Comment