Java no memo

自分のためのJavaメモ。

基本型とラッパークラス

  • 基本型にはメソッドがない。
  • ラッパークラスを使う。 |基本データ型|ラッパークラス| |---|---| |boolean|Boolean| |char|Character| |byte|Byte| |short|Short| |int|Integer| |long |Long| |float|Float| |double|Double|
オートボクシング
  • ラッパークラスに直接入れられる。
  • 自動的に変換される。
int i1 = 84;
Integer i2 = i1;  // Integer i2 = new Integer(i1);
int i3 = i2;      // int i3 = i2.intValue();
文字列⇒数値
Integer i = 100;
String s1 = "" + i;
String s2 = String.valueOf(i);
String s3 = Integer.toString(i);
String s4 = new Integer(i).toString();
数値⇒文字列
String str = "100";
Integer i1 = Integer.parseInt(str);      // おすすめ
Integer i2 = new Integer(str).intValue();     // A
Integer i3 = Integer.valueOf(str).intValue(); // B

AとBの書き方に注意。

new Integer(str) と Integer.valueOf(str) は同じ。
文字列⇒Byte
String str = "0123456789";
byte[] bs = str.getBytes();
    
for(byte b : bs){
    System.out.println(b); // 48から57
}

2進数、8進数、16進数⇒文字列

String s1 = Integer.toBinaryString(15);
String s2 = Integer.toOctalString(15);
String s3 = Integer.toHexString(15);
System.out.println(s1); // 1111
System.out.println(s2); // 17
System.out.println(s3); // f