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?

[JAVA入門 #3-4] 演算子と条件文の核心まとめ

0
Posted at

演算子(Operator)

演算子の種類

// 算術演算子: 四則演算
int a = 10 + 5;   // 加算: 15
int b = 10 - 5;   // 減算: 5
int c = 10 * 5;   // 乗算: 50
int d = 10 / 5;   // 除算: 2
int e = 10 % 3;   // 剰余: 1

// 増減演算子
int count = 0;
count++;  // 1増加
count--;  // 1減少

// 比較演算子: 結果はboolean
boolean result1 = (5 == 5);   // true (等しい)
boolean result2 = (5 != 3);   // true (等しくない)
boolean result3 = (5 > 3);    // true (大きい)
boolean result4 = (5 < 3);    // false (小さい)
boolean result5 = (5 >= 5);   // true (以上)
boolean result6 = (5 <= 3);   // false (以下)

// 論理演算子: boolean値を演算
boolean and = true && false;  // false (AND: 両方真なら真)
boolean or = true || false;   // true (OR: 片方真なら真)
boolean not = !true;          // false (NOT: 反対)

// 代入演算子
int x = 10;
x += 5;   // x = x + 5  (15)
x -= 3;   // x = x - 3  (12)
x *= 2;   // x = x * 2  (24)
x /= 4;   // x = x / 4  (6)
x %= 4;   // x = x % 4  (2)

// 三項演算子
int age = 20;
String result = (age >= 18) ? "成人" : "未成年";  // "成人"

核心概念

1. 同じ型同士で計算可能

int a = 10;
int b = 5;
int result = a + b;  // int + int = int (15)

double x = 10.5;
double y = 2.5;
double result2 = x + y;  // double + double = double (13.0)

2. 文字列演算の特徴

String str1 = "Hello";
String str2 = "World";
String result = str1 + str2;  // "HelloWorld"

String mixed = "年齢: " + 25;  // "年齢: 25" (数値が文字列に変換される)

3. 文字列比較は必ず.equals()使用

String name1 = "田中";
String name2 = "田中";

// 誤った方法 (精度が落ちる)
if (name1 == name2) { }

// 正しい方法
if (name1.equals(name2)) { }  // こう使う!

増減演算子: 前置 vs 後置

// 前置増減: 先に増加、その後使用
int a = 1;
int result = ++a;  // aを先に2に増加 → resultに2を保存
System.out.println(a);       // 2
System.out.println(result);  // 2

// 後置増減: 先に使用、その後増加
int b = 1;
int result2 = b++;  // result2に1を保存 → bを2に増加
System.out.println(b);        // 2
System.out.println(result2);  // 1

// 単独使用時は違いなし
int c = 1;
c++;  // 2
++c;  // 3 (結果同じ)

演算子の優先順位

覚える必要なし! 次の3つの原則だけ覚える

  1. 常識的な優先順位を使用 (乗算が加算より先など)
  2. 曖昧なら括弧を使用
  3. 単純さと明確さが最優先
// 悪い例: 優先順位が曖昧
int result = 10 + 5 * 2;

// 良い例: 括弧で明確に
int result = 10 + (5 * 2);

💡 実務ヒント: コード数文字を削って曖昧になるより、コードが多くても明確で単純な方が保守に有利です。


条件文(Conditional Statement)

条件文は特定の条件に応じて異なるコードを実行する時に使用します。

if 文

int age = 20;

// 基本if文
if (age >= 18) {
    System.out.println("成人です");
}

// if-else文
if (age >= 18) {
    System.out.println("成人です");
} else {
    System.out.println("未成年です");
}

// if-else if-else文
if (age >= 65) {
    System.out.println("高齢者");
} else if (age >= 18) {
    System.out.println("成人");
} else {
    System.out.println("未成年");
}

if文使用戦略

// if-else使用: 互いに関連する条件 (一つだけ実行)
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else {
    grade = "C";
}

// if個別使用: 独立した条件 (複数同時実行可能)
if (hasLicense) {
    System.out.println("免許あり");
}
if (hasInsurance) {
    System.out.println("保険あり");
}

⚠️ 重要: if文を1行で書く時{}を省略できますが、保守性と可読性のため常に入れることを推奨します。

// 可能だが非推奨
if (age >= 18) System.out.println("成人");

// 推奨
if (age >= 18) {
    System.out.println("成人");
}

switch 文

単純に値が等しいかだけを比較する時に使用します。

// 従来のswitch文 (break必須!)
int grade = 2;

switch (grade) {
    case 1:
        System.out.println("1等級");
        break;  // breakがないと下に続けて実行される!
    case 2:
        System.out.println("2等級");
        break;
    case 3:
        System.out.println("3等級");
        break;
    default:
        System.out.println("等級なし");
}

新しいswitch式 (Java 14+)

// 値を直接返す (break不要)
int grade = 2;

int coupon = switch (grade) {
    case 1 -> 1000;
    case 2 -> 2000;
    case 3 -> 3000;
    default -> 500;
};

System.out.println("クーポン: " + coupon + "円");  // クーポン: 2000円

利点:

  • breakキーワード不要
  • コードがより簡潔で明確
  • うっかりbreakを忘れるリスクを排除

三項演算子

単純に真/偽に応じて特定の値を求める時に使用します。

// 基本形式
(条件) ? 真の時の値 : 偽の時の値;

// 例
int age = 20;
String type = (age >= 18) ? "成人" : "未成年";

// if文で表現すると
String type;
if (age >= 18) {
    type = "成人";
} else {
    type = "未成年";
}

使用ガイド:

  • ✅ 単純な条件式にのみ使用
  • ✅ 可読性が良い時のみ使用
  • ❌ 複雑な条件や複数行コードはif文使用
// 良い例: 簡単で明確
String status = (isOnline) ? "接続中" : "オフライン";

// 悪い例: 複雑で可読性が落ちる
String result = (score >= 90) ? "A等級" : 
                (score >= 80) ? "B等級" : 
                (score >= 70) ? "C等級" : "F等級";  // こういう時はif-else使用!

実践例

演算子総合

int a = 10;
int b = 3;

// 算術
System.out.println(a + b);   // 13
System.out.println(a % b);   // 1 (剰余)

// 比較
System.out.println(a > b);   // true

// 論理
System.out.println((a > 5) && (b < 5));  // true (両方真)
System.out.println((a > 5) || (b > 5));  // true (片方真なら)

// 代入
a += 5;  // a = 15
System.out.println(a);

条件文総合

int score = 85;
String grade;

// if-else ifで等級決定
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else {
    grade = "F";
}

// switchで成績別メッセージ
String message = switch (grade) {
    case "A" -> "素晴らしい!";
    case "B" -> "よくできました!";
    case "C" -> "頑張ってください!";
    default -> "再試験が必要です。";
};

// 三項演算子で合否判定
String result = (score >= 70) ? "合格" : "不合格";

System.out.println("等級: " + grade);      // 等級: B
System.out.println("評価: " + message);    // 評価: よくできました!
System.out.println("結果: " + result);     // 結果: 合格

まとめ

演算子

  • 算術: +, -, *, /, %
  • 増減: ++, -- (前置/後置の違いに注意)
  • 比較: ==, !=, >, <, >=, <= (結果はboolean)
  • 論理: &&(AND), ||(OR), !(NOT)
  • 代入: =, +=, -=, *=, /=, %=
  • 文字列比較: 必ず.equals()使用
  • 優先順位: 曖昧なら括弧使用、明確さが最優先

条件文

  • if-else: 関連する条件、一つだけ実行
  • if個別: 独立した条件、複数同時実行可能
  • switch: 値が等しいかだけ比較、新文法(Java 14+)推奨
  • 三項演算子: 単純な真/偽の値決定時のみ使用

本投稿はインフルン キム・ヨンハンのJava講座を学習しながらまとめた内容です。

次回の投稿: ループ文 (予定)

0
1
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
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?