May 2025 Flashcards

(128 cards)

1
Q

Is public ListInteger> getList() a valid override of public List? extends Number> getList()?

A

Yes —

List<Integer> matches List<? extends Number>
because Integer extends Number.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Is public ListObject> getList() a valid override of public List? extends Number> =-?9 |

A

No — Object is not a subtype of Number, so

List<Object>
does not match
List<? extends Number>
.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can public ArrayListDouble> getList() override public List? extends Number> getList()?

A

Yes — Double extends Number, and ArrayList<Double> is a subtype of List<? extends Number>.</Double>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is public ListObject> getList() a valid override of public List? super Integer> getList()?

A

Yes — because List<object> is a valid instantiation of List<? super Integer>.</object>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can public ListNumber> getList() override public List? super Integer> getList()?

A

Yes — Number is a supertype of Integer, so List<Number> matches List<? super Integer>.</Number>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is public ListDouble> getList() a valid override of public List? super Integer> getList()?

A

No — Double is not a supertype of Integer; it’s a sibling in the type hierarchy, so List<Double> does not match List<? super Integer>.</Double>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can a char be assigned a byte or short without a cast?

A

No. Even though byte (8-bit) and short (16-bit signed) are smaller than char (16-bit unsigned), a cast is required because Java doesn’t allow implicit conversion from signed to unsigned types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can a char be assigned an int value directly without a cast?

A

No. int (32-bit) is wider than char (16-bit), so an explicit cast is required to assign an int to a char.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Can a char be assigned a character literal like ‘A’ or a numeric constant within the char range (e.g. 65)?

A

Yes. If the value is a compile-time constant within the range 0 to 65535, it can be assigned to a char without a cast.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which of the following lambda expressions correctly implements Runnable?

A) () -> System.out.println("Running")
B) () -> "Done"
A

A: A. Runnable has a void run() method, so the lambda must not return a value. B returns “Done” and is invalid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which functional interface is most appropriate for a method like int operate(int a, int b)?

A) BiFunctionInteger, Integer, Integer>
B) BinaryOperatorInteger>

A

A: B. While both work, BinaryOperator<T> is more specific for operations with two same-type inputs and one same-type output.</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can the following interface be used as a functional interface with a lambda?

interface MyFunc {
default void help() {}
int compute(int x);
}

A

A: Yes. It has only one abstract method (compute), so it’s a valid functional interface despite having a default method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the diamond problem in the context of Java inheritance?

A

It occurs when a class inherits from two classes that both inherit from a common superclass, potentially leading to ambiguity in method resolution. Java avoids this by not allowing multiple inheritance of classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does Java prevent the diamond problem with classes?

A

Java does not allow a class to inherit from more than one class. It only allows multiple inheritance through interfaces, which do not carry implementation by default.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Can the diamond problem occur with interfaces in Java 8+?

A

Yes, if two interfaces provide the same default method, the implementing class must override it to resolve ambiguity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between multiple inheritance of type and multiple implementation inheritance in Java?

A

Multiple inheritance of type means a class can implement multiple interfaces (method signatures only). Multiple implementation inheritance (inheriting code from multiple classes) is not allowed in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What type of function does Stream.flatMap() require as an argument?

A

A function that maps each element to a Stream, i.e., Function<? super T, ? extends Stream<? extends R».

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the main purpose of the flatMap() method in Java Streams?

A

To apply a one-to-many transformation and flatten the resulting nested streams into a single stream.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What happens if you pass an undefined variable like bs to flatMap()?

A

It causes a compilation error, because flatMap() expects a valid mapping function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the mark(int readAheadLimit) method do in BufferedReader, and what are its constraints?

A

The mark(int readAheadLimit) method records the current position in the stream. A subsequent call to reset() will attempt to reposition the stream to this point.
* readAheadLimit defines how many characters can be read before the mark becomes invalid.
* If readAheadLimit < 0, it throws IllegalArgumentException.
* A large limit may cause the buffer to grow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is variable shadowing in Java?

A

Variable shadowing occurs when a local variable or parameter has the same name as an instance variable, making the instance variable inaccessible without using this.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you access an instance variable that’s being shadowed by a parameter in a method or constructor?

