Exam Flashcards

(188 cards)

1
Q

How many public classes in a .java file, and what are conditions on it and the file name.

A

1, and name must match with file name

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

When can compilation of Java code be omitted

A

When entire program is in one file

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

What is the output from compiling a java type definition?

A

Each type definition in a .java file is compiled to its own .class file whether public or not

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

What are the conditions for single file program

A
  • All definitions in one file,
  • First class much define main method
  • No compiled .class file for contents
  • Can’t access other compiled classes
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Statement, Expression which returns a value?

A

Expression

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

What are all the syntax’s for comments

A

// Text
/* Text */
“””Text”””

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

What is the order of primitive widening conversions? How does char fit into this?

A

byte, short, int, long, float, double

char can be widened to int but not byte, short

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

What is the range of byte type

A

-128, 127

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

How is long 2L printed

A

2

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

How is float 2F printed?

A

2.0

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

In operator precedence where does equality come?

A

After relative >=, but before bitwise and &. Mid table

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

What is XOR ^ truth table

A

T^T = F
T^F = T
F^T = T
F^F = F

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

Name all 9 cases where var type is not permitted

A

Instance variable
Static variable
Method Parameters
Without initialisation or initialised to null
Compound declaration
Array initialisation like this a = { 1, 2, 3 }
As array element type
No self reference in initialisation
Return type

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

Give example of compound assignment

A

String s, t = “def”
(FYI, s is not initialised)

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

List all the valid array initialisations

A

int[][] a = new int[10][10]
int[] a [] = new int[3][3]
int a[][] = new int[3][3]
int[] a = new int[]{1,2,3}
int[] a = {1,2,3}

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

What are the 6 +/- methods on AtomicInteger

A

.addAndGet
.getAndAdd
.decrementAndGet
.getAndDecrement
.incrementAndGet
.getAndIncrement

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

What are the characteristics of the Runnable interface and Callable interface

A

Runnable takes no inputs and doesn’t return anything and throws no Exceptions. Callable takes no inputs but can return a value and can throw Exception
Both can throw unchecked exceptions

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

Are private static methods allowed in Interfaces?

A

Yes

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

What are the integer primitives and is this valid

integerPrimitiveType t = 0;

A

byte, short, char, int and yes the assignment is valid as they are integer primitives.

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

What is the result of:
Path p1 = Paths.get(“c:\a\b\c”);
p1.getName(1);

A

b

Drive letter is not included in path.

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

What is getRoot(path) on both windows and linux file systems

A

Windows -> c:\ (drive letter)
Linux -> /

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

Is this valid

Integer i = 1;
double a = i

A

Yes

Unboxing followed by widening conversion is allowed

https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html

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

Does Object class implement Comparable?

A

No

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

Collections.sort(array, null)

Does this compile and if so how does it sort

A

