Note
There are two main types of Java. ** Primitive type ** and ** Reference type **. I tried to summarize each.
The following eight are primitive types.
Mold | Classification | Bit number |
---|---|---|
boolean | Boolean value | 1 |
byte | integer | 8 |
short | integer | 16 |
char | letter | 16 |
int | integer | 32 |
float | Decimal | 32 |
long | integer | 64 |
double | Decimal | 64 |
When declaring a variable of a primitive type, the value can be stored in the variable at the same time as the declaration. The value 1 is stored in the variable a below.
int a = 1;
Reference types are types other than the above eight. For example, Strings and arrays are reference types.
Hoge hoge = new Hoge();
String str = "fuga";
In the reference type, the variable does not store the value as it is, but stores the memory location where the value is stored.
There is a difference in the behavior of reassignment between the basic type and the reference type.
The sample code below is the code that reassigns the basic type. You can see this intuitively.
kihon.java
int a = 1;
int b = a; //The value of a: 1 is stored in b
a = 2;
Systemout.println(a); //2 is output
Systemout.println(b); //1 is output
On the other hand, in the reference type, it is as follows. In the same way as the basic type, b [0] seems to output 1. However, with reference types, variables store only the location of the memory where the data is stored.
When the array a is declared, a stores the memory location information in which the array information {1, 2, 3}
is stored.
When the array b is declared, b also stores the memory location of the array {1, 2, 3}
that a has.
At this time, both a and b are variables that contain the same memory location information.
ʻA [0] = 0; replaces the 0th value of the array
{1, 2, 3} in the memory location stored in a with 0. The array stored in memory is now
{0, 2, 3}`.
Therefore, even if you look at the 0th array from the memory location stored in b, the output value will be 0.
sansyo.java
int[] a = {1, 2, 3};
int[] b = a;
a[0] = 0;
Systemout.println(a[0]); //0 is output
Systemout.println(b[0]); //0 is output
Recommended Posts