Last active
September 10, 2019 16:39
-
-
Save soheil-ghahremani/ce00a0c8e7490e2f51a1d69f51c12357 to your computer and use it in GitHub Desktop.
Java uses only call by value while passing variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ir.soheil_gh; | |
public class ParameterPassingTest { | |
public static void main(String[] args) { | |
int a = 10; | |
System.out.println("value of a before calling change method: " + a); | |
change(a); | |
System.out.println("value of a after calling change method: " + a); | |
System.out.println(); | |
Person b = new Person(20); | |
System.out.println("age of Person b before calling changeValueOfReference method: " + b.getAge()); | |
changeValueOfReference(b); | |
System.out.println("age of Person b after calling changeValueOfReference method: " + b.getAge()); | |
System.out.println(); | |
Person c = new Person(20); | |
System.out.println("age of Person c before calling changeInnerValue method: " + c.getAge()); | |
changeInnerValue(c); | |
System.out.println("age of Person c after calling changeInnerValue method: " + c.getAge()); | |
} | |
private static void change(int a){ | |
a = 5; | |
System.out.println("value of a inside change method: " + a); | |
} | |
private static void changeValueOfReference(Person b){ | |
b = new Person(30); | |
System.out.println("age of Person b inside changeValueOfReference method: " + b.getAge()); | |
} | |
private static void changeInnerValue(Person c){ | |
c.setAge(30); | |
System.out.println("age of Person c inside changeInnerValue method: " + c.getAge()); | |
} | |
} | |
class Person{ | |
private int age; | |
public Person(int age) { | |
this.age = age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public int getAge() { | |
return age; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: