Skip to content

Instantly share code, notes, and snippets.

@soheil-ghahremani
Last active September 10, 2019 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soheil-ghahremani/ce00a0c8e7490e2f51a1d69f51c12357 to your computer and use it in GitHub Desktop.
Save soheil-ghahremani/ce00a0c8e7490e2f51a1d69f51c12357 to your computer and use it in GitHub Desktop.
Java uses only call by value while passing variables
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;
}
}
@soheil-ghahremani
Copy link
Author

soheil-ghahremani commented Sep 10, 2019

output:

value of a before calling change method: 10
value of a inside change method: 5
value of a after calling change method: 10
 
age of Person b before calling changeValueOfReference method: 20
age of Person b inside changeValueOfReference method: 30
age of Person b after calling changeValueOfReference method: 20

age of Person c before calling changeInnerValue method: 20
age of Person c inside changeInnerValue method: 30
age of Person c after calling changeInnerValue method: 30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment