変数と型

プリミティブ型と参照型。Javaの型システムの基礎。

箱と住所 (Box vs Address)

**プリミティブ型** = 箱の中に「値そのもの」が入っている **参照型** = 箱の中に「倉庫の住所」が入っている int x = 5 → 箱の中に5が入っている String s = "Hello" → 箱の中に「倉庫A-123番」という住所が入っていて、そこに"Hello"がある

用語集

プリミティブ
int, double等。値そのものを格納。
参照型
String, 配列等。オブジェクトへの参照。
final
再代入不可。定数として使う。
var
Java 10+。型推論でコード簡略化。

プリミティブ型

primitives.java
// Primitive types (stored directly in memory)
int age = 25; // 32-bit integer
long population = 8_000_000_000L; // 64-bit (note the L suffix)
double price = 19.99; // 64-bit floating point
float rate = 3.14f; // 32-bit floating point (note the f)
boolean isActive = true; // true or false
char letter = 'A'; // single character
byte small = 127; // -128 to 127
short medium = 32767; // -32768 to 32767
メモリサイズ
byte:    1 byte  (-128 to 127)
short:   2 bytes (-32,768 to 32,767)
int:     4 bytes (-2B to 2B)
long:    8 bytes
float:   4 bytes
double:  8 bytes
char:    2 bytes (Unicode)
boolean: 1 bit

参照型

references.java
// Reference types (store a reference to object in heap)
String name = "Alice"; // String is a class, not primitive
String greeting = null; // Can be null (primitives cannot)
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
// Type inference with var (Java 10+)
var message = "Hello"; // Compiler infers String
var count = 42; // Compiler infers int
var list = new ArrayList<String>(); // Compiler infers type
Bad
// Bad: Magic numbers
if (status == 1) {
price = price * 1.1;
}
Good
// Good: Named constants
final int STATUS_ACTIVE = 1;
final double TAX_RATE = 1.10;
if (status == STATUS_ACTIVE) {
price = price * TAX_RATE;
}
Tip: マジックナンバーは final 定数に置き換える。コードの意図が明確になる。

文字列比較(重要!)

string-comparison.java
// String comparison - CRITICAL
String a = "hello";
String b = "hello";
String c = new String("hello");
// CORRECT: Use equals() for content comparison
a.equals(b); // true - same content
a.equals(c); // true - same content
// WRONG: == compares references, not content
a == b; // true (string pool optimization)
a == c; // FALSE! Different objects
// Null-safe comparison
Objects.equals(a, c); // true, handles null safely
警告: 文字列比較は必ず equals() を使う。== は参照比較になり、予期せぬバグの原因になる。

null安全

null-handling.java
// Null handling
String name = null;
// Old way: null check
if (name != null) {
System.out.println(name.length());
}
// Modern way: Optional (Java 8+)
Optional<String> optName = Optional.ofNullable(name);
optName.ifPresent(n -> System.out.println(n.length()));
// With default value
String result = optName.orElse("Unknown");

合格ライン

プリミティブと参照型の違いを説明できる
文字列比較に equals() を使う
final で定数を定義できる
Optional を使える

参考リンク

演習課題

課題1: プリミティブ型
各プリミティブ型の変数を宣言して使ってください。
課題2: String 比較
== と equals() の違いを確認してください。

次のステップ