PR

Java silver se17 Quizzes 2

Java

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

package a;
public class A{
	protected static boolean i;
	A(boolean j){
		if(!i)System.out.print("A");
		this.i=j;
	}
	A(String k){
		this(true);
		if(!(k==null))System.out.print(k.toUpperCase());
	}
}
Copy Code
package b;
import a.A;
public class Main{
	public static void main(String[] args) {
		A b=new A(A.i);//line A
		A a=new A(null);//line B
		A c=new A(new String("a"));//line C
	}	
}
Copy Code

A: Compilation error occurs in one of line A~C
B: Compilation error occurs in two of line A~C
C: Compilation error occurs in all of line A~C
D: AAA
E: AA
F: A
G: Nothing is output

 

Check the answer

 

C: Compilation error occurs in all of line A~C
The compilation error is caused by an access violation to package-private members.

1. Access rights of Class A constructors
Both constructors of Class A in package `a` omit the access modifier.
A(boolean j){ ... }
A(String k){ ... }
When the access modifier is omitted, it becomes package-private (default access), meaning it can only be accessed from within the defined package (`package a`).

2. Access violation from Main Class
The Main class belongs to `package b`, which is a different package from Class A.

All constructor calls within the main method attempt to access package-private constructors from a different package, so they all result in a compilation error.
line A: A b = new A(A.i); → Access violation to constructor A(boolean).
line B: A a = new A(null); → Access violation to constructor A(String).
line C: A c = new A(new String("a")); → Access violation to constructor A(String).
Therefore, compilation errors occur in all lines from A to C.

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

package a;import b.A;
public class Main extends A{
	int i=12;
	 Main(int i) {
		super(i);
	}
	 public int i(int i) {
		 return this.i+=i;
	 }
	public static void main(String[] args) {
		A a=new Main(3);
		Main m=new Main(2);
		a.i(a);a.i();a.i(a.i);m.i(m);m.i();m.i(m.i);
		System.out.println(""+a.i+((Main)a).i+m.i+((A)m).i);
	}
}
Copy Code
package b;
class A{
	public int i=2;
	protected A(int i) {
		this.i+=i*2;
	}
	protected void i(A a) {
		a.i/=this.i+1;
	}
	public void i() {
		this.i+=i+5;
	}
	public int  i(int i) {
		return i+10;
	}
}
Copy Code

A:512245
B:517245
C:5.112245.1
D:5.117245.1
E:1012202
F:Compilation error

 

Check the answer

 

B:517245


1. Initialization
First, two objects are initialized.
A a = new Main(3):
super(3) is executed, setting the superclass side (A.i) of `a` to 2 + (3 * 2) = 8.
The subclass side (Main.i) remains the initial value 12.
Main m = new Main(2):
super(2) is executed, setting the superclass side (A.i) of `m` to 2 + (2 * 2) = 6.
The subclass side (Main.i) remains the initial value 12.
Initial state: a.A.i=8, a.Main.i=12 / m.A.i=6, m.Main.i=12

2. Method calls and field updates
Processing 1-2: a.i(a) and a.i()
When a.i(a) is executed, the method A.i(A a) of the static type A is executed. This method references the a.A.i field, calculates 8 / 9 = 0, and sets a.A.i to 5 (after 8 / (8 + 1) = 0, the next a.i() makes it 0 + 0 + 5 = 5).
At this point, a.A.i is updated to 5, but a.Main.i remains 12.

