LoginSignup
5
5

More than 5 years have passed since last update.

Javaの基本データ型と参照型

Last updated at Posted at 2017-02-26

基本データ型

基本データ型 ラッパークラス
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

ラッパークラスは便利なメソッドを持っている。

java
int x = Integer.valueOf("99");
int y = Integer.parseInt("88");

System.out.println(x);
System.out.println(y);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);

参照型

参照型
String
Array
Class

基本データ型と参照型の違いを確認する。

基本データ型の場合

java
public static void main(String[] args) {
    int x = 10;
    int y = x;
    y = 5;
    System.out.println(x); 
    System.out.println(y);
}
10
5

参照型の場合

java
public static void main(String[] args) {
    int[] a = {3, 5, 7};
    int[] b = a;
    b[1] = 8;
    System.out.println(a[1]);
    System.out.println(b[1]);
}

両方とも8。これは、aもbも同じメモリの番地が入っているから、こういう動作になる。

8
8

ラッパークラスの場合は、どうなるか?

java
public static void main(String[] args) {
    Integer x = 10;
    Integer y = x;
    y = 5;
    System.out.println(x);
    System.out.println(y);
}
10
5

String型の場合はどうなるか?

java
public static void main(String[] args) {
    String x = "hello";
    String y = x;
    y = "world";
    System.out.println(x);
    System.out.println(y);
}

参照型なのに、基本型っぽく表示される。
文字列は変更が不可になっていて、違う文字列を割り当てると別の領域に新しくデータを確保するため

hello
world

boxingとunboxingについて

Javaのクラスによっては参照型の引数しか受け付けないものもあるので、ラッパークラスと基本データ型
を相互に変換する必要がある。

参照型にいれることをauto boxing

java
Integer i = new Integer(32);
Integer j = 32;

auto unboxing

java
Int n = i; 
int m = j.intValue();
5
5
0

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
5
5