PR

Java silver se17 Quizzes 3

Java

21:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String... args) {
	A a=new A("a");
	A b=new A("a");
	A c=new B("a");
	B d=new B("b");
	System.out.print(""+(a==b)+(a.equals(b)));
	System.out.print(""+(c==d)+(c.equals(d)));
	}
}
class A{
	String i;
	A(String i){
		this.i=i;
	}
}
class B extends A{
	String i;
	B(String i){
		super(i);
	}
	public boolean equals(Object i) {
		if(i instanceof B b)
		return this.i==b.i;
		else return false;
	}
}
Copy Code

A:falsetruefalsefalse
B:truetruefalsefalse
C:falsefalsefalsefalse
D:falsefalsefalsetrue
E:Compilation error
F:NullPointerException thrown at runtime

 

Check the answer

 

D:falsefalsefalsetrue
First output: (a == b) + (a.equals(b))
a == b: Since a and b refer to different objects, the result is false.
a.equals(b): Class A does not override the equals method. Therefore, the equals method of the Object class is called, which behaves the same as a == b, so the result is false.

Second output: (c == d) + (c.equals(d))
c == d: Since c and d refer to different objects, the result is false.
c.equals(d): c and d are instances of Class B, so the equals method overridden in Class B is executed.
Inside the method, `if(i instanceof B b)` is true.
`return this.i == b.i` is evaluated.
Class B has a field `i` with the same name as its superclass A. Inside B's constructor, the parent class A's constructor is called via `super(i);`, assigning to A.i, but no assignment is made to B.i.
Therefore, the instance variables c.i (as B) and d.i (as B) both remain at their default value of null.
null == null is true.

22:Choose the correct result when executing the following code with the following command.

>java A He llo “He llo” 1 2 3

public class  A{
	public static void main(String... i) {
		i=replace(4,i);
		for(int j=0;j<i.length;j++) {
			if(i[j] instanceof String a)
				System.out.print(a);
			    System.out.print(" ");
		}
	}
	static String[] replace(int i, String ...j) {
		if(i>j.length|i<0)i=j.length;
		String[]l=new String[i];
		for(int k=0;k<l.length;k++) {
				l[k]=j[k].replace(" ", "");
		}
                return l;
	}
}
Copy Code

A:He llo Hello 1
B:He llo Hello 1 2
C:He llo He llo 1 2 3
D:A He llo Hello
E:Compilation error
F:Exception thrown at runtime

 

Check the answer

 

A:He llo Hello 1
1. Argument passing
With the command `java A He llo "He llo" 1 2 3`, the argument `i` of the main method stores the following 6 strings:
i={"He","llo","He llo","1","2","3"}

2. replace method processing
`i = replace(4, i);` is executed.
Creation of new array: The value 4 from `i` is used as the array size, creating a new array `l` of size 4.
Element manipulation: The loop processes the first 4 elements of the original array `i`. `j[k].replace(" ", "")` removes all half-width spaces from each element.
`i` in the main method is replaced by this array: {"He", "llo", "Hello", "1"}.

3. Output processing
The for loop in the main method processes the new 4-element array in order. After printing each element, `System.out.print(" ");` always outputs a half-width space.

23:Which of the following classes or interfaces causes a compilation error?

public interface A{
	A a(A a);
}
abstract class B{
	abstract B b(B b);
}
abstract class C extends B implements D{
	C b(B b) {
		return new E();
	}
}
interface D extends A{
	default A a(D d) {
		return new E();
	}
}
class E extends C{
	public A a(E e) {
		return new E();
	}
}
Copy Code

A:C
B:D
C:E
D:C, D, and E
E:C and D
F:D and E
G:No compilation error occurs

 

Check the answer

 

C:E
Class E inherits from C, and ultimately bears the obligation to implement the abstract method of Interface A.
Abstract method defined in `interface A`: `A a(A a);`
`abstract class C` does not implement this method, but since it is an abstract class, that is fine.
`class E` is a concrete class, so it must implement this abstract method.

2. Implementation in Class E
Required signature (inherited from A): `A a(A a)`
Defined signature (defined in E): `A a(E e)`
The method in E changes the argument type from A to its subclass E. This is considered an overload (definition of a new method), not an override.

3. Occurrence of compilation error
Class E does not provide a matching implementation for the inherited abstract method `A a(A a)`. Nevertheless, since E is a concrete class not declared as abstract, the following compilation error occurs:
Error: Class E must implement the abstract method `A a(A a)` inherited from the superclass, or declare itself as abstract.

Checking other classes
A, B: Only declarations, no problem.

D: `default A a(D d)` is an overload because the signature differs from `A.a(A a)`, but since it is an interface, there is no problem.