Yes and natural sorting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What are the types in the below Object[] o = { 100, 100.0, "100" }
26
What is module-info.java compiled into
module-info.class
27
What is the result of and why? int[] ia1 = { 0, 1, 2, 6}; int[] ia2 = { 0, 1 }; System.out.println(Arrays.compare(ia1, ia2));
2 If one array is a prefix of the other than the result will not just be -1, 0, 1 It will take into account the difference in the number of elements Non null value is considered lexicographically larger than null value.
28
Record instance variables are implicitly what?
private and final
29
What runtime exception can be thrown with Console c = System.console();
It can throw NullPointerException if console is not support and null is return, the next access of c will throw.
30
Which is time based and which date based Period Duration
Duration - Time Period - Date
31
What are the interfaces for Car::getModel() car::getModel() where Car is the object type, car is an instance of Car
Function and Supplier respectively
32
Can boolean be used in switch statement/expression? What are the allowed types for switch?
No byte, short, char, int and their wrapper classes. Then enum and string
33
What is the StringBuilder method to set capacity?
.ensureCapacity(int)
34
What is the lambda for stream.mapToInt()
X->x
35
Choosing from modules and packages, which are required and which are exported?
Modules are required and packages exported
36
int a, b; a = b = 2; Is this valid?
Yes
37
What format is LocalDate printed in?
2023-12-30 ISO_DATE format
38
What are the rules for functional interfaces
One abstract method Default methods are allowed Static Methods are allowed Private Methods are allowed
39
With an SQL query that returns columns ID, NAME, AGE as ResultsSet. What are the ways of getting AGE value for row as an int?
rs.getInt(2) rs.getInt("AGE")
40
What is the condition for a variable to be used in a lambda
It needs to be effectively final
41
What type of variables are initialised to default values and which are not? What are their default values?
Static and instance variables are initialised to default values Boolean - False Char - ‘\u 0000’ Numerical Primitive - 0 or 0.0 Reference - Null Local variables are not initialised to default values
42
What can be put in to Public static void main() and won’t change behavior. What will change it?
Final Changing access type, removing static and return type.
43
Is this valid? abstract interface Interface {}
Yes, interfaces are implicitly abstract but there is no issue adding keyword explicitly
44
What does Paths.get("c:\\..\\temp\\test.txt").normalize().toUri() evaluate to?
file:///c:/temp/test.txt .. on root is just root
45
What do these String methods to: .isBlank() .isEmpty() .strip()
.isBlank() - True if empty or only comprised of whitespace .isEmpty() - True only if length is zero .strip() - Strip removes leading and trailing whitespace
46
What happens when .remove(index) is called on an empty list?
IndexOutOfBoundsException
47
What is the method determination for - Hidden methods - Overridden methods - Overloaded methods
- Hidden: Reference - Overridden: Actual object type at runtime - Overloaded: Actual object type at runtime
48
What is the method determination order for inputs?
Promotion, Cast, Boxing, Varargs
49
What does \s regex stand for?
A single whitespace
50
Can abstract classes have constructors?
Yes
51
What is the return type of Stream.count()
long
52
How is the Duration 12H 30M 12.45S printed? What are the units for durations always?
PT12H30M12.45S Hours, Minutes and Seconds with decimal
53
What exception is thrown when a file does not exist, give the fully qualified name.
java.nio.file.NoSuchFileException
54
When a sub class defined instance variable the same as super class is it overridden, overloaded or hidden? How is the instance variable determined?
Hidden by the type of reference variable not actual type of object.
55
Will this compile and why? switch(day){ case MONDAY: TUESDAY: WEDNESDAY: THURSDAY: FRIDAY: System.out.println("working"); case SATURDAY: SUNDAY: System.out.println("off"); }
Yes, the lines without case are just labels on the printing of "working"
56
What class and generic types does Properties class extend?
HashMap
57
What is wrong with this definition? Consumer x = (String msg)->{ System.out.println(msg); };
Consumer<> Is not typed and therefore implicitly typed to Object. This is not compatible with String msg and therefore won't compile.
58
Does Stream.findFirst() take any parameters, and if so what?
No
59
How do you describe a module with java cmd
java -p/--module-path moduleFolder -d/--describe-module moduleName
60
How do you describe a module with jar cmd
jar -f/--file jarFile.jar -d/--describe-module moduleName
61
How do you list the java system modules
java --list-modules
62
How do you list the java system modules and the modules in a particular directory
java -p . --list-modules
63
Is this a valid record definition? record Student(int id, String... subjects)
Yes
64
Are Records allowed static fields?
Yes
65
Can Records implement interfaces?
Yes
66
Can Records define other instance methods?
Yes
67
Which one of these can Records define? - Extra instance fields - Static fields - Static methods - Private method
No Yes Yes Yes
68
What does \ mean in regex terms
Negate carriage return
69
What is the result of 10.0/0.0
Double.POSITIVE_INFINITY
70
How do you load a service?
ServiceLoader.load(service.class)
71
What are the elements of ServiceLoader.stream() and how are they accessed
> Provider.get()
72
Is this valid? public int method() { throw Exception(); }
Yes not need to return value if throwing exception
73
Which cmd line tool is --jdk-internals valid for and what does it do?
jdeps - It finds class level deps on JDK internal APIs which are inaccessible.
74
How is determination of an instance field named the same in both parent and child class? How can the instance field in parent be accessed?
Based on reference type By casting the reference type to the type of parent class.
75
How is determination of static field named the same in both parent and child class?
Based on reference type
76
What is the natural ordering for Enum types?
The order in which they are defined
77
Can a record define a compact constructor and a canonical constructor?
No
78
When an exception is printed, what is the output
Name of Exception type and message
79
How do you get full stack trace from exception
Exception.printStackTrace()
80
How do you get the number of elements on a Set collection
Set.size()
81
What is special about ArrayDeque and what are its methods?
It can be used as a stack and a queue Queue methods - add, remove, offer, poll Stack methods - push, pop
82
A pattern matching variable can/cannot shadow which variable types
Can't shadow local, can shadow instance
83
Where can labels be used and where can they not be used
They can be used on any code block or block level statement e.g for. But not declarations
84
How do you access instance variable of outer class from within nested type?
OuterClass.this.variable
85
How do you access outer instance variable from static member type?
You can’t access outer instance variables from static context
86
How do you initialise instance of inner class
It needs to be associated with instance of our class new OuterClass().new InnerClass()
87
What are the top level types
Class, enum, record, interface
88
What are the three types of nested type?
Static Member Type Inner Classes Static Local Type
89
What are the types of Static Member Types?
Class, enum, interface, record
90
What are the types of inner class?
Non-static member type Anonymous Class Local Class
91
What are the types of static local types?
Interface, enum, record
92
What access types can static member types have?
Public, protected, package and private Apart from interface where members are implicitly static and public.
93
How is the type defined for an nested type (NestedType) inside an OuterType
OuterType.NestedType
94
How is a static member type initialised?
new OuterType.StaticMemberType() Directly on the outer type
95
What type of variables can static member types access in containing type?
Only static as they type is static
96
Can static member types define instance variables?
True
97
What nested types are implicitly static?
Enum, Record and Interface. Hence why we can only have inner classes
98
How do you access an instance variable of parent class from within child class which is hidden?
super.a
99
When an inner class extends another class that has a variable that matches variable from enclosing type which takes precedence when referenced by simple name
Inherited variable
100
What access modifiers can a local class have?
None, as it can’t be accessed from outside block. Only if it extends another class and is referenced super type
101
What access modifiers are allowed for members of a local class? And how can they be accessed in enclosing class?
They can have any and are accessible in enclosing context regardless of access set
102
What does the put methods of HashMap return?
If the value exists in the hash map already this value is returned after updating the value in map. If it doesn't then null is returned.
103
What is the input type for Stream.peek()
Consumer
104
What is the output of System.out.println(null) and String s = null; System.out.println(s)
Compilation error and null
105
What is the output of System.out.println(true) and System.out.println("" + true)
true and true
106
What is the database type for string
Types.VARCHAR
107
How do you set an sql parameter to null
statement.setNull(3, Types.VARCHAR)
108
What is the rule about ambiguous members when implementing multiple interfaces
Having multiple ambiguous members inherited is fine, referencing them in an ambiguous way will cause CTE.
109
What does ArrayList.subList() do?
It returns a view of the arraylist, backed by the original list, changing elements in one will reflect in the other.
110
What are the jmod commands
create extract describe list
111
And enums constructor is what?
Implicitly private
112
What does Arrays.mismatch() do?
Return the first index where two arrays differ
113
What is the abstract method for Comparable interface
compareTo(Object o)
114
What is the abstract method for Comparator interface
compare(Object o, Object 0)
115
What are the two formats of List.toArray()?
Object[] toArray() and T[] toArray(T[] t), elements from list will be put in array of type T, if elements fit they will go in that array otherwise new array will be created.
116
Give the module, package format of module-info.java
module module_name { requires module0 requires module4 requires transitive module3 exports package to module1, module2 opens package provides interface with class use type }
117
What are the rules for overriding/overloading generic methods
Erasure occurs on the method inputs, so if this is the same between methods that do not properly override each other then CTE. For overriding methods the return types have to be covariant with the same Generic Type.
118
What is the format string for full text time zone?
zzzz
119
Are instance variables in sub classes initialised before super constructor is called? What if the instance variable is marked final?
No it is not, but it is if marked final
120
If you have an overloaded method that has a variant that takes, Object, Number, Integer and Long, and you call it with primitive type double, which method is called?
The one with Number input as the double is first Boxed and then Number is the most specific input type.
121
If you have a list and call .subList(1,1), how many elements will be returned?
Zero
122
Is ClassNotFoundException a checked or unchecked exception
It is a checked exception
123
What is the output? char a = 'a', b = 98; int a1 = a; int b1 = (int) b; System.out.println((char)a1+(char)b1);
195
124
Is the below string interned? String s = "Hello"
Yes
125
Is there incidental whitespace in this text block? String s2 = """ Hello World""";
Yes
126
Which of these is a subtype of List List List List ArrayList ArrayList ArrayList
List ArrayList ArrayList
127
Is List a subtype of List
No
128
How do you create an empty Optional
Optional.ofNullable(null)
129
130
What does compareAndSet do on the AtomicInteger classs
compareAndSet(expected, newValue) compares current with expected and if they are the same then updates to newValue.
131
Is this valid? float f = 0x0123;
Yes
132
What does Collections.unmodifiableList() do?
It creates unmodifiable view of original collection but the change the underlying collection will change the view
133
What does isSameFile(p1, p2) do?
It checks to see if both paths are the same in the file system, following symlinks. If the paths are equal then it will return True without checking if the files exist.
134
How do you declare the type to use in generic method on a type C
C.method()
135
What is the access modifier for a constructor automatically inserted?
The same as the access of the class that it was inserted for.
136
What is the acronym for operator precedence?
AUpoUpreCMASRBCAA Access Unary Post Unary Pre Cast/Constructor Multi Additive Shift Relational Bitwise Conditional Arrow Assignment
137
What does Path.toAbsolutePath() do
Creates an absolute path, if already abs then returns that, otherwise creates absolute depending on implementation
138
What does Path.toRealPath() do?
Gets the real path to existing file in system, throws if doesn't exist. Converts to abs path first Does not follow Symlinks
139
What does Path.normalize() do?
It will condense the path to its most basic form removing redundant elements
140
What does Path.resolve(otherPath) do?
If otherPath is abs it returns that, otherwise it adds otherPath on to the end of current path
141
What does Path.resolveSibling(otherPath) do?
Calls resolve on parent
142
What does Path.relativize(otherPath) do?
It will determine the path from current path to otherPath. Both need to be relative or absolute
143
How does Path.equals(otherPath) compare paths?
It only compares the strings and it doesn't normalise them first.
144
What are the 4 way to create Path objects?
Path.of(String p, String ...) Path.of(URI) FileSystem.getPath(String p, String ...) Paths.get(String p, String ...)
145
How do you convert a Path to legacy File type?
Path.toFile()
146
Does Files.exists(Path) follow symlinks?
Yes
147
What is the Symlink constant?
LinkOptions.NOFOLLOW_LINKS
148
What does Files.isSameFile(Path, Path)
It compares the path strings only, normalising and following symlinks
149
How does Files.delete(Path) and Files.deleteIfExists(Path)
delete will throw if the file does not exist and has void return type, while deleteIfExists will return boolean.
150
How does Files.delete(Path) and Files.deleteIfExists(Path) behave with directories?
Deletes them if they are empty
151
How does Files.delete(Path) and Files.deleteIfExists(Path) behave with symlinks?
Delete the symlink not the target
152
What the are the Files.copy signatures?
copy(InputStream, Path) copy(Path, OutputStream) copy(Path, Path)
153
How does Files.copy behave if the destination Path exists already
It throws a FileAlreadyExistsException and if REPLACE_EXISTING has not been specified
154
How does Files.move(Path, Path) behave
It throws a FileAlreadyExistsException and if REPLACE_EXISTING has not been specified If target is symlink that it is moved and not the target
155
How does Files.createDirectory(Path) behave?
It will throw exception if the destination already exists, it will only create the target and throw exception if parent of path does not exist
156
How does Files.createDirectories(Path) behave?
It will create all non-existent parent directories of path first, and won't throw an exception if one exists.
157
What are the signatures of the Files.find() and .walk() methods? What is the return type of these methods?
find(Path, depth, Bifunction, FileVisitOptions ) walk(Path, FileVisitOptions) walk(Path, depth, FileVisitOptions)
158
What is the return type of the Files.find() and .walk() methods?
Stream
159
Do Files.find() and .walk() methods follow links by default?
No
160
What does Files.mismatch(Path, Path) do?
It will find the position of the first mismatching byte between two files.It will find the position of the first mismatching byte between two files.
161
What is the behaviour of tryLock()
It will try to acquire the lock or move on, or try for the specified amount of time tryLock(long, TimeUnit)
162
What is the return type of Executors.newScheduledThreadPool(int)
ScheduledExecutorService
163
What are the behaviours of ScheduledExecutorService.scheduleWithFixedDelay() and ScheduledExecutorService.scheduleWithFixedRate()
Fixed delay will run the lambda again after given period, fixed rate will run the lambda again after the given period after it has completed. The only exist for Runnables
164
What the ExecutorService.execute() and ExecutorService.submit() return types
execute() returns void, while submit() returns Future
165
Is return null equivalent to return; for a void method
No? This would not work for Runnable lambda for instance
166
What ordering will .forEachOrdered(Consumer) process in?
In the stored order of the original stream.
167
How does Stream.findFirst() behave?
It will find the first stored element in stream even if it is parallel
168
How does Stream.findAny() behave?
It will return first element read by thread, regardless of sorting or ordering
169
What are the Streams.reduce signatures?
reduce(BinaryOperator) reduce(T Identity, BinaryOperator) reduce(U Identity, BiFunction, BinaryOperator)
170
What states are relevant for calling .interrupt() on a thread?
WAITING and TIMED_WAITING
171
What does volatile keyword ensure?
Memory consistency but not threadsafety
172
What variables can be used in lambda and what are the conditions?
They can use static, instance and local variables, but local variables must be final or effectively final.
173
How does ScheduledExecutorService work with Callables
schedule(Callable, delay, TimeUnit)
174
What are the ExectorService methods for Callables?
submit(Callable) invokeAll(Collection>) invokeAny(Collection>) with timeouts.
175
Math class methods .sum .average .pow
176
Can an input stream's .mark() functionality be re-used? E.g. .reset() called multiple times?
Yes
177
Can a Record class extend another class? Can it implement an interface?
No it can't extend but it can implement and interface
178
Does String.split() include trailing empty strings?
No
179
How do you initialise DateTimeFormatter?
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy"); DateTimeFormatter df = DateTimeFormatter.ISO_DATE; DateTimeFormatter df = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
180
How do you get the default locale?
Locale.getDefault()
181
What needs to be remembered with resources created in try-with-resource blocks?
They are implicitly final and can't be re-assigned.
182
What does the ArrayList.add() return?
It returns a boolean if the list is altered
183
What are the return types for Float.parseFloat() Float.floatValue() Float.valueOf()
Float.parseFloat(String) - float Float.floatValue() - float Float.valueOf(String) - Float Float.valueOf(float) - Float
184
What exception does the wrapper parse* methods throw?
NumberFormatException (Unchecked Exception)
185
Can you override/hide a static method with instance method and vice versa?
No
186
What is the input of Stream.averageInt
ToIntFuntion
187
How do you add a new row with ResultSet
.insertRow()
188