0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

if文についてのメモ

Last updated at Posted at 2022-06-25

javaのif文についてよく解説書では
処理が1行のものであれば{}は省略できる。
というような記載になっている。

実際以下のようなプログラムはコンパイルも実行もできるし、
if文も想定通り動く。

public class Main {
    public static void main(String[] args) throws Exception {
     int a = 1;
      if(a == 1)
       System.out.println("aは"+a+"です");
    }
}

だが以下のif文ではコンパイルエラーが発生する。

public class Main {
    public static void main(String[] args) throws Exception {
     int a = 1;
      if(a == 1)
    	int b = 1;
    }
}

エラー文

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
構文エラーがあります。". class" を挿入して Expression を完了してください
構文エラーがあります。"AssignmentOperator Expression" を挿入して Assignment を完了してください
構文エラーがあります。";" を挿入して Statement を完了してください
代入の左側は変数でなければなりません
b を変数に解決できません
at Main.main(Main.java:5)

こちらは正常にコンパイルも実行も可能

public class Main {
    public static void main(String[] args) throws Exception {
     int a = 1;
      if(a == 1){
    	int b = 1;
      }
    }
}

クラスのインスタンス宣言等他にもできない事はいくつかあるようだが、
新しく何かを宣言する処理というのは{}を省略しては実行することができないようだった。
調べても詳細にたどりつけなかったが、メモリ領域の取得とかの処理が挟まって実質1行で動いていないとかそういうことなのかもしれない。

時間があんまりないので今日はこの辺りで。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?