A

Use this.variableName to refer explicitly to the instance variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Can a Java record extend another class? Why or why not?

A

No, a Java record cannot extend another class because it implicitly extends java.lang.Record and Java does not support multiple class inheritance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Can a Java record implement interfaces?

A

Yes, a record can implement interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What kind of exceptions can an overriding method declare in Java?
It can declare the same or narrower (more specific) checked exceptions as the method it overrides.
26
What happens if an overriding method declares a broader checked exception than the original method?
The code will not compile because Java does not allow overriding methods to introduce broader checked exceptions.
27
Can an overriding method in Java declare unchecked exceptions if the original method does not?
Yes. Unchecked exceptions (subclasses of RuntimeException) can be declared or thrown regardless of the superclass method’s exception list.
28
What is DateTimeFormatter used for in Java?
It is used to format and parse date-time objects like LocalDate, LocalTime, and LocalDateTime.
29
How do you create a formatter that outputs a date in a localized short style?
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
30
What happens if you try to format a LocalDate with a formatter created using ofLocalizedDateTime()?
A UnsupportedTemporalTypeException is thrown because LocalDate does not contain time information required by the formatter.
31
What is the purpose of the uses directive in a Java module declaration?
It declares a dependency on a service interface, signaling that the module will use implementations of that service via ServiceLoader.
32
What must a module also include if it provides an implementation for a service interface declared with uses?
A provides ServiceInterface> with ImplementationClass>; directive in another module.
33
True or False: The uses directive is used to import classes or packages from another module.
False. It is only used for declaring service usage for dynamic discovery via ServiceLoader, not for general package access.
34
What is the rule in Java regarding the order of catch blocks when catching exceptions from the same inheritance hierarchy?
More specific exceptions (subclasses) must be caught before more general ones (superclasses), otherwise the compiler will throw an “exception is already caught” error.
35
How can you fix a catch block that violates exception hierarchy rules in Java?
Either reverse the order to catch subclasses first, or merge into a single catch for the superclass if handling is the same.
36
Can automatic modules read other modules?
Yes. Automatic modules can read all other modules, including named and unnamed modules.
37
How is a module name inferred from a JAR file when it’s used as an automatic module?
The module name is derived from the JAR filename by replacing hyphens with dots, and removing the version number if present (e.g., my-lib-1.2.jar → my.lib).
38
Are all characters valid in inferred automatic module names?
No. Some characters, like hyphens, are not valid. They’re replaced with dots during name inference, and the result must still be a legal Java identifier.
39
In Java’s module system, what does the exports directive refer to in module-info.java?
It refers to packages, not individual classes.
40
Why is exports com.example.MyClass; invalid in a module-info.java file?
Because exports only works with package names, not specific class names.
41
How do you make a public class available to other modules in Java’s module system?
Place the class in a package and export that package using exports package.name;.
42
What is the purpose of the requires directive in module-info.java?
It declares a dependency on another module so that its exported packages can be used.
43
Does the requires directive import specific packages?
No. It imports all exported packages from the required module, not individual packages.
44
What happens if a module does not declare a needed requires directive?
Compilation will fail with a “package is not visible” or “module not found” error.
45
What rule must an overriding method follow regarding checked exceptions in Java?
It must not declare new or broader checked exceptions than the method in the interface or superclass.
46
Can a class method that implements an interface method omit all checked exceptions declared in the interface?
Yes. It can declare fewer or no checked exceptions, as long as it doesn’t widen the exception scope.
47
If two interfaces declare a method with the same signature but different checked exceptions, how can a class implement both?
By implementing the method without declaring any checked exceptions.
48
What modifiers are implicitly applied to fields declared in an interface?
public static final — all interface fields are constants by default.
49
Can you declare a protected or private field in a Java interface?
No, all fields in an interface must be public.
50
Are fields in interfaces mutable?
No, they are constants (final) and must be assigned a value when declared.
51
Your are modularizing your java application but it depends on commons-dbcp-0.9.jar, which is not modularized. So, you have decided to put this jar on the module-path. What module name will be given to the automatic module created for this jar?
commons.dbcp
52
What is the purpose of the Automatic-Module-Name entry in a JAR’s MANIFEST.MF?
It explicitly defines the module name for an automatic module, avoiding Java’s default derivation from the JAR filename.
53
Where should the Automatic-Module-Name entry be added to stabilize a module’s name?
In the META-INF/MANIFEST.MF file or a custom manifest.txt used when creating the JAR.
54
What happens if a JAR on the module path lacks both module-info.class and Automatic-Module-Name?
Java derives the module name from the JAR filename by removing .jar and replacing hyphens with dots, which may result in unstable or invalid module names.
55
What are the four types of inner classes in Java?
A: 1. Non-static (regular) inner class 2. Static nested class 3. Local inner class (defined inside a method) 4. Anonymous inner class
56
Can a non-static inner class access the members of its outer class?
Yes, a non-static inner class has access to all members (including private) of its outer class instance.
57
What is required to instantiate a non-static inner class from outside its outer class?
You must first instantiate the outer class: Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();
58
What happens to constructors and initialization blocks during deserialization of a Serializable class?
Constructors and static/instance blocks of the class are not executed during deserialization.
59
If a superclass does not implement Serializable, what happens during deserialization?
Its constructor is invoked to initialize the non-serializable part of the object.
60
In a class hierarchy where BooBoo → Boo → Zing, and only Zing implements Serializable, which constructors are called during deserialization?
The constructors of BooBoo and Boo are called, but not Zing’s.
61
What does the add(E e) method return in a Collection?
It returns true if the collection changed as a result of the call, or false if it did not (e.g., the element was already present in a non-duplicate-allowing collection).
62
What is the purpose of the finally block in Java exception handling?
The finally block is used to define code that will always execute after the try and optional catch blocks, regardless of whether an exception was thrown or caught.
63
Can a finally block execute even if there is a return statement in the try or catch block?
Yes, the finally block executes even if the try or catch block contains a return statement.
64
Is the finally block optional in Java, and can it exist without a catch block?
Yes, the finally block is optional, and it can follow a try block even without a catch block.
65
What elements make up a method signature in Java?
The method name and the parameter types (in order). The return type is not part of the signature.
66
Why can’t you define two methods with the same signature but different return types in a Java class?
Because the compiler and JVM use only the method name and parameter types to identify methods. The return type is ignored, so such methods would cause ambiguity.
67
Is the following code valid in Java? void doSomething(int x) {} int doSomething(int x) { return x; }
No, it will not compile. Both methods have the same signature doSomething(int) despite having different return types.
68
What does JDBC stand for?
JDBC stands for Java Database Connectivity. It is an API in Java that allows applications to connect to and interact with relational databases like MySQL using SQL.
69
What is string interning in Java?
It’s a process where identical string literals are stored in a common pool to save memory. All references to the same literal point to the same object.
70
What happens when you create a string using new String("value")?
A new string object is created on the heap, even if an identical string already exists in the string pool.
71
What does the == operator compare when used with objects in Java?
It compares object references, not their contents. Two different objects with the same value will return false when compared with ==.
72
What is the correct syntax for declaring a generic method?
public T> void doSomething(T item)
73
Can a static method be generic in Java?
Yes, you can declare a static method like this: public static T> T doSomething()
74
Why is T> static T doSomething() invalid in Java?
A: Because the type parameter must appear before the return type and after any modifiers (like public or static). Correct form: public static T> T doSomething()
75
Can a static method in a class override a method in an interface?
No. Static methods do not override interface methods and do not fulfill interface contracts.
76
Why can’t static methods be used to implement interface methods?
Because static methods are bound to the class, not instances, and do not participate in polymorphism.
77
What happens if a class implements an interface but only provides a static method with the same name as the interface method?
The class won’t compile — the static method doesn’t count as an override, and the interface contract remains unfulfilled.
78
What types of modules can be placed on the module-path?
Only named modules and automatic modules can be placed on the module-path.
79
Can classes from named modules access classes on the classpath (unnamed module)?
No, classes from named modules cannot access classes/packages from the unnamed module (i.e. classpath).
80
What is special about automatic modules regarding access to unnamed modules?
Automatic modules (which are also named modules) can access all classes/packages in the unnamed module.
81
Where must the module-info.java file be placed in a modular project?
At the root of the module’s source directory, e.g., src/my.module/module-info.java
82
Is module-info.java optional in modular applications?
No, it’s required for named modules. It is only optional for unnamed modules (those on the classpath).
83
What is an unnamed module?
A module that doesn’t have a module-info.java and runs on the classpath instead of the module-path.
84
What happens if you pass a null element to List.of(...) in Java?
A NullPointerException is thrown because List.of does not allow null elements.
85
True or False: List.copyOf() creates a new unmodifiable list that allows null values from the source collection.
False. List.copyOf() throws a NullPointerException if any element in the source collection is null.
86
Why do List.of() and List.copyOf() throw NullPointerException when encountering null?
Because they create immutable collections that explicitly forbid null to ensure safety and clarity in usage.
87
In the expression int j = i++;, what are the values of i and j afterward?
i becomes 2, and j is assigned 1. The i++ is a post-increment, so the original value is assigned before i is incremented.
88
What does the single | operator do in Java when used in an if condition?
It is a bitwise OR operator that does not short-circuit. Both conditions are always evaluated, unlike || which short-circuits.
89
What is the final value printed by this code? int i = 1; int j = i++; if ((i == ++j) | (i++ == j)) { i += j; } System.out.println(i);
The output is 5. Final values: i = 5, j = 2. Both sides of the condition evaluate to true (2 == 2), triggering i += j with i = 3 before the addition.
90
What must be present for a module using uses org.example.Service to compile?
The interface org.example.Service must be accessible (i.e., exported by the module that defines it and required by the using module). No implementation or provides directive is required at compile time.
91
Is it necessary for a service provider to be on the module path for compilation when a module uses ServiceLoader.load(SomeService.class)?
No. A provider is only required at runtime. Compilation only requires that the service interface is visible to the using module.
92
What does the uses directive in module-info.java actually do?
It declares that the module depends on a service interface, allowing it to use ServiceLoader to discover implementations at runtime. It does not imply any compile-time requirement for a provider.
93
What is the main advantage of ConcurrentHashMap over HashMap in a multithreaded context?
ConcurrentHashMap allows safe concurrent read and write operations without needing external synchronization, making it more scalable than synchronizing a HashMap.
94
Can the iterators of ConcurrentHashMap reflect changes made by other threads during iteration?
Yes. Iterators of ConcurrentHashMap are weakly consistent, meaning they may reflect some, all, or none of the changes made after the iterator was created, but they will not throw ConcurrentModificationException.
95
Is it safe to use Iterator.remove() on a ConcurrentHashMap iterator?
No. ConcurrentHashMap’s iterators do not support remove() and will throw UnsupportedOperationException. Use keySet().removeIf(...) instead for safe conditional removal.
96
When is the abstract keyword required for a method in a class?
When the method has no implementation (i.e., no method body) and should be implemented by subclasses.
97
Does a class need to be abstract if it only contains implemented methods?
No. If all methods are implemented, the class can be concrete and does not need the abstract keyword.
98
Can a subclass override a concrete method from its superclass without the superclass being abstract?
Yes. A subclass can override any non-final method from a superclass, whether the superclass is abstract or not.
99
What does shutdownNow() do in ExecutorService?
It attempts to stop all actively executing tasks by calling Thread.interrupt() on them and returns a list of tasks that were awaiting execution.
100
Why does a task using Thread.sleep() get interrupted when shutdownNow() is called?
Because Thread.sleep() is an interruptible operation, so if the thread is interrupted while sleeping, it throws InterruptedException.
101
What happens to a Callable task submitted to an ExecutorService if it’s interrupted during Thread.sleep()?
It throws an InterruptedException before completing, and the result (e.g., “done”) is never returned.
102
How do you create a parallel stream from a Collection in Java?
Use collection.parallelStream(), e.g., c.parallelStream().
103
Given a sequential stream Stream s = c.stream();, how can you convert it to a parallel stream?
Call s.parallel() to get a parallel version of the stream.
104
Which of the following correctly creates a parallel stream? c.parallelStream() c.stream().parallel()
both create parallel streams.
105
What must be true about a local variable for it to be accessed in a lambda expression?
It must be final or effectively final.
106
What does “effectively final” mean in Java?
A variable is effectively final if it is not modified after its initial assignment.
107
Why must local variables be final or effectively final in lambdas or inner classes?
Because the lambda or inner class may outlive the method call, and Java captures the variable’s value, not its reference.
108
Can a static method be overridden in a subclass?
No. Static methods are not part of an object’s instance and are bound at compile time. If a subclass defines a static method with the same signature, it hides the superclass method, but does not override it.
109
What happens when a static method is called using an object reference?
The static method is still resolved at compile time using the reference type, not the object’s runtime type. This can be misleading but is not polymorphism.
110
Can you access a static method of a superclass from a subclass without using inheritance?
Yes. Since static methods belong to the class and not the object, they can be accessed using the superclass name: SuperclassName.staticMethod().
111
What does TreeSet.subSet(from, fromInclusive, to, toInclusive) return?
It returns a view of the portion of the TreeSet ranging between the specified from and to values, with control over whether the bounds are inclusive or exclusive.
112
Can you modify a TreeSet subset returned by subSet()?
Yes, but only with elements within the defined range. Adding an element outside the range throws IllegalArgumentException.
113
Do changes to a subSet view affect the original TreeSet?
Yes. The subSet is a view backed by the original TreeSet, so modifications are reflected both ways.
114
What is downcasting in Java?
Downcasting is casting an object from a superclass reference to a subclass type, e.g., (Dog) animal, where animal is declared as type Animal.
115
When is downcasting safe in Java?
Downcasting is safe only when the object is actually an instance of the subclass. Otherwise, it throws a ClassCastException at runtime.
116
How can you safely perform a downcast?
Use instanceof to check the type before downcasting: if (animal instanceof Dog) { Dog dog = (Dog) animal; }
117
What kind of list does Arrays.asList() return in Java?
It returns a fixed-size list backed by the original array, meaning you cannot add or remove elements.
118
What exception is thrown when you try to remove an element from a list created with Arrays.asList()?
UnsupportedOperationException is thrown because the list does not support structural modification.
119
Can you update elements in a list created with Arrays.asList()?
Yes, you can use set(index, value), but you cannot add or remove elements.
120
What does the add(E e) method do in a Deque, and how does it behave on failure?
add(E e) inserts the element at the tail of the deque. It returns true if the insertion is successful. If the deque is full (in bounded implementations), it throws an exception.
121
What does the pop() method do in a Deque?
pop() removes and returns the head of the deque (like removeFirst()). It throws a NoSuchElementException if the deque is empty.
122
What is the behavior of the offerFirst(E e) method in a Deque?
offerFirst(E e) attempts to insert the element at the head of the deque. It returns true if successful, or false if the deque is full (in bounded implementations). It does not throw an exception on failure.
123
What is the basic syntax of a lambda expression in Java?
(parameters) -> expression or (parameters) -> { statements } Example: (a, b) -> a + b
124
When can you omit parentheses in a lambda expression?
When there’s only one parameter and its type is inferred, parentheses can be omitted. Example: s -> s.length()
125
Can a lambda expression have a block body with multiple statements?
Yes, use curly braces {} and a return statement if returning a value. (a, b) -> { int sum = a + b; return sum; }
126
What determines the number of bytes written when using PrintWriter.write(int)?
It writes a single character. The size in bytes depends on the platform’s default character encoding (e.g., 1 byte for UTF-8).
127
What happens when os.write(99) is executed in a FileOutputStream?
It writes the lowest 8 bits of the integer (i.e., one byte) to the file, so the file will be 1 byte in size.
128
What is the file size result of: var bos = new BufferedOutputStream(os); var pw = new PrintWriter(bos); pw.print(99);?
The print(99) call writes the string “99”, which results in 2 bytes if the default encoding is UTF-8.