Processing 3: Importance of a.i(a.i)
The call is made on `a`, and the signature is i(int). Since i(int) of class A is overridden in class Main, Main.i(int i) (the actual object's method) is executed.
The argument a.i references the hidden superclass field a.A.i (value 5) because the static type of reference variable `a` is A.
The executed code is this.i += i; inside Main.i(int i). `this.i` always refers to the subclass field Main.i.
Update: The value of a.Main.i (12) has the argument value (5) added to it, updating a.Main.i to 17.

Processing 4-5: m.i(m) and m.i()
Similar processing to `a` is performed on `m`. m.A.i goes from 6 to 0, and is finally updated to 5.

Processing 6: m.i(m.i)
Main.i(int i) is executed just like with `a`.
The argument m.i references m.Main.i (value 12) because the static type of reference variable `m` is Main.
Update: The value of m.Main.i (12) has the argument value (12) added to it, updating m.Main.i to 24.

3. Final Output
System.out.println(""+a.i+((Main)a).i+m.i+((A)m).i);
a.i: Reference type A → Value of a.A.i is 5
((Main)a).i: Reference type Main → Value of a.Main.i is 17
m.i: Reference type Main → Value of m.Main.i is 24
((A)m).i: Reference type A → Value of m.A.i is 5
Concatenating these results in 517245.

13:Which of the following methods can be written in class A?

public class Main {
	public static void main(String[] args) {
	}
	final void a() {}
	protected void b() {}
	private void c() {}
}
class A extends Main{
}
Copy Code

A:public void a(){}
B:void b(){}
C:void c(){}
D:@Override
public void c(){}
E:C and D
F:B, C, and D

 

Check the answer

 

C:void c(){}
A: public void a(){} → Compilation error
The superclass method a() has the final modifier. Final methods are prohibited from being redefined (overridden) in child classes, so this causes an error.

B: void b(){} → Compilation error
The superclass method b() is protected. The access modifier of an overriding method cannot be weaker than that of the superclass.
The void b(){} in option B has package-private (default) access, which is weaker than protected, violating the overriding rules and causing an error.

C: void c(){} → No compilation error
The superclass method c() is private. Private members are not inherited by child classes.
Therefore, defining void c(){} inside class A is not an override, but simply defining a new, independent method in class A. This is legal.

D: @Override public void c(){} → Compilation error
Since the superclass's c() method is not inherited, there is no method to override. Attaching the @Override annotation to a method that does not override anything results in an error.
Based on strict Java rules, only definition C does not cause a compilation error.

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

public class Main {
	public static void main(String[] args) {
		Main a=new A("1");A b=new A(1);Main c=new Main(2);
	}
    private void a() {System.out.print("a");}
    void b() {System.out.print("b"); }
    Main(){a();b();}
    Main(int i){this(); }
}
class A extends Main{
	void a() {System.out.print("A");}
	void b() {System.out.print("B");}
	A(int i){super(i);}
	A(String i){System.out.print("S");}
}
Copy Code

A:Sabab
B:ABSABab
C:SABab
D:aBSaBab
E:Compilation error
F:Exception thrown at runtime

 

Check the answer

 

D:aBSaBab
The key to solving this problem is understanding the order of constructor calls and method overriding (especially the behavior of private methods).
Private methods are not overridden:
The a() method in the Main class is private. This means it is hidden from outside the Main class. Even if you define a() in the subclass A, it is not an override but a completely separate new method definition.
Therefore, when a() is called inside the Main class constructor, it always refers to the Main class's a() method.
The Main class's b() method has no access modifier, so it can be overridden by a subclass in the same package.
When b() is called inside the constructor, either Main's b() or A's b() is executed depending on the actual class of the generated object (polymorphism).

Step-by-step Execution Trace
1. Main a = new A("1");
The constructor A(String i) of Class A is called.
Since there is no explicit super() call, the no-argument constructor super() of the superclass (Main) is implicitly called first.
The Main() constructor is executed.
a() is called. Since it is private, Main's a() is executed, outputting "a".
b() is called. Since the object being created is A, the overridden A's b() is executed, outputting "B".
Execution of Main() finishes, returning to A(String i).
System.out.print("S"); is executed, outputting "S".
Output so far: aBS

2. A b = new A(1);
The constructor A(int i) of Class A is called.
super(i) calls the superclass constructor Main(int i).
Inside Main(int i), this() calls the no-argument constructor Main() of the same class.
The Main() constructor is executed.
a() is called. Being Main's private method, "a" is output.
b() is called. The object is A, so the overridden A's b() is executed, outputting "B".
Main() finishes, returns to Main(int i) which finishes, returns to A(int i) which finishes.
Output so far: aBSaB

3. Main c = new Main(2);
The constructor Main(int i) of Class Main is called.
this() calls the no-argument constructor Main().
The Main() constructor is executed.
a() is called. Being Main's private method, "a" is output.
b() is called. The object is Main, so Main's b() is executed, outputting "b".
Main() finishes, Main(int i) finishes.
Based on the flow above, the final output is aBSaBab.

15:How many compilation errors occur in the following code?

public class $ {
	private var _=2;
	public static void main(String[] args) {}
	public static var a%(var i) {
		var j= {1,2,3};
		var k=new Integer[2][];
		var _k1$=new Short[] {3,4};
		var 2k=new Byte[] {5};
                var m=null;
		int sum=0;
		for(var l:j) {
			sum+=(int)l;
		}
	}
}
Copy Code

A:4
B:5
C:6
D:7
E:8
F:9

 

Check the answer

 

E:8
This code contains multiple violations regarding `var` usage restrictions, identifier naming rules, and method naming rules.

1. Method Name Error (1 place)
public static var a%(var i) (Method name)

Error 1: The percent sign (%) used in the method name a% is not a valid character for identifiers (method names, variable names, etc.). Only _ and $ are allowed symbols in identifiers.

2. `var` Usage Restriction Errors (5 places)
`var` can only be used for local variables, and the type must be clearly inferable from the initialization expression.

private var _=2;
Error 2: `var` cannot be used for class field (instance variable) declarations.

public static var a%(var i) (Return type)
Error 3: `var` cannot be used as a method return type.

public static var a%(var i) (Argument i type)
Error 4: `var` cannot be used as a method argument (parameter) type.

var j= {1,2,3};
Error 5: `var` cannot be used with an array initializer alone ({...}) because the compiler cannot explicitly infer the type (it must be new int[]{...}).

var m=null;
Error 6: `var` requires a non-null type to be inferred from the initialization expression. `null` alone does not determine the type, so it cannot be used.

3. Variable Name Naming Rule Errors (2 places)
var _k1$=new Short[] {3,4};
Error 7: Backslash () cannot be used in variable names (identifiers). Only _ and $ are allowed.

var 2k=new Byte[] {5};
Error 8: Variable names (identifiers) cannot start with a number.

Therefore, the total number of compilation errors is 8.
Oracle Certified Qualification Textbook Java Programmer Silver SE 17 (Exam Number 1Z0-825) (EXAMPRESS) [ Yuko Nemoto ]
Price: 4,620 JPY (Tax included, Free Shipping) (As of 2025/10/7) Purchase on Rakuten

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

public class Main {
	public static void main(String[] args) {
	String i[]= {" a "bn",new String("""
			 a "b
			"""), """
			       a "b"""};
	System.out.println(""+(i[0]==i[1])
			             +(i[0].equals(i[1]))
			             +(i[1]==i[2])
			             +(i[0]==i[1].intern()));
	}
}
Copy Code

A:falsefalsefalsefalse
B:truetruefalsetrue
C:falsefalsefalsetrue
D:truetruetruetrue
E:falsetruefalsetrue
F:Compilation error
G:Exception thrown at runtime

 

Check the answer

 

E:falsetruefalsetrue
First, verify what string instances the elements of array `i` hold.


i[0]: " a "bn"
This is a standard string literal. It is stored in the String Constant Pool at compile time. The value is " a "b" followed by a newline character (n).

i[1]: new String(""" a "b""")
This explicitly uses `new String()` to create a new instance in the heap area from the content of a Text Block ("""..."""). After processing the indentation of the Text Block, the value becomes " a "b" followed by a newline character (n), same as i[0].

i[2]: """a "b"""
This is also a Text Block but treated as a literal. After processing common indentation, the value becomes "a "b" without a newline character.

Comparisons
① i[0]==i[1]
i[0] refers to an instance in the String Pool.
i[1] refers to a new instance created in the heap by `new String()`.
Since the referenced addresses are different, the result is false.

② i[0].equals(i[1])
The string content held by i[0] and i[1] is identical.
equals() compares content, so the result is true.

③ i[1]==i[2]
The content of i[1] includes a newline n.
The content of i[2] does not include a newline.
Since the string values themselves are different, the referenced addresses are also different, so the result is false.

④ i[0]==i[1].intern()
i[1].intern() retrieves the instance corresponding to i[1]'s content from the String Pool.
i[0] also refers to the same instance in the String Pool with the same content.
Since both refer to the identical instance in the String Pool, the result is true.

Final Result
Concatenating the 4 boolean values as a string results in:
(false)+(true)+(false)+(true)→"falsetruefalsetrue"

17:Choose two of the following that do not cause a compilation error.

A:float f=3._2___2_f;
B:int i=0_5_2;
C:int j=0b_1111;
D:int k=0xf_5_abcdE;
E:int l=08_777;
F:int m=0b2___10;

 

Check the answer

 

B:int i=0_5_2; and D:int k=0xf_5_abcdE;
A: Error occurs
float f=3._2___2_f;
Reason: Underscores cannot be placed immediately before or after a decimal point (.). This code violates the rule at `3._`.

B: No error occurs
int i=0_5_2;
Explanation: Inserting underscores between digits in a decimal (treated as decimal here) or octal (starting with 0) number is permitted. This literal is interpreted as octal 052, which is decimal 42.

C: Error occurs
int j=0b_1111;
Reason: Underscores cannot be placed immediately after a prefix indicating the radix (such as 0b or 0x). This code violates the rule at `0b_`.

D: No error occurs
int k=0xf_5_abcdE;
Explanation: Inserting underscores between digits in a hexadecimal literal (starting with 0x) is permitted. Also, since there is no underscore immediately after the E, it does not violate the rule about placing underscores immediately before a type suffix (like L or F) (there is no type suffix here, so it is fine). This literal is interpreted as hexadecimal 0xF5ABCDE.

E: Error occurs
int l=08_777;
Reason: Integer literals starting with 0 are treated as octal, but octal literals cannot contain the digits 8 or 9. This code contains 8, so it causes a compilation error.

F: Error occurs
int m=0b2___10;
Reason: Binary literals (starting with 0b) can only contain the digits 0 and 1. This code contains 2, so it causes a compilation error.

Supplement: Positions where underscores are prohibited
When using underscores in Java numeric literals, the prohibited positions are:
At the beginning or end of the literal
Example: _100, 100_

Immediately before or after a decimal point (.)
Example: 3_.14, 3._14

Immediately after a radix prefix (0b, 0x, etc.)
Example: 0b_1101, 0x_FF

Immediately before a type suffix (L, f, F, etc.)
Example: 100_L, 3.14_f

18:Source file A.java exists in package a, and class B is inside this file. Choose the correct description regarding the commands related to these.

A:>java a/A.java 2
>java a.B
The main methods of class A and class B can be executed in order with the above commands.
B:>javac A.java
>java B
The main method of class B can be executed with the above commands.
C:>javac -d . a/A.java
>java -cp .. a.B
The main method of class B can be executed with this.
D:>java a/A.java java “a”
The main method of class A can be executed with this.
E:>javac a/A
>java a.A
The main method of class A can be executed with this.
F:All are incorrect

 

Check the answer

 

D:>java a/A.java java “a” 
The main method of class A can be executed with this.
D: Correct
In Java 11 and later, you can directly execute a single source file (.java) using the `java` command (JEP 330). In this case, compilation happens in memory.
`java a/A.java` executes the main method of the first top-level class, `class A`, within the A.java file.
`java "a"` are command line arguments passed to the main(String[] args) method. Two strings, "java" and "a", are passed as arguments. This is a valid execution format.

A: Incorrect
The first line `java a/A.java 2` executes class A.
The second line `java a.B` is the correct way to specify the class name (fully qualified class name), but in single-file source execution mode (line 1), the compiled class exists in-memory and is typically not found by subsequent `java` commands. This method is valid if a compiled .class file exists and the classpath is set correctly.

B: Incorrect
Since the source file is in package `a`, it is located at `a/A.java`. `javac A.java` might fail to find the file or compile it ignoring the package structure.
Also, to execute the packaged class (a.B), you must specify it with the fully qualified class name like `java a.B`, not `java B`.

C: Incorrect
The compile command `javac -d . a/A.java` correctly outputs `a/A.class` and `a/B.class` under the current directory in the `a/` directory structure.
However, the execution command `java -cp .. a.B` specifies the parent directory of the current directory as the classpath (`-cp ..`). The class files are inside `a/` directly under the current directory, so the classpath should normally be `-cp .` (current directory). Therefore, the class loader cannot find `a.B`.

E: Incorrect
The compile command `javac a/A` fails because the filename is missing the `.java` extension.
Also, the execution command `java a.A` would be executable if compilation succeeded and the classpath was set to the current directory, but since line 1 is incorrect, the whole is incorrect.

19:File Main.java contains sealed class Main permits A, C{} as well as class B, class C, interface E, and interface F. Which two of the following can be written in this file?

A:sealed class A permits C extends Main implements E, F{}
B:final class G extends Main implements F{}
C:class A extends Main {}
D:non-sealed class A extends Main implements E, F{}
E:public final class A extends Main{}
F:non-sealed class A extends E implements Main{}
G:non-sealed interface G  extends E, F{}
H:sealed interface A extends Main{}

 

Check the answer

 

D:non-sealed class A extends Main implements E, F{} and G:non-sealed interface G  extends E, F{}
File Main.java defines `sealed class Main permits A{}`, restricting direct inheritance of Main only to class A. The permitted class (A) in the permits clause must have one of the following modifiers: final, sealed, or non-sealed.


No Error Generated
D: non-sealed class A extends Main implements E, F{}
A is permitted in Main's permits clause.
The `non-sealed` modifier is required for a class inheriting from a sealed class, fitting the rules perfectly.
The syntax of extending Main and implementing E and F is also correct.

G: non-sealed interface G extends E, F{}
This is the definition of an independent top-level interface that has no inheritance relationship with sealed class Main.
`interface G extends E, F` is correct syntax for inheriting existing interfaces.
Strictly speaking, `non-sealed` is not required for normal interfaces, but it is not a grammatical error (permitted in Java 17+ specs).

Error Generated
A: sealed class A permits C extends Main implements E, F{}
The order should be extends clause, implements clause, then permits clause.

B: final class G extends Main implements F{}
G is not included in Main's permits clause. This violates the inheritance restriction of the sealed class.

C: class A extends Main{}
The permitted class A lacks the mandatory `final`, `sealed`, or `non-sealed` modifier.

E: public final class A extends Main{}
When multiple top-level classes (Main, A, B, C, etc.) are defined in Main.java, typically only the class matching the filename can have the public modifier.
Since the source filename is Main.java, only `class Main` has the right to be public among the top-level classes (even if sealed class Main is not public, the type matching the filename is the unique one allowed to be public).

F: non-sealed class A extends E implements Main{}
A `class` cannot `extends` an `interface` (E). Also, a `class` cannot `implements` a `class` (Main).

H: sealed interface A extends Main{}
An interface cannot `extends` a class (Main). Also, a `sealed interface` cannot omit the `permits` clause.

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

public class  Main extends A implements B{
	int i;
	public static void main(String[] args) {
	int j=new A().a(10);int k=new B().b(20);
	System.out.println(j+k+new Main().i);
	}
	int a(int i){
		this.i=2;
		return i*2;
	}
	public int b(int i) {
		this.i=3;
		return this.i*3;
	}
}

abstract class A{
	int i;
	abstract int a(int i);
	A(){System.out.print(1);	
	}
}
interface B {
	int i=1;
	int b(int i);
}
Copy Code

A:132
B:183
C:116
D:84
E:1
F:Compilation error
G:Exception thrown at runtime

 

Check the answer

 

F:Compilation error
You cannot create instances of abstract classes and interfaces, such as `new A()` or `new B()`.

コメント