C: Since it is an abstract class, it does not have to implement `A.a(A a)`. Also, `C b(B b)` is a valid override of `B.b(B b)` (the return type can be changed to B's subclass C due to covariant return types).

24:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String[] args) {
		int a=0b1001, b=0b101;
		if((a&b++)>(a|++b)&b-->0)System.out.print(b<<2);
		if((--a^b)<(~b)&&b-->0)System.out.print(b>>2);
		if((-a>>2)<(-a>>>2)|a<(b<<1)|a++>3||a-->2)
			System.out.print(a+b);		
	}
}
Copy Code

A:24214
B:15
C:2313
D:146
E:10
F:Compilation error occurs

 

Check the answer

 

B:15
1. `if((a&b++)>(a|++b)&b-->0)`
Evaluation of left side: `(a & b++) > (a | ++b)`
`a & b++` : `1001 & 0101` → `1`. `b` becomes `0110` due to post-increment.
`a | ++b` : `b` becomes `0111` due to pre-increment.
`1001 | 0111` → `1111`.
Comparison: `1 > 1111` → `false`.

Evaluation of logical AND (&): `&` does not perform short-circuit evaluation, so the right side is also evaluated.
Right side `b-->0`:
`0111 > 0` → `true`.
`b` becomes `0110` due to post-decrement.

Final result `false & true` → `false` → The first if statement is not executed.

2. `if((--a^b)<(~b)&&b-->0)`
Evaluation of left side: `(--a^b) < (~b)`
`--a^b`: `a` becomes `1000` due to pre-decrement. `1000 ^ 0110` → `1110`.
`~b`: Bitwise complement of `b=110` → `1...1001` (Negative number because the 32nd bit is 1).
Comparison: `1110` (positive) < (negative) → `false`.

Evaluation of logical AND (&&):
The result of the left side is `false`. Since `&&` performs short-circuit evaluation, the right side `b-->0` is not evaluated.

→ The 2nd if statement is not executed, and the value of `b` remains `110`.

3. Evaluation of 3rd if statement and output
`if((-a>>2)<(-a>>>2)|a<(b<<1)|a++>3||a-->2)`
Evaluation of logical OR (|) (no short-circuit): `|` does not short-circuit, so the first three conditions are evaluated in order.

`(-a >> 2) < (-a >>> 2)`
Signed right shift of `-a` (`1...1000`): `-a >> 2` → `1...10` (negative number).
Zero-fill right shift: `-a >>> 2` → `001...10` (positive number).
Comparison: (negative) < (positive) → `true`.

Since the first condition is `true`, the overall result will be `true`, but the remaining conditions connected by `|` are still evaluated.

`a < (b << 1)`
Left shift of `b` (`110`): `b << 1` → `1100`.
Comparison: `1000 < 1100` → `true`.

`a++ > 3`
`1000 > 3` → `true`.
`a` becomes `1001` due to post-increment.

Evaluation of logical OR (||) (with short-circuit):
At `(true | true | true)`, the result is already `true`. Since `||` performs short-circuit evaluation, the right side `a-->2` is not evaluated.
→ The 3rd if statement is executed.

5. Output `System.out.print(a + b);`
Final value of `a`: `1001` = 2^3 + 1 = 9. Final value of `b`: `110` = 2^4 + 2^1 = 6.
`a + b` = 9 + 6 = 15.

25:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String[] args) {
		A a=new C("1");B b=new C("2");
		Main c=new Main();
		System.out.print(a);
		System.out.print(a.toString());
		System.out.print(b);
		System.out.print(c);
	}
}
abstract class A{
	static String i;
	public String toString() {
		return new C("3").i;
	}
}
interface B{
	public default String toString() {
		return "B";
	}
}
class C extends A implements B{
C(String i){
super.i=i;
}
Copy Code

A:a@372f7a8dbc
B:@372f7a8d@372f7a8d@4517d9a3@372f7a8d
C:33B@372f7a8d
D:12B@372f7a8d
E:Compilation error occurs
F:Exception thrown at runtime

 

Check the answer

 

E:Compilation error occurs
The reason this code causes a compilation error lies in the declaration of the `toString()` method within interface B.
Under Java rules, an interface cannot redefine public methods of the Object class (such as `toString()`, `equals()`, `hashCode()`, etc.) as default methods.
Due to this rule, the declaration `default String toString()` in interface B violates the Java language specification, so the compiler generates an error when attempting to compile this code.

26:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String[] args) {
		double[]i[]= {{1.9,0.5},{5.01},{}};
		for(double[]l:i) {
			for(double k:l) {
				new B().access((int)k);
			}
		}
		
	}
}
interface A{
	int i=2;
	void access(int i);
}
class B implements A{
	public void access(int i) {
		a:switch(i*2) {
		case A.i:;
		case 3*3:System.out.print(1);
		default: System.out.print(2);
		break a;
		case 1/3:System.out.print(3);
		case 3:System.out.print(4);
		}
	}
}
Copy Code

