[For beginners] An article that makes you understand 5000 trillion% of Java's complicated "passing by reference"

Hello. We will make a slimy Qiita debut.

This article is a revised version of what was previously left in the sea of the Internet under another name and another medium. Please prepare coffee and go out with us.

Target readers of this article

--Java beginner --People who want to review Java --People who want to review passing by value and passing by reference

I will write it for those who have a minimum knowledge of basic Java, but there is no problem even if you read the Java-specific description appropriately.

Introduction

Isn't it difficult to pass Java references in the first place? Overall, I don't think it's that difficult, but there are some who behave obviously strangely, even though beginners can't avoid it.

Yes, ** Stiring type **. You are you.

honestly speaking, "String type can be treated the same as basic type (like int)" "But when comparing, use .equals () instead of ==" Even the recognition is quite good.

However, it feels unpleasant to think calmly, isn't it?

ex0


	public static void main(String[] args) {
		String str1 = "String 1";
		translate(str1);
		System.out.println(str1);//String 1
	}
	private static void translate(String str2) {
		str2 = "String 2";
	}

In Java, objects other than basic types are objects (inheriting the Object class). And the String type is not the basic type. It is an object. The object is passed by reference. That means that it is strange if the output is not "character string 2", isn't it?

If you understand why "string 1" is printed here, you probably don't need this article. "Because the String type is like a basic type" is ... correct but incorrect. sorry.

In this article, I would like to explain ** "what is happening" ** for beginners (those who understand the meaning of instances).

As a matter of fact, many people who understand Java to some extent will want to say, "Since the String type is immutable, this is just the case" or "Java is all passed by reference in the first place!". However, I think it will be a heavy burden for beginners.

As long as there is a fairly broad explanation of Java that conforms to the concepts of "passing by value" and "passing by reference", it is useless to understand "what each of" passing by value "and" passing by reference "wants to say when learning Java for the time being." Wouldn't be. So let's go.

Basics in the basics: In the case of "passing by value"

It's the basic of the basics, but let's check it.

ex1


	public static void main(String[] args) {
		int num_sender = 1;
		add(num_sender);
		System.out.println(num_sender);//It's 1
	}

	private static void add(int num_receiver) {
		num_receiver += 1;
	}

The recommended way to remember it is ** "Num_sender's number" 1 "in your head is" written on a white card "and handed over to the add () method" **.

Write the numbers in your head on the card and give it to you.

No matter what the add () method does, the numbers in num_sender's head will not change. However, in this case ...

ex2


	public static void main(String[] args) {
		int num_sender = 1;
		num_sender = add(num_sender);
		System.out.println(num_sender);//It's 2
	}

	private static int add(int num_receiver) {
		num_receiver += 1;
		return num_receiver;
	}

The output is "2" because num_sender is explicitly instructed to ** "Remember the changed numbers !!!" **. Well of course.

Some may think it's too easy, but stay tuned to the end. It will be effective later.

Basic 2: By reference

ex3


	public static void main(String[] args) {
		List<String> onlyOneList = new ArrayList<String>();
		onlyOneList.add("2018");
		replaceFirstItemTo2019(onlyOneList);
		System.out.println(onlyOneList.get(0));//"2019"
	}

	//The first element of the list will be 2019
	private static void replaceFirstItemTo2019(List<String> another_hensu) {
		another_hensu.add(0, "2019");
	}

I tried to make the variable name a bit vulgar, but for the time being, imagine that the often-called passing by reference is "manipulating only one object (object)".

However, if you still feel uncomfortable, think this way. The contents of the variable "onlyOneList-kun" are ** taking a nap in room 20 of the luxury hotel "memory". ** ** ** Room 20 was somehow decided when I did new ArrayList () ;. ** **

…… I wrote it lightly, but it's a very important place, so please remember it. ………… Is it really important? Did you say that?

That being said, what is being passed to the replaceFirstItemTo2019 () method "Room 20" That's the information.

So, in the replaceFirstItemTo2019 () method, the first element of the only one List who is sleeping in Room 20 is rewritten to "2019." The information that is finally output is the information rewritten to "Room 20 information", that is, "It's 2019".

This is what the Java chotdexers call "passing by reference". What is the difference between "reference" and "reference value" here? If you think ... Forget it because there is not enough space.

Well, the review is over. It is a little application from here.

