How to change arguments in [Java] method (for those who are confused by passing by value, passing by reference, passing by reference)

at first

Pass the value to the method and process the value in the method

I didn't know what to do in Java, which doesn't have pointers or passing by reference like C ++, so I was confused during the investigation and investigation (mainly passing by reference / passing by reference). I will summarize about such things.

Although I am writing an article, I have been in contact with Java for about 3 months, so I would appreciate it if you could point out any mistakes.

Pass by value

For example, write the code below to double the value of the method as an argument in the method. (This code doesn't work as intended)

java


public class Main{
    /*Double the value in the method*/
    public static void twice(int n){
        n *= 2;
    }
    /*Main function*/
    public static void main(String[] args){
        int num = 2;
        twice(num);
        System.out.println(num);   //2
    }
}   

As a result, the value of num is not rewritten in the method, and the originally declared 2 is output as it is. This looks like you are passing the variable num to the method as is, but only the value inside ** num ** is passed to the method. This is called ** passing by value **.

How to rewrite a value in Java

When I try to rewrite a value, there is no pointer or passing by reference (I write it like this now) How should I rewrite the value in Java? The method is to use an array or a class type variable.

Example of using an array

array


public class Main {
    /*Changed to pass an array*/
	public static void twice(int[] n){
        n[0] *= 2;
    }
    /*Main function*/
    public static void main(String[] args){
        int num[] = new int[1];
        num[0] = 2;
        twice(num);
        System.out.println(num[0]);   //4
    }  
}
Example of using a class for storing values

Data.java


public class Data {
	int num;  //Field for data storage
}

Main.java


public class Main {
    /*Changed to pass an instance of the data storage class*/
	public static void twice(Data ins){
        ins.num *= 2;
    }
    /*Main function*/
    public static void main(String[] args){
        Data data = new Data();
        data.num = 2;
        twice(data);
        System.out.println(data.num);   //4
    } 
}

So why can arrays and instances rewrite values in methods? Now let's look at the arguments of Java methods (for those who are confused by passing by value, passing by reference, passing by reference).

Java method arguments

It may be a misleading expression, but I stumbled here, so I will say it first. There is only ** passing by value ** in Java **. Forget about passing by reference and passing by value.

What is passed to the method in Java

I said that Java only exists by value, but there are two types of values that are passed depending on the type of variable. First of all, the types of variables are roughly divided into two in Java. ・ Basic type ・ Reference type There is a variable of. And what to pass when set to the argument of each method is different.

At the time of basic type

First of all, the basic type is

Data type Numerical classification
byte integer
short integer
int integer
long integer
floot Floating point
double Floating point
boolean Authenticity
char letter

It refers to. If you pass these as method arguments, Java only passes them by value. In other words, only the value of the contents of the variable is passed, so changing the value of the argument in the method does not change the value of the passed argument.

When it is a reference type

Then for the reference type

・ Class type ・ Array type

And so on. They pass their ** reference value ** when they become method arguments. Now, what is the reference value here?

What is a reference value?

The reference value is an image ** Where the variable exists ** It will be. In C language, it is an image of something like a pointer.

Why the value is rewritten in the method

Java cannot change arguments within a method (not surprisingly because it only exists by value). However, passing a reference value allows you to rewrite the value through the location of that reference value.

What is different from passing by reference

Here, what is different from passing by reference is to the last in Java ** Pass by copying the value of the place where the variable exists called the reference value (of course, the reference value cannot be rewritten) ** It is doing the operation. Pass by reference ** Pass the location of the variable as it is ** It is doing the operation. The result is similar behavior, but Java does not pass by reference, but by value.

An example that shows that you are passing a reference value by value

Rewrite the code that was rewriting the value in the method using the data storage class earlier as follows.

Data.java


public class Data {
	int num;  //Field for data storage
}

Main.java


public class Main {
	
    /*Pass an instance of the class*/
	public static void twice(Data n){
		/*Create a new instance in the method*/
		Data inMethodInstance = new Data();
		/*Give data*/
		inMethodInstance.num = n.num * 2;  //4
		/*Rewriting reference value*/
        n = inMethodInstance;
    }
	
    /*Main function*/
    public static void main(String[] args){
        Data data = new Data();
        data.num = 2;
        twice(data);
        System.out.println(data.num);  //2
    }  
}

If you change to such a code and execute it, you can see that 2 is output. If it is passed by reference, it is done at the end of the method

n = inMethodInstance

N should be rewritten in the part of and 4 should be output.

By the way, if you write the code so that the code written in Java is passed by reference in C ++, it will be as follows.

data.h


#ifndef DATA_H_
#define DATA_H_
/*Data storage class*/
class data 
{
public:
	int num;
};

#endif

main.cpp


#include <iostream>
#include "data.h"

void twice(data &d) {
	/*Instantiate within a method*/
	data inMethodInstance;
	/*Give a value to the instance in the method*/
	inMethodInstance.num = d.num * 2;
	/*Rewrite the argument*/
	d = inMethodInstance;
}

int main(void)
{
	data ins;
	ins.num = 2;
    std::cout << ins.num << std::endl;  //2
	twice(ins);
	std::cout << ins.num << std::endl;  //4
}

In C ++ that can pass by reference like this, the value of the argument can be rewritten.

Passing by reference does not exist in Java

As I've seen, there is no passing by reference in Java. Only pass by value exists. However, you can change the value via a reference value.

I think that you might mistakenly think that passing by reference exists in the part where you can change the value via the reference value, but Java only exists by passing by value.

At the end

This time, I've summarized what I investigated about how to rewrite values in Java methods. Since I wrote the article for the first time, it may be difficult to read, but please take a look ...

Recommended Posts

How to change arguments in [Java] method (for those who are confused by passing by value, passing by reference, passing by reference)
Whether Java arguments are passed by value or by reference
[Java] How to search for a value in an array (or list) with the contains method
Method to describe by dividing into multiple methods How to pass arguments How to use return value Method overload Pass by value and pass by reference
(Java) How to implement equals () for a class with value elements added by inheritance
[Java] How to get the key and value stored in Map by iterative processing
[For those who create portfolios] How to use font-awesome-rails
Summary of how to implement default arguments in Java
How to get the class name / method name running in Java
[For those who create portfolios] How to use chart kick
[For those who create portfolios] How to omit character strings
[Java] How to write when passing two or more arguments to super
How to increment the value of Map in one line in Java
[For those who create portfolios] How to use binding.pry with Docker
[Java] How to use join method
How to learn JAVA in 7 days
Java pass by value and pass by reference
How to use classes in Java?
How to name variables in Java
How to concatenate strings in java
[Java] Pass arguments to constructor in Mockito / Set method default call to callRealMethod
How to test a private method in Java and partially mock that method
[Java] How to receive numerical data separated by spaces in standard input
Java Programmer Gold SE 8 Qualification Summary (for those who are familiar with Java)
How to get the value after "_" in Windows batch like Java -version
How to change the value of a variable at a breakpoint in intelliJ
[Java] [For beginners] How to insert elements directly in a 2D array
How to reference a column when overriding the column name method in ActiveRecord
How to create your own annotation in Java and get the value
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
Java reference to understand in the figure
[Java] How to compare with equals method
How to use submit method (Java Silver)
How to do base conversion in Java
[Java] How to use the toString () method
How to have params in link_to method
Change List <Optional <T >> to Optional <List <T >> in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
How to get the date in java
[For beginners] How to debug in Eclipse
How to concatenate strings separated by commas using StringJoiner even in java7 environment
[Java] Various methods to acquire the value stored in List by iterative processing
[Java] How to get HashMap elements by loop control using extended for statement
How to make a judgment method to search for an arbitrary character in an array