Java reference to understand in the figure

You may have learned about "references" in Java programming. Some people can understand it easily, others can understand it only somehow, or some people can't understand it and are in trouble. This article uses diagrams to explain Java "references" to those who think "I understand it somehow, but I can't explain it to others" or "I can't get an image even if it is explained in words". It will be an article to do. Regarding the figure, it is not accurate because it actually expresses what is invisible to the eye and it is composed of the minimum information. Please note.

Primitive and reference types

There are two types of Java types: primitive types (basic data types) and reference types. Primitive types are all lowercase letters and can be assigned specific data values (numeric values and characters) that are written directly to memory. Also, unlike the reference type, it does not have a method, which is one of its features.

Model name Classification Size (bit)
long integer 64
int integer 32
short integer 16
byte integer 8
double Decimal 64
float Decimal 32
boolean Authenticity ?
char letter 16

The above eight are primitive types, and all others are reference types. Unlike the primitive type, the pointer (address in memory) to the newly created object is assigned as the reference value to the reference type instead of the concrete value. The object here is synonymous with an instance.

Arrays and Strings

Arrays and Strings are the ones that I personally find easy to misunderstand. Since both the array and the String are reference types, we will create an object.

//Primitive type
int i = 1;
//Reference type
int[] array = {1, 2, 3};
String string = "Apple";

The int [] type is expressed by adding to int, so it is easy to misunderstand. Be careful because int type and int [] type are different. The String type assigns a string, but be aware that the String object treats the string as a char array. The bottom three have different notations for object creation, but they are all equivalent. Please note that equivalence and equivalence have different meanings. I would be grateful if you could read this article for equivalence and equivalence.

String a = "Apple";
String b = new String("Apple");
String c = new String(new char[]{'Ri', 'Hmm', 'Go'});
System.out.println(a); //Apple
System.out.println(b); //Apple
System.out.println(c); //Apple

I think most of the String types will be remembered along with the primitive types when you start learning Java. So people with little programming experience often don't really understand the difference. Now, let's use a diagram to express the difference between a primitive type and a reference type. WS000001.JPG Variables of type int directly assign data values in memory. The int [] type creates an object, expands it in memory, and assigns the pointer of that object to a variable as a reference value. The String type looks like this because the internal char [] variable has a reference value for the char [] object. After all, since it is a computer, most of it is in memory, but for the sake of readability, variables and values are written separately.

What is null

Null can be assigned to a reference type variable, and it can be expressed that there is no reference destination for that variable. A java.lang.NullPointerException (so-called nullpo) occurs when you try to execute a method of a variable that has no reference. WS000003.JPG

Assign to a variable

A variable is a memory area allocated with a name, and storing a value in that area is called assignment. Assignment between variables means copying the value on the right side and storing it on the left side to share the data. WS000007.JPG If you don't understand the references, you won't be able to program correctly, so let's get a solid image. Now let's actually write the code and see how the values are passed.

//[A] Primitive type
int intA = 1;
int intB = intA;
intB = 2;
System.out.println(intA); // 1
System.out.println(intB); // 2

//[B] Reference type
char[] arrayA = {'A', 'B', 'C'};
char[] arrayB = arrayA;
arrayB[0] = 'D';
System.out.println(arrayA[0]); // D
System.out.println(arrayB[0]); // D

 //[C] Reference type (immutable)
String stringA = "String";
String stringB = stringA;
stringB = "String";
System.out.println(stringA); //String
System.out.println(stringB); //String

No explanation is required for [A]. Of note are [B] and [C]. [B] is assigned to arrayB and affects arrayA, but [C] does not affect stringA. I'll also use a diagram to explain what's happening. WS000000.JPG In ③ of [B], the data value is assigned to the array of arrayB, but since the referenced object is the same as arrayA (this is called the same value for arrayA and arrayB), the output of arrayA and arrayB is the same. .. In [C], a new String object with "Mojiretsu" is created in ③ and the reference value is assigned to stringB, so the reference to the "String" object is cut off. Therefore, the output of stringA and stringB will be different. So if you want to change the value of a String object, you have to assign the data value to the internal char array. However, since the char array variable inside the String class is defined in private final, it cannot be rewritten. A design in which the value of an object cannot be changed in this way is called immutable </ b>.

Method call

It's easy to misunderstand the method call, so let's imagine the behavior of the program from the code and the figure.

void main() {

  String string = "String";
  sub(string);
  System.out.println(string); //String

}
void sub(String string) {

  string = "String";

}

At first glance, it looks like you are assigning another value to the variable passed from main in the sub method. But understand that you're not passing a variable, but the reference value of the object it's referencing. WS000002.JPG Variables declared within a method are called local variables for that method and can only be used within that method. So we call the sub method from the main method and pass the argument, which means that the string variable of the main method is assigned to the string variable of the sub method. I think this is also a place where misunderstandings are likely to occur because the variable names are the same.

Finally

There are many articles on the Web about Java references, but I think most of them are explained in words and code. I think that those who have a programming sense can understand it by itself, but those who do not understand it well or who have just started learning should read this article and have a clear understanding.

Recommended Posts

Java reference to understand in the figure
Java classes and instances to understand in the figure
[java8] To understand the Stream API
How to get the date in java
[Java] How to omit the private constructor in Lombok
Understand the characteristics of Scala in 5 minutes (Introduction to Scala)
Source used to get the redirect source URL in Java
I tried to implement the Euclidean algorithm in Java
Java thread to understand loosely
Input to the Java console
How to get the class name / method name running in Java
Understand the rough flow from request to response in SpringWebMVC
Refer to C ++ in the Android Studio module (Java / kotlin)
[Android, Java] Convenient method to calculate the difference in days
Create a method to return the tax rate in Java
How to derive the last day of the month in Java
How to switch Java in the OpenJDK era on Mac
I want to simplify the conditional if-else statement in Java
Access the network interface in Java
Guess the character code in Java
Pass the i18n locale to JavaScript
Multithreaded to fit in [Java] template
Specify the java location in eclipse.ini
How to learn JAVA in 7 days
Unzip the zip file in Java
Log output to file in Java
Welcome to the Java Library Swamp! !!
Parsing the COTOHA API in Java
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java
The road from JavaScript to Java
How to concatenate strings in java
Call the super method in Java
Understand how functional programming was introduced to Java in one shot
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
[Android / Java] Understand the description type in listener settings (button installation)
Determine if the strings to be compared are the same in Java
[Java] I want to perform distinct with the key in the object
Sample code to call the Yahoo! Local Search API in Java
How to solve the unknown error when using slf4j in Java
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
About returning a reference in a Java Getter
Shorten the UUID to base64 in Swift.
How to implement date calculation in Java
How to implement Kalman filter in Java
[Java] How to use the File class
[Easy-to-understand explanation! ] Reference type type conversion in Java
Easy to make Slack Bot in Java
Introduction to java for the first time # 2
Try to implement n-ary addition in Java
Try using the Stream API in Java
Understand java interface in your own way
Call the Windows Notification API in Java
Java SE8 Silver ~ The Road to Pass ~
About the procedure for java to work
I tried the new era in Java
How to do base conversion in Java
[Java] How to use the toString () method
[Java] Use cryptography in the standard library