変数と型
プリミティブ型と参照型。Javaの型システムの基礎。
用語集
プリミティブ
int, double等。値そのものを格納。
参照型
String, 配列等。オブジェクトへの参照。
final
再代入不可。定数として使う。
var
Java 10+。型推論でコード簡略化。
プリミティブ型
// Primitive types (stored directly in memory)int age = 25; // 32-bit integerlong population = 8_000_000_000L; // 64-bit (note the L suffix)double price = 19.99; // 64-bit floating pointfloat rate = 3.14f; // 32-bit floating point (note the f)boolean isActive = true; // true or falsechar letter = 'A'; // single characterbyte small = 127; // -128 to 127short 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
参照型
// Reference types (store a reference to object in heap)String name = "Alice"; // String is a class, not primitiveString greeting = null; // Can be null (primitives cannot)
// Arraysint[] numbers = {1, 2, 3, 4, 5};String[] names = new String[3];
// Type inference with var (Java 10+)var message = "Hello"; // Compiler infers Stringvar count = 42; // Compiler infers intvar list = new ArrayList<String>(); // Compiler infers typeBad
// Bad: Magic numbersif (status == 1) { price = price * 1.1;}Good
// Good: Named constantsfinal int STATUS_ACTIVE = 1;final double TAX_RATE = 1.10;
if (status == STATUS_ACTIVE) { price = price * TAX_RATE;} Tip: マジックナンバーは final 定数に置き換える。コードの意図が明確になる。
文字列比較(重要!)
// String comparison - CRITICALString a = "hello";String b = "hello";String c = new String("hello");
// CORRECT: Use equals() for content comparisona.equals(b); // true - same contenta.equals(c); // true - same content
// WRONG: == compares references, not contenta == b; // true (string pool optimization)a == c; // FALSE! Different objects
// Null-safe comparisonObjects.equals(a, c); // true, handles null safely 警告: 文字列比較は必ず equals() を使う。== は参照比較になり、予期せぬバグの原因になる。
null安全
// Null handlingString name = null;
// Old way: null checkif (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 valueString result = optName.orElse("Unknown");合格ライン
プリミティブと参照型の違いを説明できる
文字列比較に equals() を使う
final で定数を定義できる
Optional を使える
参考リンク
演習課題
課題1: プリミティブ型
各プリミティブ型の変数を宣言して使ってください。
課題2: String 比較
== と equals() の違いを確認してください。