A:12342
B:222
C:132
D:1222
E:Nothing is output
F:Compilation error
G:Exception thrown at runtime

 

Check the answer

 

A:12342
1. Determination of input values
Through the double loop in the main method, the following three integer values are passed sequentially to `new B().access()`:
1: (int)1.9, 0: (int)0.5, 5: (int)5.01

Inside the `access(int i)` method, the key for the switch statement is `i * 2`.
1st time: 1 * 2 = 2, 2nd time: 0 * 2 = 0, 3rd time: 5 * 2 = 10

2. Behavior of switch statement (Determining output)
Each case value in the switch statement is determined at compile time.
`case A.i`: value is 2, `case 3*3`: value is 9, `case 1/3`: integer division, so value is 0, `case 3`: value is 3.

1st time: When i * 2 = 2 (Output: 12)
Matches `case 2` (case A.i). Processing starts.
Since there is no processing immediately after `case 2`, it falls through to the next `case 9`.
`case 9` processing `System.out.print(1);` is executed, printing 1.
Next, it falls through to `default`.
`default` processing `System.out.print(2);` is executed, printing 2.
Reaches `break a;`, exits the labeled switch statement entirely, and ends the method.

2nd time: When i * 2 = 0 (Output: 34)
Matches `case 0`, prints 3.
Next, falls through to `case 3` and prints 4.

3rd time: When i * 2 = 10 (Output: 2)
Matches no case label, so processing jumps to `default`.
`default` processing `System.out.print(2);` is executed, printing 2.
Reaches `break a;`, ending the switch statement.

27:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String[] args) {
	short o=2;long p=2;
	byte[]k[]=new byte[o*p][o*(int)p];
	System.out.print(extractLength(k));
		for(byte i=0,int j=0;i<k.length&j<k.length;i++,j++,dot()) {
			System.out.print(k[i][j]);
		}
	}
	static int extractLength(Object i) {
		if(!(i instanceof byte[][] a))
			return -1;
		else return a[0].length;
	}
	static void dot(){
		System.out.print(",");
	}
}
Copy Code

A:Compilation error occurs at 1 place
B:Compilation error occurs at 2 places
C:Compilation error occurs at 3 places
D:Output is 40,0,0,0
E:Output is -10,0,0,0
F:4
G:Exception thrown at runtime

 

Check the answer

 

B:Compilation error occurs at 2 places
Compilation Error 1: Array size specification
`short o=2;long p=2;`
`byte[]k[]=new byte[o*p][o*(int)p];` // ← Error here
`o` is short type, `p` is long type.
In the calculation `o * p`, the short type `o` is promoted (type promotion) to long, so the result is long type `4L`.
Array sizes cannot be specified with long type; they must be int type.
Therefore, it is interpreted like `new byte[4L][4]`, causing a compilation error in the size specification of the first dimension.

Compilation Error 2: Initialization block of for loop
`for(byte i=0,int j=0;i<k.length&j<k.length;i++,j++,dot()) {` // ← Error here
When declaring multiple variables in the initialization block of a for loop, they must all be of the same type.
This code attempts to declare two different types, byte type `i` and int type `j`, simultaneously, resulting in a syntax error and failure to compile. Correctly, types must match, like `int i=0, j=0;` or `byte i=0, b=0;`.

28:Choose the correct result when compiling and executing the following code.

public class  Main{
	public static void main(String[] args) {
	StringBuilder i=new StringBuilder();
	StringBuilder j=new StringBuilder(17);
	i.append("ab".repeat(8)).append("cd".repeat(1));
	i.replace(1, 16, "").reverse();
	i.deleteCharAt(1).insert(1,'e');
	if(i.capacity()<j.capacity())System.out.print(i.reverse());
	else System.out.println(i);
	}
}
Copy Code

A:Nothing is output
B:aecd
C:dcea
D:dea
E:aed
F:Compilation error
G:Exception thrown at runtime

 

Check the answer

 

D:dea
1. Initialization and Capacity
`j` is initialized with `new StringBuilder(17)`, so its capacity (`j.capacity()`) is 17.
`i` is initialized with `new StringBuilder()`, so its default capacity (`i.capacity()`) is typically 16.

2. Content manipulation of `i`
`i.append("ab".repeat(8)).append("cd".repeat(1));`
`"ab".repeat(8)` is 16 characters: "abababababababab".

