Talking more about primitive and reference variables as method parameter in Java

You have been learning about the primitive variable in Java in this tutorial and this tutorial, the reference variable in this tutorial. In this tutorial, we will learn more about these two types of variables when they are passed to a method in the form of parameters.

Passing the primitive variable into a method

When we pass a primitive variable to a method, its value is copied and passed to that method. This means that the value of this primitive variable will not change at the end of the execution of the method, although it is possible that during the execution of this method we will change its value.

Consider the following example code:

Result:

In this example, we passed for the increase() method in the Example class a primitive n type of int. This method has increased the value of the primitive variable that we pass into. But obviously you see, the value of the number variable in the Example object does not change after being passed to the increase() method.

Passing the reference variable to a method

Assume, I have class Student with the following content:

Now we will make an example to use this Student object in a method like this:

In the above example, I used the Student object in a swap() method with the intention of swapping references of two variables. Take a look at the following:

As you can see, the reference to the student1 and student2 variables is still unchanged after the swap() method is executed.

But if you change the state of the Student object, please consider the following example.

Result:

You see, if you change the state of the object, after the method is executed, the state of the object will change.

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment