|
|
41:Choose two code fragments that do not cause a compilation error.
A:import java.util.ArrayList;
package a;
public class A{ArrayList i=new ArrayList();}
B:package a;
import java.util.*;
public class A{Collection i;List j;ArrayList k;}
C:import java.util.ArrayList;
public class A{List i=new ArrayList();}
D:package a;
import java.util.List;
import java.util.Collection;
public interface A{static List i=List.of();
static Collection<Character> j=new java.util.ArrayList();}
E:import java.util.ArrayList;
package a;
import java.util.List;
public record A{static java.util.Collection i; static List<Integer> j=new ArrayList();}
F:import java.util.*;
public abstract class A{List<int>i;}
Check the answer
Code fragments that do not cause compilation errors: B: Correct file structure: The package declaration is before the import declaration, following Java rules. Type resolution: `import java.util.*;` correctly resolves Collection, List, and ArrayList types. Grammar: Correct class field declarations; uninitialized fields are initialized to null. D: Correct file structure: The package declaration is followed by import declarations, which is correct. Interface fields: Interface fields are implicitly public static final, so they must be initialized at declaration. `static List i = List.of();` is validly initialized with an immutable list. `static Collectionj = new java.util.ArrayList();` is also validly initialized with an instance. Code fragments that cause compilation errors and their reasons: A: Error reason: Incorrect declaration order. The package declaration must be written before all import declarations. C: Error reason: ArrayList is imported, but List is not imported. E: Error reason: Incorrect declaration order. The package declaration is written after the import declaration. (However, the static field declaration in the record itself is valid.) F: Error reason: Misuse of generics. Primitive types (int) cannot be used as type arguments in generics (List<...>). You must use wrapper classes (Integer).
42:Choose the correct result when compiling and executing the following code.
public class Main {
static int i=2;static int j;
static boolean k;static String m;
static int[] l=new int[1];
public static void main(String[] k) {
if(i())System.out.println(j());
else System.out.println(j().toUpperCase());
}
static boolean i() {
try {
i/=j;
}catch(ArithmeticException ae) {
return k;
}catch(RuntimeException re) {
return !k;
}finally {k=true;}
return k;
}
static String j() {
try {
l[1]/=i;
}catch(ArrayIndexOutOfBoundsException iobe) {
return m;
}finally {m="hi";}
return m;
}
}
A:hi
B:HI
C:NULL
D:null
E:Compilation error
F:Exception thrown at runtime
Check the answer
1. Execution of i() method (if condition)
Division by zero occurs in the try block of i(), throwing an ArithmeticException.
static boolean i() {
try {
i/=j; // 2 / 0 throws ArithmeticException
} catch(ArithmeticException ae) {
return k; // Current value of k (false) is held as return value
} finally {
k=true; // k is updated to true
}
// After finally executes, the held false becomes the return value
}
The return value of i() is false.
2. Execution of else block
Since the if condition is false, the else block executes.
`else System.out.println(j().toUpperCase());`
3. Execution of j() method (Argument evaluation)
First, the j() method is called.
static String j() {
try {
l[1]/=i; // l is array of size 1 (index 0 only). l[1] throws ArrayIndexOutOfBoundsException
} catch(ArrayIndexOutOfBoundsException iobe) {
return m; // Current value of m (null) is held as return value
} finally {
m="hi"; // m is updated to "hi"
}
// After finally executes, the held null becomes the return value
}
The return value of j() is null.
4. Final exception occurrence
The execution in main method becomes:
`System.out.println(null.toUpperCase());`
Attempting to call the instance method `toUpperCase()` on a null reference throws a `NullPointerException` at runtime, terminating the program abnormally.
43:Choose two correct descriptions regarding the following code.
public class M {
public static void main(String[] k) {
A a=new A(1,"2","3");
A b=new A(1,"2","3");
a.equals(b);//line a
a.hashCode();//line b
a.toString();//line c
a.i();//line d
}
public int i(){return 0;}
}
final record A(int i, String...j){}
A:In line a~c, methods of java.lang.Object class are executed
B:line a returns true
C:line c returns the hash code
D:line d returns 0
E:This code causes a compilation error
F:This code throws an exception at runtime
G:A private static final field i is created in record A and initialized with 1 when a is created.
H:A private final field j[] is created in record A and initialized with “2” and “3” when b is created.
Check the answer
Correct Descriptions
B: Record A automatically generates an `equals()` method based on component values. `a` and `b` are instances with identical values A(1, "2", "3"). Therefore, `a.equals(b)` judges that all component values are equal and returns true.
H: Record components (String...j) are implicitly defined as instance fields. Varargs (...) are treated as `String[]` type fields inside the record. Record component fields are always `private final` and are initialized with the values passed during instance creation (constructor execution). The values passed when creating `b` are "2" and "3".
Incorrect Descriptions
A: Record A automatically overrides Object's `equals()`, `hashCode()`, and `toString()` with implementations based on components. The base implementations of the Object class are not executed as is.
C: `line c` calls `a.toString()`, which returns a string containing the record components. It is `a.hashCode()` (line b) that returns the hash code.
D: `a.i()` calls the implicitly generated accessor method `public int i()` of class A. This returns the value of component `i`, which is 1. It is unrelated to the `public int i(){return 0;}` method defined in class M.
G: The field corresponding to the record component is generated as a `private final` instance field. It is not `static`.
44: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.
45:Choose the one code fragment that does not cause a compilation error.
A:try{Object i=null;i.toString();}catch(Exception i){}catch(RuntimeException j){}
B:try{String i=”1″;i.indexOf(“1”);}catch(StringIndexOutOfBoundsException |RuntimeException i){}
C:a:try{return;}finally{return;}
D:try{}catch(Throwable t){}finally{}finally{}
E:All of the above are correct
F:None of the above is correct
Check the answer
A: This causes a compilation error. In Java's try-catch syntax, when defining multiple catch blocks, more specific exceptions (subclasses) must be written before more general exceptions (superclasses). RuntimeException is a subclass of Exception. In this code, the superclass Exception is caught first, so the subsequent RuntimeException catch block is unreachable. It becomes an error as "unreachable code". B: In a multi-catch syntax using | (pipe), you cannot simultaneously specify exceptions that have an inheritance relationship, such as RuntimeException and its subclass StringIndexOutOfBoundsException. C: This does not cause a compilation error. `a:` is a label and is fine. When there is a `return;` statement in both the try block and the finally block, the `return;` in the finally block is executed. D: This causes a compilation error. Only one finally block can be written for a single try block. Since there are two consecutive finally blocks, it is a syntax error.
|
|
46:Choose the correct result when compiling and executing the following code.
import java.util.ArrayList;
public class Main {
public static void main(String[] k) {
ArrayList i=new ArrayList();
i.add(new ArrayList());
((ArrayList)i.get(0)).add(0);
((ArrayList)i.get(0)).add(0,2);
((ArrayList)i.get(0)).remove(0);
i.add(new String("1"));
i.add(1,new int[] {2});i.add(2,2);i.set(2,1);
print(i);
}
static void print(ArrayList i) {
for(Object j:i) {
if(j==(Integer)1)i.remove(j);
else System.out.print(j);
}
}
}
A:[0][2]
B:[0][I@5ca881b5
C:[I@5ca881b5[2]
D:[0][I@5ca881b51
E:Compilation error
F:Exception thrown at runtime
Check the answer
Preparation of list i in main method
First, let's see how the ArrayList `i` changes in the main method before `print` is called.
`ArrayList i = new ArrayList();` `i` is an empty list [].
`i.add(new ArrayList());` An empty ArrayList is added to `i`. State of i: `[ [] ]`
`((ArrayList)i.get(0)).add(0);` 0 is added to the 0th element (list) of `i`. State of i: `[ [0] ]`
`((ArrayList)i.get(0)).add(0, 2);` 2 is inserted at index 0 of the 0th element (list) of `i`. State of i: `[ [2, 0] ]`
`((ArrayList)i.get(0)).remove(0);` The 0th element of the 0th element (list) of `i` is removed. State of i: `[ [0] ]`
`i.add(new String("1"));` String "1" is added to `i`. State of i: `[ [0], "1" ]`
`i.add(1, new int[] {2});` int array {2} is inserted at index 1 of `i`. State of i: `[ [0], int[] {2}, "1" ]`
`i.add(2, 2);` Integer 2 is inserted at index 2 of `i`. State of i: `[ [0], int[] {2}, 2, "1" ]`
`i.set(2, 1);` The element at index 2 (2) is replaced with Integer 1.
The final state of `i` when `print(i)` is called is a list with these 4 elements: `[ [0], int[] {2}, 1, "1" ]` (0th: List, 1th: Array, 2nd: Integer 1, 3rd: String "1")
Loop processing in print method
Next, the `print` method processes this list `i`. The loop `for(Object j : i)` processes elements of list `i` sequentially starting from the 0th element into variable `j`.
Loop 1st iteration
`j` holds the 0th element `[0]` (List). The condition `if (j == (Integer)1)` is false.
The `else` block executes, and `System.out.print(j)` outputs `[0]`.
Loop 2nd iteration
`j` holds the 1st element `int[] {2}` (Array). The `if` condition is false.
The `else` block executes, and `System.out.print(j)` outputs the array reference (string starting with `[I@`).
Loop 3rd iteration
`j` holds the 2nd element `1` (Integer). The condition `if (j == (Integer)1)` is true.
`i.remove(j)` is executed. This command removes the element with value `(Integer)1` from list `i`. The 2nd element `1` is removed. As a result, list `i` itself changes to state `[ [0], int[] {2}, "1" ]`.
Loop 4th attempt
Since the 2nd element was removed, the element "1", which was the 3rd element, shifts up to become the current element being evaluated. The `for` loop attempts to advance to the next element to process. Since there is no element after "1", there are no more elements to process, and the loop terminates. Thus, "1" is never processed, and the program ends after outputting `[0][I@...`.
47:Choose two correct class A definitions that can be written in ■■■.
public class Main {
public static void main(String[] k) {
try(A a=new A()){}
}
}
■■■
A:class A implements Closeable{public void close(){}}
B:class A implements AutoCloseable{public void close(){}}
C:class A implements java.io.Closeable{
@Override
public boolean close() {}}
D:class A extends AutoCloseable{public void close(){}}
E:class A implements java.io.Closeable{
@Override
public void close(){}}
F:class A implements AutoCloseable{public void open(){}}
Check the answer
You need to define `class A` such that the try-with-resources statement (`try(A a=new A()){}`) does not cause a compilation error. Classes used in try-with-resources must implement either `java.lang.AutoCloseable` or `java.io.Closeable`. Since nothing is imported in the given code, if you use `Closeable` from the io package, you must write `java.io.Closeable`. `AutoCloseable` belongs to the `java.lang` package, which is implicitly imported for all classes, so you can simply write `AutoCloseable`.
Also, a class implementing `Closeable` or `AutoCloseable` must override `public void close(){}`.
48:Choose the correct result when compiling and executing the following code.
public class Main {
private Integer i;
public static void main(String[] k) {
Main a=new Main();a.i=2;a.insert(1);
a.check();
}
void insert(int i) {
this.i=new Main().i;
}
void check() {
switch(this.i) {
case 0:System.out.println("zero");
break;
case 1:System.out.println("one");
break;
case 2:System.out.println("two");
break;
default:System.out.println("something else");
}
}
}
A:zero
B:one
C:two
D:something else
E:Compilation error
F:Exception thrown at runtime
Check the answer
1. Start of main method `Main a = new Main();` A new instance of Main class is created and assigned to variable `a`. At this time, the instance variable `i` of Integer type is initialized to null. `a.i = 2;` 2 is assigned to instance variable `i` of variable `a`. `a.insert(1);` Next, the `insert` method of `a` is called. 2. Execution of insert method The insert method (`void insert(int i)`) is executed. Argument `i` is passed as 1. The processing inside the method (`this.i = new Main().i;`) is executed. `new Main()` temporarily creates a new instance of Main class. The instance variable `i` of this new instance is initialized to null. This null is assigned to `this.i` (i.e., instance variable `i` of variable `a`). As a result, the value of `a.i` becomes null. 3. Execution of check method `a.check()` is called. The condition expression of the switch statement (`switch(this.i)`) inside the check method is executed. At this time, the value of `this.i` is null. In a switch statement, when using a wrapper type (like Integer), if a null value is passed, a `NullPointerException` occurs.
49:The following code causes a compilation error. Choose two options that resolve the compilation error when written inside C.
interface A{
default void a() {}
}
interface B{
default void a() {}
}
public interface C extends A,B{}
A:default void b(){A.super.a();}
B:default void a(){throw new ArrayIndexOutOfBoundsException();}
C:default void a(){super.a();}
D:default void a(){A.super.a();}
E:default void b() throws Throwable{}
F:public static void a(){A.super.a();}
Check the answer
The compilation error in this code occurs because interface C inherits from both A and B, resulting in a conflict between two default methods with the same signature (`void a()`) (one from A and one from B). The compiler cannot determine which default implementation to use for C's `a()` method. To resolve this error, interface C itself must override (rewrite) the `void a()` method and explicitly redefine C's implementation of `a()`. Option B: This description is correct. Interface C overrides the `a()` method and defines a new implementation that "throws an exception". Since C's own implementation is provided, the ambiguity of whether to use A or B is gone, and the compilation error is resolved. Option D: This description is correct. Interface C overrides the `a()` method and defines its implementation as "explicitly calling A's default implementation (`A.super.a()`)". By explicitly stating which implementation to call, like `A.super.a()` or `B.super.a()`, the ambiguity is gone, and the compilation error is resolved. Other Options A and E: `default void b()...` This defines a new method `b()`, which does not resolve the problem of the conflicting `a()` method. C: When executing a default method of a parent interface, you must write it as `(ParentInterfaceName).super.(MethodName)`. F: `public static void a()...` Static methods cannot override default methods (instance methods). The conflict of `a()` is not resolved. Also, the `super` keyword cannot be used in static methods.
50:Choose the correct result when compiling and executing the following code.
public class Main {
public static void main(String[] k) {
A.i="M";System.out.print(A.i); A a=new A();
B b=new B(6);
}
}
class A{
static String i;
static {System.out.print(0);}
{System.out.print(1);}
static {i="A";}
}
class B{
private static int i;
B(int i){
this();System.out.print(this.i);
}
{System.out.print(2);}
static {System.out.print(3);}
{i=4;}
B(){i=5;}
}
A:0M1325
B:M01235
C:0M126
D:M1025
E:Compilation error
F:Exception thrown at runtime
Check the answer
`A.i = "M";`: First access to class A. Static elements of class A are initialized.
`static {System.out.print(0);}` is executed. Output: 0
`static {i="A";}` is executed, making `i` "A". After class initialization is complete, `A.i = "M";` is executed, overwriting `i` to "M".
`System.out.print(A.i);`: The current value of `A.i`, "M", is printed. Output: M
`A a = new A();`: Creates an instance of A. Instance initialization block is executed.
`{System.out.print(1);}` is executed. Output: 1
`B b = new B(6);`: First access to class B. Static elements of class B are initialized.
`static {System.out.print(3);}` is executed. Output: 3
Next, `B(6)` constructor is called to create an instance of B.
`this()` in `B(int i)` constructor calls the no-argument `B()` constructor first.
Before the `B()` constructor executes, the instance initialization blocks are executed.
`{System.out.print(2);}` is executed. Output: 2
`{i=4;}` is executed, making static `B.i` 4.
Next, the body of `B()` constructor executes. `i=5;` is executed, making static `B.i` 5.
`B()` finishes, returning to `B(int i)` constructor.
`System.out.print(this.i);` is executed.
Since class B has no instance field named `i` but only a static field `i`, `this.i` refers to static `B.i`. The current value of `B.i`, 5, is printed.
コメント