
問題
次のコードをコンパイルし、次のコマンドを実行するとどうなりますか。
public class Main {
public static void main(String... args) {
final Integer[] numbers = { 1, 4, 2, 7, 1, 2, 1 };
int element = Integer.parseInt(args[0]);
BaseType c = new MyClass();
if (c.isContain(numbers, element))
System.out.println("The array contains: " + element);
else
System.out.println("The array done not contain: " + element);
}
}
interface BaseType {
boolean isContain(Integer[] numbers, int element);
}
interface MyType extends BaseType {
public default boolean isContain(Integer[] numbers, int element) {
int count = 0;
for (int i : numbers) {
if (i == element)
++count;
}
return count > 0;
}
}
class MyClass implements MyType {
}
コマンド
$ java Main 3 1
選択肢
A)ClassCastException がスローされる
B)The array done not contain: 3 The array contains: 1 がスローされる
C)コンパイルエラーになる
D)The array done not contain: がスローされる
E)The array done not contain: 3 がスローされる
F)ArrayIndexOutOfBoundsException がスローされる
G)The array contains: 1 がスローされる
解答
A)ClassCastException がスローされる
B)The array done not contain: 3 The array contains: 1 がスローされる
C)コンパイルエラーになる
D)The array done not contain: がスローされる
E)The array done not contain: 3 がスローされる
F)ArrayIndexOutOfBoundsException がスローされる
G)The array contains: 1 がスローされる
解説
このコードをコンパイルして、指定されたコマンドを実行するとどうなるかを解説します。
コードの説明
- 引数の取得:
args[0]からelementを取得します。コマンドライン引数として3を渡すため、elementは3になります。 - クラスのインスタンス化:
BaseTypeインターフェースを実装したMyClassのインスタンスcを作成します。 - isContain メソッドの呼び出し:
c.isContain(numbers, element)が呼ばれます。MyTypeインターフェースのデフォルトメソッドが呼ばれるので、numbers配列をループしてelement(3)を探します。
ループの処理
numbers配列は{ 1, 4, 2, 7, 1, 2, 1 }です。elementは3ですが、配列には3は含まれていません。- したがって、カウントは
0になり、count > 0の条件は満たされません。
結果
isContainメソッドはfalseを返します。else節が実行され、"The array done not contain: " + elementが出力されます
対象資格:Java SE17 認定資格