2 characters "cd" are appended, making `i`'s content "ababababababababcd" (length 18).

Since length 18 exceeds the initial capacity of 16, `i`'s capacity is expanded (to be 18 or more).

Current: `i` content: "ababababababababcd", Capacity: 34

3. Replacement and Reversal
`i.replace(1, 16, "").reverse();`
`i.replace(1, 16, "")`:
15 characters from index 1 to 16 ('b' to 'b') are deleted.

Original string: a bababababababab cd
From this, 'a' at index 0, 'c' at index 16, and 'd' at index 17 remain.
`i`'s content becomes "acd".

`i.reverse()`: `i`'s content becomes "dca".

4. Final character manipulation
`i.deleteCharAt(1).insert(1,'e');`
`i.deleteCharAt(1)`: Character 'c' at index 1 is deleted. `i`'s content becomes "da".

`i.insert(1, 'e')`: 'e' is inserted at index 1. `i`'s content becomes "dea".

5. Condition check and output
`if(i.capacity()<j.capacity())System.out.print(i.reverse());`
`else System.out.println(i);`
`i.capacity()` is 34. `j.capacity()` is 17.
34 < 17 is false.
→ The `else` block is executed, and the current content of `i`, "dea", is output with a newline.

29:Choose the correct code that can be written in ■■■■■■ of the following code.

public class  Main{
	public static void main(String[] args) {
	long i=1l;float f=2f;Character c='a';Byte b=2;
■■■■■■
	}
}

Copy Code

A:int j=switch(c){case 'a':yield 2;
case 'b':yield 1;};
B:int j=switch(i){default->1;
case 1->2;};
C:int j=switch(b){default->{System.out.print("d");yield 2;}
case 2->2;};
D:int j=switch(f){default:System.out.print(2);yield 2;
case 1:yield 1;};
E:None of the above is correct
F:A and B
G:A and C

 

Check the answer

 

C:int j=switch(b){default->{System.out.print("d");yield 2;}
case 2->2;};
A: Incorrect (Compilation error)
Control variable: `c` is Character (char) type.
Error reason: Since char type can take many values other than 'a' or 'b', the lack of a default block fails to satisfy exhaustiveness, causing a compilation error.

B: Incorrect (Compilation error)
Error reason: Control variable `i` is long type. `long` is not a valid type for a switch control variable, causing a compilation error. Usable types are int, byte, short, char, their wrapper classes (Integer, etc.), String, and enum.

C: Correct (Compilable)
Control variable: `b` is Byte type, which is valid for a switch control variable.
Exhaustiveness: Since a default block is written, exhaustiveness is satisfied.
Syntax: It is correct syntax for a switch expression, and compilation succeeds. `yield` is used to return values inside `{}`.

D: Incorrect (Compilation error)
Error reason 1: Control variable `f` is float type. `float` is not a valid type for a switch control variable, causing a compilation error.

30:Which of the following is correct to write in ■■■■■■■■■■■?

interface A{
	default void a() {}
}
interface B extends A{
	default void b() {}
}
abstract class C{
	void c() {}
        public void b(){}
}
abstract class D extends C{
}
■■■■■■■■■■■
Copy Code

A:final abstract class E extends D implements B{public void b(){}}
B:final interface E extends B{public void a(){}}
C:abstract class E extends D implements B{
protected void d(){super.c();B.super.b();A.super.a();}}
D:abstract interface E extends B{static void e1(){}
private void e2(){}
protected final void e3(){}}
E:abstract interface E extends B{public A(){}}
F:interface E extends B{int i;}
G:All are incorrect

 

Check the answer

 

G:All are incorrect
A: `abstract` (abstract) class is a modifier that assumes inheritance.
`final` class is a modifier that prohibits inheritance. These two contradictory modifiers cannot be specified on a class simultaneously.

B: Since interfaces are intended to be implemented, the `final` modifier cannot be attached.

C: Looks correct at first glance, but the call to `A.super.a()` is problematic.
When calling a default method with the syntax `InterfaceName.super.methodName()`, that `InterfaceName` must be an interface that the calling class directly implements (`implements`).
In this code, class E directly implements B, but A is an interface that B inherits from, not one that E implements directly (it is an indirect superinterface). Therefore, the call `A.super.a()` results in a compilation error.

D: You cannot attach `protected` or `final` modifiers to interface methods.

E: `public A(){}` is a constructor description.
Interfaces cannot be instantiated, so they cannot have constructors.

F: Fields (variables) declared in an interface are automatically treated as `public static final` (constants).
`final` fields must be initialized at declaration, but `int i;` is uninitialized, causing a compilation error. Correctly, you must assign a value like `int i = 10;`.

コメント