This is difficult, isn't it Java

Please read this code.

ex_4


	public static void main(String[] args) {
		List<String> onlyOneList = new ArrayList<String>();
		onlyOneList.add("2018");
		replaceFirstItemTo2019(onlyOneList);
		System.out.println(onlyOneList.get(0));//"2018"
	}

	//The first element of the list will be 2019
	private static void replaceFirstItemTo2019(List<String> another_hensu) {
		another_hensu = new ArrayList<String>();
		another_hensu.add(0, "2019");
	}

Nande is still 2018! ?? ?? ?? ** No more ... it's over **

There are times when you do this in practice without a joke. Let's be careful!

This is the only line that I rewrote from the previous example.

another_hensu = new ArrayList<String>();

But this is a mess and a serious thing. Remember what I wrote earlier.

The content of the variable "onlyOneList-kun" is a luxury hotel"memory"I'm taking a nap in Room 20.
Room 20 is the new Array List<String>();Somehow it was decided when I did.

In other words, what new is doing is ** "allocate a bedroom in a hotel (memory) and then create a new thing (object)" **. Here, "room 21" or some other room number different from room 20 is assigned to the contents of "anothe_hensu-kun", and then a new List is born. And the information recorded by the variable "onlyOneList-kun" remains "Room 20". To make matters worse, List is no longer the only one at this point!

So, "2019 is 2019" is stored in the List of "Room 21", but there is no change in the List of "Room 20" which is the information held by "onlyOneList-kun", and it is "2018" as it is. "Is output. ...... That is.

For String type

If you have read this far, you can understand it.

ex0


	public static void main(String[] args) {
		String str1 = "String 1";
		translate(str1);
		System.out.println(str1);//String 1
	}
	private static void translate(String str2) {
		str2 = "String 2";
	}

In this code, the String type is certainly an "object" and is passed "pass by reference".

But the String type is "immutable". ……What do you mean Ya? It means that you can't mess with the object directly.

……

**……What do you mean Ya! ?? Be sharp! !! ?? ** **

First, as a premise, in the case of String, "exceptionally"


String str1 = "String 1";

With this description alone, a String type object is "born and stored in a suitable room in the luxury hotel" memory "". Let's say you were born in "Room 22" this time.

I will change the writing style again.

(String)Variable name= "hoge";

** With this description alone, a String type object is "born and stored in a suitable room in the luxury hotel" memory "". ** **

What does that mean?

str2 = "String 2";

At the time of writing this, "Room 23" (I don't know if it's Room 24 or 5000 trillion, but anyway, it's in another room other than Room 22) was born. Then, how to change the "character string 1" sleeping in "Room 22" ...! ??

** There is no such thing. ** ** That's too bad. Let's give up. After all, this means "String type is immutable" or "Object cannot be modified directly".

The contents (values) of variables as seen by the person writing the program can be rewritten. It means that you can rewrite "Room 22" to "Room 23".

So, as a result, this behavior becomes basic type = pass-by-value behavior. That's it.

Application: What does the String type do after all?

(You can skip this section)

in short,

String str1 = "String 1";

Is

String str1 = new String("String 1");

This is syntactic sugar. that's all!









I'm sorry it's a lie. I'm sorry. I knew that until I wrote this article, but there is some disproof ...

ex_*


	public static void main(String[] args) {
		String a = "Ah";
		String b = "Ah";
		System.out.println(a == b); //true
	}

** Oh, you were true ... ** This behavior, even if a beginner tries it and asks various people, "Are you ???. Equals () You can compare with == without bothering to use it ???" You can't get it. ** I was. ** **

(Reference) ** In Java, “Hoge” is not just syntactic sugar for new String (“Hoge”) ** http://blog.supermomonga.com/articles/java/difference-bewtween-two-way-to-create-string-instanc.html

Perhaps, to save memory, there is a mechanism to reuse objects for exactly the same string. → It was the correct answer. ** Difference between initialization by "" (double quote) and initialization by new String ("") ** http://education.yachinco.net/tips/java/06/2.html

I'm happy.

reference

** Don't call it by reference anymore ** https://qiita.com/mdstoy/items/2ef4ada6f88341466783

the end. We'll see you somewhere.

Recommended Posts

[For beginners] An article that makes you understand 5000 trillion% of Java's complicated "passing by reference"