Exam Flashcards
How many public classes in a .java file, and what are conditions on it and the file name.
1, and name must match with file name
When can compilation of Java code be omitted
When entire program is in one file
What is the output from compiling a java type definition?
Each type definition in a .java file is compiled to its own .class file whether public or not
What are the conditions for single file program
- All definitions in one file,
- First class much define main method
- No compiled .class file for contents
- Can’t access other compiled classes
Statement, Expression which returns a value?
Expression
What are all the syntax’s for comments
// Text
/* Text */
“””Text”””
What is the order of primitive widening conversions? How does char fit into this?
byte, short, int, long, float, double
char can be widened to int but not byte, short
What is the range of byte type
-128, 127
How is long 2L printed
2
How is float 2F printed?
2.0
In operator precedence where does equality come?
After relative >=, but before bitwise and &. Mid table
What is XOR ^ truth table
T^T = F
T^F = T
F^T = T
F^F = F
Name all 9 cases where var type is not permitted
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
Give example of compound assignment
String s, t = “def”
(FYI, s is not initialised)
List all the valid array initialisations
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}
What are the 6 +/- methods on AtomicInteger
.addAndGet
.getAndAdd
.decrementAndGet
.getAndDecrement
.incrementAndGet
.getAndIncrement
What are the characteristics of the Runnable interface and Callable interface
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
Are private static methods allowed in Interfaces?
Yes
What are the integer primitives and is this valid
integerPrimitiveType t = 0;
byte, short, char, int and yes the assignment is valid as they are integer primitives.
What is the result of:
Path p1 = Paths.get(“c:\a\b\c”);
p1.getName(1);
b
Drive letter is not included in path.
What is getRoot(path) on both windows and linux file systems
Windows -> c:\ (drive letter)
Linux -> /
Is this valid
Integer i = 1;
double a = i
Yes
Unboxing followed by widening conversion is allowed
https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html
Does Object class implement Comparable?
No
Collections.sort(array, null)
Does this compile and if so how does it sort
Yes and natural sorting
What are the types in the below
Object[] o = { 100, 100.0, “100” }
What is module-info.java compiled into
module-info.class
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.
Record instance variables are implicitly what?
private and final
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.
Which is time based and which date based
Period
Duration
Duration - Time
Period - Date
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
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
What is the StringBuilder method to set capacity?
.ensureCapacity(int)
What is the lambda for stream.mapToInt()
X->x
Choosing from modules and packages, which are required and which are exported?
Modules are required and packages exported
int a, b;
a = b = 2;
Is this valid?
Yes
What format is LocalDate printed in?
2023-12-30
ISO_DATE format
What are the rules for functional interfaces
One abstract method
Default methods are allowed
Static Methods are allowed
Private Methods are allowed
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”)
What is the condition for a variable to be used in a lambda
It needs to be effectively final
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
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.
Is this valid?
abstract interface Interface {}
Yes, interfaces are implicitly abstract but there is no issue adding keyword explicitly
What does Paths.get(“c:\..\temp\test.txt”).normalize().toUri() evaluate to?
file:///c:/temp/test.txt
.. on root is just root
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
What happens when .remove(index) is called on an empty list?
IndexOutOfBoundsException
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
What is the method determination order for inputs?
Promotion, Cast, Boxing, Varargs
What does \s regex stand for?
A single whitespace
Can abstract classes have constructors?
Yes
What is the return type of Stream.count()
long
How is the Duration 12H 30M 12.45S printed?
What are the units for durations always?
PT12H30M12.45S
Hours, Minutes and Seconds with decimal
What exception is thrown when a file does not exist, give the fully qualified name.
java.nio.file.NoSuchFileException
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.
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”
What class and generic types does Properties class extend?
HashMap<Object, Object>
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.
Does Stream.findFirst() take any parameters, and if so what?
No
How do you describe a module with java cmd
java -p/–module-path moduleFolder -d/–describe-module moduleName
How do you describe a module with jar cmd
jar -f/–file jarFile.jar -d/–describe-module moduleName
How do you list the java system modules
java –list-modules
How do you list the java system modules and the modules in a particular directory
java -p . –list-modules
Is this a valid record definition?
record Student(int id, String… subjects)
Yes
Are Records allowed static fields?
Yes
Can Records implement interfaces?
Yes
Can Records define other instance methods?
Yes
Which one of these can Records define?
- Extra instance fields
- Static fields
- Static methods
- Private method
No
Yes
Yes
Yes
What does \ mean in regex terms
Negate carriage return
What is the result of 10.0/0.0
Double.POSITIVE_INFINITY
How do you load a service?
ServiceLoader.load(service.class)
What are the elements of ServiceLoader.stream() and how are they accessed
<ServiceLoader.Provider<S>></S>
Provider.get()
Is this valid?
public int method() {
throw Exception();
}
Yes not need to return value if throwing exception
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.
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.
How is determination of static field named the same in both parent and child class?
Based on reference type
What is the natural ordering for Enum types?
The order in which they are defined
Can a record define a compact constructor and a canonical constructor?
No
When an exception is printed, what is the output
Name of Exception type and message
How do you get full stack trace from exception
Exception.printStackTrace()
How do you get the number of elements on a Set collection
Set.size()
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
A pattern matching variable can/cannot shadow which variable types
Can’t shadow local, can shadow instance
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
How do you access instance variable of outer class from within nested type?
OuterClass.this.variable
How do you access outer instance variable from static member type?
You can’t access outer instance variables from static context
How do you initialise instance of inner class
It needs to be associated with instance of our class
new OuterClass().new InnerClass()
What are the top level types
Class, enum, record, interface
What are the three types of nested type?
Static Member Type
Inner Classes
Static Local Type
What are the types of Static Member Types?
Class, enum, interface, record
What are the types of inner class?
Non-static member type
Anonymous Class
Local Class
What are the types of static local types?
Interface, enum, record
What access types can static member types have?
Public, protected, package and private
Apart from interface where members are implicitly static and public.
How is the type defined for an nested type (NestedType) inside an OuterType
OuterType.NestedType
How is a static member type initialised?
new OuterType.StaticMemberType()
Directly on the outer type
What type of variables can static member types access in containing type?
Only static as they type is static
Can static member types define instance variables?
True
What nested types are implicitly static?
Enum, Record and Interface. Hence why we can only have inner classes
How do you access an instance variable of parent class from within child class which is hidden?
super.a
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
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
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
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.
What is the input type for Stream.peek()
Consumer
What is the output of
System.out.println(null)
and
String s = null;
System.out.println(s)
Compilation error
and
null
What is the output of
System.out.println(true)
and
System.out.println(“” + true)
true
and
true
What is the database type for string
Types.VARCHAR
How do you set an sql parameter to null
statement.setNull(3, Types.VARCHAR)
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.
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.
What are the jmod commands
create
extract
describe
list
And enums constructor is what?
Implicitly private
What does Arrays.mismatch() do?
Return the first index where two arrays differ
What is the abstract method for Comparable interface
compareTo(Object o)
What is the abstract method for Comparator interface
compare(Object o, Object 0)
What are the two formats of List.toArray()?
Object[] toArray()
and
<T> 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.
</T>
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
}
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.
What is the format string for full text time zone?
zzzz
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
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.
If you have a list and call .subList(1,1), how many elements will be returned?
Zero
Is ClassNotFoundException a checked or unchecked exception
It is a checked exception
What is the output?
char a = ‘a’, b = 98;
int a1 = a;
int b1 = (int) b;
System.out.println((char)a1+(char)b1);
195
Is the below string interned?
String s = “Hello”
Yes
Is there incidental whitespace in this text block?
String s2 = “””
Hello World”””;
Yes
Which of these is a subtype of List<? super Integer>
List<? extends Integer>
List<? super Number>
List<? extends Number>
ArrayList<? extends Integer>
ArrayList<Number>
ArrayList<Integer></Integer></Number>
List<? super Number>
ArrayList<Number>
ArrayList<Integer></Integer></Number>
Is List<Integer> a subtype of List<Number></Number></Integer>
No
How do you create an empty Optional
Optional.ofNullable(null)
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.
Is this valid?
float f = 0x0123;
Yes
What does Collections.unmodifiableList() do?
It creates unmodifiable view of original collection but the change the underlying collection will change the view
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.
How do you declare the type to use in generic method on a type C
C.<Type>method()</Type>
What is the access modifier for a constructor automatically inserted?
The same as the access of the class that it was inserted for.
What is the acronym for operator precedence?
AUpoUpreCMASRBCAA
Access
Unary Post
Unary Pre
Cast/Constructor
Multi
Additive
Shift
Relational
Bitwise
Conditional
Arrow
Assignment
What does Path.toAbsolutePath() do
Creates an absolute path, if already abs then returns that, otherwise creates absolute depending on implementation
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
What does Path.normalize() do?
It will condense the path to its most basic form removing redundant elements
What does Path.resolve(otherPath) do?
If otherPath is abs it returns that, otherwise it adds otherPath on to the end of current path
What does Path.resolveSibling(otherPath) do?
Calls resolve on parent
What does Path.relativize(otherPath) do?
It will determine the path from current path to otherPath. Both need to be relative or absolute
How does Path.equals(otherPath) compare paths?
It only compares the strings and it doesn’t normalise them first.
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 …)
How do you convert a Path to legacy File type?
Path.toFile()
Does Files.exists(Path) follow symlinks?
Yes
What is the Symlink constant?
LinkOptions.NOFOLLOW_LINKS
What does Files.isSameFile(Path, Path)
It compares the path strings only, normalising and following symlinks
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.
How does Files.delete(Path) and Files.deleteIfExists(Path) behave with directories?
Deletes them if they are empty
How does Files.delete(Path) and Files.deleteIfExists(Path) behave with symlinks?
Delete the symlink not the target
What the are the Files.copy signatures?
copy(InputStream, Path)
copy(Path, OutputStream)
copy(Path, Path)
How does Files.copy behave if the destination Path exists already
It throws a FileAlreadyExistsException and if REPLACE_EXISTING has not been specified
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
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
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.
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)
What is the return type of the Files.find() and .walk() methods?
Stream<Path></Path>
Do Files.find() and .walk() methods follow links by default?
No
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.
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)
What is the return type of Executors.newScheduledThreadPool(int)
ScheduledExecutorService
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
What the ExecutorService.execute() and ExecutorService.submit() return types
execute() returns void, while submit() returns Future
Is return null equivalent to return; for a void method
No?
This would not work for Runnable lambda for instance
What ordering will .forEachOrdered(Consumer) process in?
In the stored order of the original stream.
How does Stream.findFirst() behave?
It will find the first stored element in stream even if it is parallel
How does Stream.findAny() behave?
It will return first element read by thread, regardless of sorting or ordering
What are the Streams.reduce signatures?
reduce(BinaryOperator<T>)
reduce(T Identity, BinaryOperator<T>)
reduce(U Identity, BiFunction<U,T>, BinaryOperator<T>)</T></T></T>
What states are relevant for calling .interrupt() on a thread?
WAITING and TIMED_WAITING
What does volatile keyword ensure?
Memory consistency but not threadsafety
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.
How does ScheduledExecutorService work with Callables
schedule(Callable, delay, TimeUnit)
What are the ExectorService methods for Callables?
submit(Callable)
invokeAll(Collection<Callable<T>>)
invokeAny(Collection<Callable<T>>)
with timeouts.</T></T>
Math class methods
.sum
.average
.pow
Can an input stream’s .mark() functionality be re-used? E.g. .reset() called multiple times?
Yes
Can a Record class extend another class?
Can it implement an interface?
No it can’t extend but it can implement and interface
Does String.split() include trailing empty strings?
No
How do you initialise DateTimeFormatter?
DateTimeFormatter df = DateTimeFormatter.ofPattern(“yyyy”);
DateTimeFormatter df = DateTimeFormatter.ISO_DATE;
DateTimeFormatter df = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
How do you get the default locale?
Locale.getDefault()
What needs to be remembered with resources created in try-with-resource blocks?
They are implicitly final and can’t be re-assigned.
What does the ArrayList.add() return?
It returns a boolean if the list is altered
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
What exception does the wrapper parse* methods throw?
NumberFormatException (Unchecked Exception)
Can you override/hide a static method with instance method and vice versa?
No
What is the input of Stream.averageInt
ToIntFuntion
How do you add a new row with ResultSet
.insertRow()