Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@soheil-ghahremani 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
You can’t perform that action at this time.