0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

基本データ型と参照型

0
Last updated at Posted at 2018-11-20

基本データ型の変数とは

変数の中身に、値そのものが入っている変数のこと

基本データ型変数のメモリ使用領域

基本データ型とは、下記の8種類である。

種類 ビット数 説明
boolean 1bit true or false
byte 8bit 符号付き整数 -128~127
char 16bit Unicodeの一文字
short 16bit 符号付き整数 -32768~32767
int 32bit 符号付き整数 -2147483648~2147483647
long 64bit 符号付き整数 約-922京~約922京
float 32bit 浮動小数点数
double 64bit 浮動小数点数

基本データ型の変数は、定義された時に必要なメモリ領域を確保する。その確保したメモリ領域に、値をそのまま代入し保持する。

以下のようなコードを実行したとする。

基本データ型
int x = 10;
int y = x;
y = 20;
System.out.println(x);
System.out.println(y);

出力は以下の通り。

出力
10
20

このように、基本データ型の変数は、値そのものを変数に保存している。そのため、yの中身は、10 → 20 と変化し、最終的に20が出力される。

参照型変数とは

値そのものを保存しるのではなく、値がおいてある場所(メモリ番地)を保持する変数のこと。
基本データ型と違い、どんな値が代入されるか分からない場合、どれくらいのメモリ領域を確保しておいたらいいのか分からない。また、1度メモリ内でその変数用に確保したメモリ領域は、後から大きく変更できない仕組みになっている。
そのため、こういった参照型変数には、メモリの他の部分に作られた値の場所を示すコードが代入される。この場所を示すコードのことを参照値と呼ぶ。

以下のコードを実行したとする。

参照型
int a[] = { 1,2,3 };
int b[] = a;
b[0] = 2;
System.out.println(a[0]);

出力は以下の通り。

出力
2

これが参照型変数の挙動の特徴的な部分になる。
b[]に保存されているのは、a[]の場所を示すコードなので、b[]の中身を変更するというのは、同時にa[]の中身も変更してしまう。

参考にした記事

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?