|
|
31:Choose four code fragments that cause a compilation error.
A:byte i=100l;
B:byte i=(short)120;
C:byte i=100+28;short j=-30000-2769;
D:short i=1;byte j=i;
E:byte i=(byte)2000;byte j=i;
F:double i=10000d;byte j=(byte)(1*i);
G:byte i=1;short j=i+i;
H:char i=100;
Check the answer
The four code fragments that cause a compilation error are: A: byte i=100l; Reason: `100l` is a long literal. To assign a long type value to a smaller byte type variable, an explicit cast `(byte)` is required. C: byte i=100+28;short j=-30000-2769; Reason: The first part `byte i=100+28;` fails because 128 exceeds the byte range (-128 to 127). The second part `short j=-30000-2769;` fails because -32769 exceeds the short range (-32768 to 32767). D: short i=1;byte j=i; Reason: Variable `i` is short type. To assign a larger data type (short) to a smaller data type (byte), an explicit cast `(byte)` is required even if the value is within the byte range. G: byte i=1;short j=i+i; Reason: In Java, when byte, short, or char values are used in arithmetic operations (+, -, *, /), they are automatically promoted to int (integer promotion). Therefore, the result of `i+i` is int type. To assign an int value to a short variable `j`, an explicit cast `(short)` is required. Code fragments B, E, F, and H do not cause compilation errors. Their reasons are: B: byte i=(short)120; Reason: 120 is within the byte range (-128 to 127). Although 120 is first cast to short, its value is assignable to byte variable `i`. It is an assignment from a larger type (short) to a smaller type (byte), but since the literal value is within the destination range, the compiler automatically converts it without error. E: byte i=(byte)2000;byte j=i; Reason: `byte i=(byte)2000;`: 2000 exceeds the byte range, but an explicit cast `(byte)` is performed. This forces the value to be converted to fit within the byte range. `byte j=i;`: The value of byte variable `i` is assigned to another byte variable `j`, so it compiles without issues. F: double i=10000d;byte j=(byte)(1*i); Reason: The result of `1*i` is double type 10000.0. Usually, you cannot assign a double value to a byte variable. However, similar to E, since there is an explicit cast `(byte)`, the compiler attempts to forcibly convert 10000.0 to byte type. H: char i=100; Reason: char type internally handles numbers, so integer literals can be assigned. 100 is within the char range (0 to 65535). In this case, the character corresponding to 100 in Unicode (alphabet 'd') is stored in variable `i`. Since integer literals within the range can be directly assigned to char type, no error occurs.
32:Choose the correct result when compiling and executing the following code.
public class Main{
public static void main(String[] args) {
int i=check((char)(1+11));i+=check('D');i+=check('a');
}
private static int check(char i) {
return switch(i) {
case 'D'->' ';
case 12->{
System.out.print('D'+""+'D');
System.out.print('D'+'D');
yield 'D'+'D';
}
default->check((char)('D'+'D'));
};
}
}
A:Compilation error in main method
B:Compilation error in check method
C:DD136
D:DDDD
E:Displays DD136 then throws StackOverflowError
F:Displays DDDD then throws StackOverflowError
Check the answer
The program first displays "DD136" and then stops by throwing a StackOverflowError.
Let's look at the behavior of this code step by step.
Call to `check((char)(1 + 11))`: `1 + 11` is 12. This is cast to char and the check method is called.
It matches `case 12:` of the switch statement.
`System.out.print('D' + "" + 'D');`
Calculation is 'D' (char) + "" (empty string) + 'D' (char).
When concatenating a string and a character with +, the character is converted to a string. As a result, the string "DD" is output to the console.
`System.out.print('D' + 'D');`
Calculation is 'D' (char) + 'D' (char).
When adding characters together with +, their character codes (ASCII values) are added.
The character code for 'D' is 68, so 68 + 68 = 136. As a result, the number 136 is output to the console.
The output at this point is DD136. This case returns 136 via `yield 'D' + 'D';`.
Call to `check('D')`
Matches `case 'D':` of the switch statement. This case returns ' ' (space character).
Call to `check('a')`
'a' matches neither `case 'D'` nor `case 12`, so `default` processing is executed.
`default` calls `check((char)('D' + 'D'))`. This is equivalent to calling `check((char)136)`.
Recursive call: The called `check((char)136)` also matches no case, so it enters `default` again and calls `check((char)136)` again. This falls into infinite recursion repeating endlessly.
Conclusion: The program outputs DD136 to the screen in the first call to the check method. Then, during the third call `check('a')`, infinite recursion occurs, eventually exhausting the stack area, throwing a `java.lang.StackOverflowError`, and terminating the program abnormally.
33:Choose the correct result when compiling and executing the following code.
public class Main{
public static void main(String[] args) {
A a=new B();
var i=a.useA();var j=a.a_(a);
System.out.println(""+i.i+j.i);
}
}
sealed class A permits B{
Byte i;
private A a() {
Byte i=1;
return new A(i);
}
protected A a_(Object i) {
return new A(3);
}
A(Byte i){
this.i=i;
}
A useA(){
return a();
}
A(){}
}
final class B extends A{
public A a() {
return new B();
}
public B a_(Object j) {
return new B();
}
protected A a_(A a) {
return new A(2);
}
}
A:1null
B:null2
C:null3
D:Compilation error in class A
E:Compilation error in class B
F:Exception thrown at runtime
Check the answer
`A a = new B();`
An instance of Class B is created and assigned to variable `a` of type A. The declared type is A, but the actual instance type is B.
Evaluation of `var i = a.useA();`
Calls the `useA()` method of `a`. Class B does not override `useA()`, so the parent class A's `useA()` is called. Inside A's `useA()`, `return a();` is executed.
The important point here is that Class A's `a()` method is declared as private. Private methods are not subject to overriding.
Therefore, even if the actual instance of `a` is B, when `a()` is called from within A's code, A's own private `a()` method is always executed. A's `private A a()` method returns `new A(i)` (where i is Byte 1).
As a result, an instance of A with `i` field set to 1 is assigned to variable `i` in the main method. Thus, `i.i` is 1.
Evaluation of `var j = a.a_(a);`
This is the most critical point. In Java, which overloaded method to call is determined at compile time based on the declared type of the variable. The compiler sees the call `a.a_(a)`. The declared type of variable `a` is A. The argument `a` is also of declared type A.
The compiler looks for an `a_` method that can be called on variable of type A. Class A only has the method `a_(Object i)`. (The method `a_(A a)` defined in Class B is not visible at this point because the variable type is A).
Therefore, at compile time, it is decided to call the `a_(Object i)` method. Next, at runtime, it is determined which overridden method to execute. The actual instance of `a` is B.
Class B overrides the `a_(Object)` method as `public B a_(Object j)`. Therefore, Class B's `a_(Object j)` method is actually executed.
This method executes `return new B();`. When a B instance is created, the no-argument constructor `B()` is called, which implicitly calls the parent class's no-argument constructor `A()`.
In the `A()` constructor, the `Byte i` field is not initialized. Since Byte is a wrapper class (object), the default value for an uninitialized field is `null`.
As a result, an instance of B with `i` field set to `null` is assigned to variable `j` in the main method. Thus, `j.i` is null.
Execution of `System.out.println(""+i.i+j.i);`
`i.i` is 1. `j.i` is null. The expression evaluates to `"" + 1 + null`.
Due to string concatenation, it becomes `"1" + null`, and finally the string "1null" is output.
34:Choose the correct result when compiling and executing the following code.
public class Main{
protected static int i;
public static void main(String[] args) {
Main[]i= {new Main(),new A(),null};
i[2]=count(i);
int k=0;
while(k<i.length) {
if(i[k] instanceof A)Main.i++;
k++;
}
System.out.println(Main.i);
}
static void a(Main j) {
if(j instanceof A)Main.i++;
else if(j instanceof Main)--i;
else Main.i+=2;
}
static Main count(Main[] i) {
for(Main j:i) {
a(j);
return Main.i>0?new A():new Main();
}
}
}
class A extends Main{
static void a(Main j) {
if(j instanceof A)i++;
else if(j instanceof Main)--Main.i;
else Main.i-=2;
}
}
A:0
B:1
C:2
D:3
E:Compilation error
F:Exception occurs at runtime
Check the answer
A method whose return type is set to something other than void (in this case, Main) must reach a return statement regardless of the execution path taken. In the `count` method, the only return statement is inside the for-each loop. If the array `i` passed as an argument is an empty array (zero elements), this for-each loop will not execute even once. As a result, execution would pass through the loop and reach the end of the method, but since there is no return statement there, the compiler determines that "the method might end without returning a value". This causes a "missing return statement" compilation error. Therefore, this program cannot generate an executable file (.class file) and cannot be run.
35:Choose the correct method definition from the following.
A:void $(){throw new OutOfMemoryError();}
B:void _() throws Exception{return;throw new Exception();}
C:float $$(float i){return 2.0/i;}
D:float _$(){throw new RuntimeException();System.out.println();}
E:A and C
F:None of the above is correct
Check the answer
A: Correct: OutOfMemoryError is a subclass of Error and is an unchecked exception. A throws clause is not required, and no compilation error occurs. B: Incorrect: When `return;` is executed, the method ends. The subsequent `throw new Exception();` becomes unreachable code, causing a compilation error. C: Incorrect: `2.0` is a double literal. The result of `2.0 / i` is double type. Returning a double value as a smaller float return type without an explicit cast is a narrowing conversion and causes a compilation error. (Correctly, `return (float)(2.0/i);` is needed.) D: Incorrect: When `throw new RuntimeException();` is executed, the method terminates immediately. The subsequent `System.out.println();` becomes unreachable code, causing a compilation error.
|
|
36:Choose the correct result when compiling and executing the following code.
import java.util.List;
public class Main{
private static int p;
public static void main(String[] args) {
List<Integer>i=List.of(0,1,2,3,4);
a:do {
b:for(;;) {
System.out.print(";");
c:for(int j=0;j<1;) {
for(int k:i) {
if(k%2==1)break;
else System.out.print(k);
}
for(int k:i) {
if(k%2==0)break c;
else System.out.print(k);
}
}
for(int k:i) {
if(k%3==0&p==0) {p++;continue a;}
else System.out.print(k);
break a;
}
}
}while(true);
}
}
A:;0
B:;00
C:;0;00
D:Infinite loop occurs
E:Compilation error
F:Exception thrown at runtime
Check the answer
1st do-while loop (label a)
Enters infinite for loop (label b). `System.out.print(";");` is executed.
Enters for loop (label c).
First extended for loop:
When k is 0: `0 % 2 == 1` is false (0 is even). Executes `System.out.print(k);` in else, printing 0.
When k is 1: `1 % 2 == 1` is true (1 is odd). `break;` is executed, exiting this extended for loop.
Next extended for loop:
When k is 0: `0 % 2 == 0` is true (0 is even). `break c;` is executed, forcibly exiting the entire for loop labeled c. Processing proceeds to the line after for loop c.
Last extended for loop:
When k is 0: Evaluates condition `if (k%3==0 & p==0)`. `0 % 3 == 0` is true AND `p == 0` is true.
`p++;` updates value of p from 0 to 1. `continue a;` is executed, returning to the beginning of the do-while loop labeled a, starting the next iteration.
2nd do-while loop (label a)
Enters infinite for loop (label b).
`System.out.print(";");` is executed. Enters for loop (label c).
First extended for loop:
When k is 0: Outputs 0. When k is 1: Exits this loop with `break;`.
Next extended for loop:
When k is 0: `break c;` is executed, forcibly exiting the entire for loop labeled c.
Last extended for loop:
When k is 0: Evaluates condition `if (k%3==0 & p==0)`. `0 % 3 == 0` is true, but `p == 0` is false (since p is 1). The condition is false overall. Executes `else System.out.print(k);`, outputting 0. `break a;` is executed, exiting the entire do-while loop labeled a, and the program ends.
37:Choose the correct result when compiling and executing the following code.
import java.util.*;
public class Main extends A {
private long i;
public static void main(String[] args) {
Main i = new Main();i.i=i.a(2, 2);
if(i.b(new ArrayList()))System.out.println(i.i);
else System.out.println(-i.i);
}
}
class A {
final byte a(float i, long j) {return 2;}
protected int a(int i, double j) {return 1;}
boolean b(Collection i) {return true;}
boolean b(List i) {return false;}
}
A:1
B:2
C:-1
D:-2
E:Compilation error
F:Exception thrown at runtime
Check the answer
The reason this code causes a compilation error is in the line `i.i=i.a(2, 2);` inside the main method. Here the method `a` is called, but parent class A defines two methods named `a`. One takes arguments `(int i, double j)`. The other takes arguments `(float i, long j)`. When passing two integers 2 and 2 as arguments like `i.a(2, 2)`, the compiler cannot decide which `a` method to call. The argument 2 is int type, but int type can be converted to double, float, or long. Therefore, for the compiler, both `a(int i, double j)` and `a(float i, long j)` are candidates for the call, and since there is no clear rule to prioritize one over the other, an "ambiguous method call" error occurs. By the way, if this compilation error did not exist, the call `i.b(new ArrayList())` in the next if statement would select the `b(List i)` method. Although ArrayList is a Collection, the method taking the more specific type List is prioritized.
38:Choose the correct result when compiling and executing the following code.
public class Main {
private static byte count;
public static void main(String[] k) {
A a=new B();
var b=(B)a;
C c=(C)b;
var d=a.a();var e=c.a();
A[]i= {a,b,c,d,e};
for(var j:i) {
if(j instanceof C)count++;
else if(j instanceof B)--count;
else count/=0.5;
}
}
}
sealed abstract class A permits B{abstract A a();}
non-sealed class B extends A{B a() {return new B();}}
class C extends B{C a() {return new C();}}
A:-2
B:-1
C:0
D:1
E:Compilation error
F:Exception thrown at runtime
Check the answer
The problem is the line `C c=(C)b;` in the main method. `A a=new B();`: Variable `a` is type A, but the content is an instance of class B. `var b=(B)a;`: The content of variable `a` (B instance) is cast (type converted) to type B. This succeeds without issues. Variable `b` becomes type B. `C c=(C)b;`: Attempts to cast the content of variable `b` (B instance) to type C. Here a problem occurs. C is a child class inheriting from B, but the content of `b` is purely a B instance created with `new B()`, not an instance of C. You cannot forcibly convert an instance of a parent class (B) to a child class type (C), so a `ClassCastException` (runtime exception) is thrown when this line executes, and the program terminates forcibly.
39:Which of the following code fragments does not cause a compilation error?
A:private record A(int j) implements B{static int i;}
public interface B{}
B:abstract record A(String i, int j){private static int k=1;}
C:sealed record A(int i)permits B{A(int i){if(i<0)throw new RuntimeException();}}
D:public record A(String i, int...j){public int k;}
E:record A(int i) implements B{}
interface B{default void i(){}}
F:final record A extends Record{}
G:None of the above is correct
Check the answer
int j;}
A: `private record A(int j) ...`: You cannot specify the private access modifier for a top-level type (class, interface, record, etc.). Only public or package-private (no modifier) are permitted.
B: `abstract record A(...)`: Records are implicitly final and assume they will not be inherited. Therefore, they cannot be defined with the abstract keyword.
C: `sealed record A(int i){...}`: Since records are always final, they cannot be inherited further. Therefore, you cannot use the sealed modifier on a record. Sealed is used on classes to control inheritance.
D: `public record A(...){public int k;}`: Records cannot declare instance fields (non-static fields) other than components (variables defined in parentheses ()). `public int k;` tries to add an instance field, causing an error.
E: `record A(int i) implements B{}` and `interface B{default void i(){}}`: `record A(int i)` implicitly generates an accessor method (method to get value) named `public int i()`. Meanwhile, interface B has a method `default void i()`. When A implements B, two methods with the same name (i) but different return types (int vs void) conflict, causing a compilation error.
F: `final record A extends Record{}`: All records automatically inherit the `java.lang.Record` class without the developer needing to write it explicitly. It is grammatically prohibited for developers to explicitly write `extends Record` in the code. Also, they cannot `extends` other classes.
40:Choose three code fragments that throw an exception from the following. Assume the java.util package is imported in each code.
A:List i=List.of(new Object(),1,"2");i.add(false);i.remove(3);
B:Collection i=Arrays.asList(new Object[]{new Object(), true, ' ',3});i.add(false);i.remove(3);
C:Collection<Object> i=List.of(new ArrayList(), new List(), new Collection());i.get(0);
D:List i=new ArrayList();i.add(1);i.remove(1);
E:List i=Arrays.asList(new Number[]{1,2.0,100});i.get(0);
F:ArrayList<Integer> i=new ArrayList<>();i.add(2.0);i.remove(0);
Check the answer
Re-explanation of the three codes that throw exceptions
The code fragments that throw an exception (RuntimeException) at runtime are A, B, and D.
A: `List i=List.of(new Object(),1,"2");i.add(false);i.remove(3);`
The `List.of()` method creates an unmodifiable list (immutable list). Trying to add elements like `i.add();` or `i.remove();` throws an `UnsupportedOperationException` at runtime because the list size cannot be changed.
B: `Collection i=Arrays.asList(new Object[]{new Object(), true, ' ',3});i.add(false);i.remove(3);`
The `Arrays.asList()` method creates a fixed-size list backed by the array. Similarly, attempting to add elements like `i.add();` or `i.remove();` throws an `UnsupportedOperationException` at runtime because the list size cannot be changed.
D: `List i=new ArrayList();i.add(1);i.remove(1);`
In the first two lines, list `i` contains only one element `[1]` (element 1 exists at index 0).
The argument 1 in `i.remove(1);` is interpreted as an index, not the element value. Since the list only has an element at index 0, trying to remove index 1 which does not exist throws an `IndexOutOfBoundsException` at runtime.
Code fragments that do not throw exceptions (or are compilation errors)
C: `Collection
コメント