Questions and Answers
- How can you achieve runtime polymorphism in Java?
- method overloading
- method overrunning
- method overriding
- method calling
- Given the following definitions, which of these expression will **NOT** evaluate to true?
- `(i1 | i2) == 3`
- `i2 && b1`
- `b1 || !b2`
- `(i1 ^ i2) < 4`
- What is the output of this code?
- It will not compile because of line 4.
- It will not compile because of line 3.
- 123
- 1234
- Which of the following can replace the CODE SNIPPET to make the code below print "Hello World"?
- `super1.print(); super2.print();`
- `this.print();`
- `super.print();`
- `Interface1.print(); Interface2.print();`
- What does the following code print?
- CD
- CDE
- D
- "abcde"
- What is the result of this code?
- It will show a stack trace with a runtime exception.
- "java.lang.Exception"
- It will run and throw an exception.
- It will not compile.
- Which class can compile given these declarations?
- A
- B
- C
- D
- What is the output of this code?
- The code does not compile.
- truefalse
- truetrue
- falsetrue
- Given the following two classes, what will be the output of the Main class?
- Lines 1 and 2 generate compiler errors due to class name conflicts.
- "-123"
- It will throw an exception on line 5.
- "123"
- What is the result of this code?
- It will not compile because of line 10.
- "Hello!"
- It will not compile because of line 2.
- "World!"
- Given this code, which command will output "2"?
- `java Main 1 2 "3 4" 5`
- `java Main 1 "2" "2" 5`
- `java Main.class 1 "2" 2 5`
- `java Main 1 "2" "3 4" 5`
- What is the output of this code?
- "123451234512345"
- Nothing - this will not compile.
- a negative integer value
- "12345100000"
- What is the output of this code?
- The code does not compile.
- A runtime exception is thrown.
- "world!!world"
- "world!world!"
- How do you write a foreach loop that will iterate over ArrayList\
pencilCase? - `for (Pencil pencil : pencilCase) {}`
- `for (pencilCase.next()) {}`
- `for (Pencil pencil : pencilCase.iterator()) {}`
- `for (pencil in pencilCase) {}`
- What does this code print?
- `0`
- positive number
- negative number
- compilation error
- You have an ArrayList of names that you want to sort alphabetically. Which approach would **NOT** work?
- `names.sort(Comparator.comparing(String::toString))`
- `Collections.sort(names)`
- `names.sort(List.DESCENDING)`
- `names.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList())`
- By implementing encapsulation, you cannot directly access the class's \_ properties unless you are writing code inside the class itself.
- private
- protected
- no-modifier
- public
- Which is the most up-to-date way to instantiate the current date?
- `new SimpleDateFormat("yyyy-MM-dd").format(new Date())`
- `new Date(System.currentTimeMillis())`
- `LocalDate.now()`
- `Calendar.getInstance().getTime()`
- Fill in the blank to create a piece of code that will tell whether `int0` is divisible by `5`:
- `int0 / 5 ? true: false`
- `int0 % 5 == 0`
- `int0 % 5 != 5`
- `Math.isDivisible(int0, 5)`
- How many times will this code print "Hello World!"?
- 10 times
- 9 times
- 5 times
- infinite number of times
- The runtime system starts your program by calling which function first?
- iterative
- hello
- main
- What code would you use in Constructor A to call Constructor B?
- Jedi(name, species, false)
- new Jedi(name, species, false)
- this(name, species, false)
- super(name, species, false)
- Which statement is **NOT** true?
- An anonymous class may specify an abstract base class as its base type.
- An anonymous class does not require a zero-argument constructor.
- An anonymous class may specify an interface as its base type.
- An anonymous class may specify both an abstract class and interface as base types.
- What will this program print out to the console when executed?
- [5, 1, 10]
- [10, 5, 1]
- [1, 5, 10]
- [10, 1, 5]
- What is the output of this code?
- "Hello"
- A runtime exception is thrown.
- The code does not compile.
- "ello"
- Object-oriented programming is a style of programming where you organize your program around \_ rather than \_ and data rather than logic.
- functions; actions
- objects; actions
- actions; functions
- actions; objects
- What statement returns true if "nifty" is of type String?
- `"nifty".getType().equals("String")`
- `"nifty".getType() == String`
- `"nifty".getClass().getSimpleName() == "String"`
- `"nifty" instanceof String`
- What is the output of this code?
- A runtime exception is thrown.
- 3false
- 2true
- 3true
- What is the result of this code?
- It will not compile because of line 7.
- Hello!Hello!
- Hello!World!
- It will not compile because of line 11.
- What method can be used to create a new instance of an object?
- another instance
- field
- constructor
- private method
- Which is the most reliable expression for testing whether the values of two string variables are the same?
- string1 == string2
- string1 = string2
- string1.matches(string2)
- string1.equals(string2)
- Which letters will print when this code is run?
- A, B, and D
- A, C, and D
- C and D
- A and D
- What is the output of this code?
- It will throw a runtime exception.
- It will not compile.
- It will print "Hello World!" three times.
- It will run forever.
- What is the output of this code?
- `[abc, 0, 2, 10]`
- The code does not compile.
- `[abc, 2, 10, 0]`
- `[0, 10, 2, abc]`
- What is the output of this code?
- Hello World!
- HelloHelloWorld!
- Hello Hello World!
- Hello HelloWorld!
- What is displayed when this code is compiled and executed?
- x
- null
- 10
- 5
- Which approach cannot be used to iterate over a List named _theList_?
- A
- B
- C
- D
- What method signature will work with this code?
- public void isHealthy(String avocado)
- boolean isHealthy(String string)
- public isHealthy("avocado")
- private String isHealthy(String food)
- Which are valid keywords in a Java module descriptor (module-info.java)?
- provides, employs
- imports, exports
- consumes, supplies
- requires, exports
- Which type of variable keeps a constant value once it is assigned?
- non-static
- static
- final
- private
- How does the keyword `volatile` affect how a variable is handled?
- It will be read by only one thread at a time.
- It will be stored on the hard drive.
- It will never be cached by the CPU.
- It will be preferentially garbage collected.
- What is the result of this code?
- an alphanumeric character
- a negative number
- a positive number
- a ClassCastException
- You get a NullPointerException. What is the most likely cause?
- A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications.
- Your code has used up all available memory.
- The object you are using has not been instantiated.
- How would you fix this code so that it compiles?
- Make age static.
- Make age global.
- Make age public.
- Initialize age to a number.
- Add a Duck called "Waddles" to the ArrayList **ducks**.
- `Duck waddles = new Duck();`
- `Duck duck = new Duck("Waddles");`
- `ducks.add(new Duck("Waddles"));`
- `ducks.add(new Waddles());`
- If you encounter `UnsupportedClassVersionError` it means the code was `___` on a newer version of Java than the JRE `___` it.
- executed; interpreting
- executed; compiling
- compiled; executing
- compiled, translating
- Given this class, how would you make the code compile?
- A
- B
- C
- D
- How many times f will be printed?
- 4
- 3
- 5
- A Runtime exception will be thrown
- Which statements about `abstract` classes are true?
- 1, 2, and 3
- only 3
- 2 and 3
- only 2
- Which keyword lets you call the constructor of a parent class?
- parent
- super
- this
- new
- What is the result of this code?
- It will throw an ArithmeticException.
- It will run and output 0.
- It will not compile because of line 3.
- It will run and output infinity.
- Normally, to access a static member of a class such as Math.PI, you would need to specify the class "Math". What would be the best way to allow you to use simply "PI" in your code?
- Add a static import.
- Declare local copies of the constant in your code.
- This cannot be done. You must always qualify references to static members with the class form which they came from.
- Put the static members in an interface and inherit from that interface.
- Which keyword lets you use an interface?
- extends
- implements
- inherits
- import
- Why are ArrayLists better than arrays?
- You don't have to decide the size of an ArrayList when you first make it.
- You can put more items into an ArrayList than into an array.
- ArrayLists can hold more kinds of objects than arrays.
- You don't have to decide the type of an ArrayList when you first make it.
- Declare a variable that holds the first four digits of ?
- int pi = 3.141;
- decimal pi = 3.141;
- double pi = 3.141;
- float pi = 3.141;
- Use the magic power to cast a spell
- `new MagicPower().castSpell("expecto patronum")`
- `MagicPower magicPower = new MagicPower();`
- `MagicPower.castSpell("expelliarmus");`
- `new MagicPower.castSpell();`
- What language construct serves as a blueprint containing an object's properties and functionality?
- constructor
- instance
- class
- method
- What does this code print?
- 10 10
- 5 10
- 10 5
- 5 5
- What is the result of this code?
- Hello World
- It will not compile because the second catch statement is unreachable
- Hello World!
- It will throw runtime exception
- Which is not a java keyword
- finally
- native
- interface
- unsigned
- Which operator would you use to find the remainder after division?
- `%`
- `//`
- `/`
- `DIV`
- Which choice is a disadvantage of inheritance?
- Overridden methods of the parent class cannot be reused.
- Responsibilities are not evenly distributed between parent and child classes.
- Classes related by inheritance are tightly coupled to each other.
- The internal state of the parent class is accessible to its children.
- Declare and initialize an array of 10 ints.
- `Array
numbers = new Array (10);` - `Array[int] numbers = new Array[int](10);`
- `int[] numbers = new int[10];`
- `int numbers[] = int[10];`
- `Array
- Refactor this event handler to a lambda expression:
- `groucyButton.addActionListener(ActionListener listener -> System.out.println("Press me one more time..."));`
- `groucyButton.addActionListener((event) -> System.out.println("Press me one more time..."));`
- `groucyButton.addActionListener(new ActionListener(ActionEvent e) {() -> System.out.println("Press me one more time...");});`
- `groucyButton.addActionListener(() -> System.out.println("Press me one more time..."));`
- Which functional interfaces does Java provide to serve as data types for lambda expressions?
- Observer, Observable
- Collector, Builder
- Filter, Map, Reduce
- Consumer, Predicate, Supplier
- What is a valid use of the hashCode() method?
- encrypting user passwords
- deciding if two instances of a class are equal
- enabling HashMap to find matches faster
- moving objects from a List to a HashMap
- What kind of relationship does "extends" denote?
- uses-a
- is-a
- has-a
- was-a
- How do you force an object to be garbage collected?
- Set object to null and call Runtime.gc()
- Set object to null and call System.gc()
- Set object to null and call Runtime.getRuntime().runFinalization()
- There is no way to force an object to be garbage collected
- Java programmers commonly use design patterns. Some examples are the **\_**, which helps create instances of a class, the **\_**, which ensures that only one instance of a class can be created; and the **\_**, which allows for a group of algorithms to be interchangeable.
- static factory method; singleton; strategy pattern
- strategy pattern; static factory method; singleton
- creation pattern; singleton; prototype pattern
- singleton; strategy pattern; static factory method
- Using Java's Reflection API, you can use \_ to get the name of a class and \_ to retrieve an array of its methods.
- this.getClass().getSimpleName(); this.getClass().getDeclaredMethods()
- this.getName(); this.getMethods()
- Reflection.getName(this); Reflection.getMethods(this)
- Reflection.getClass(this).getName(); Reflection.getClass(this).getMethods()
- Which is not a valid lambda expression?
- `a -> false;`
- `(a) -> false;`
- `String a -> false;`
- `(String a) -> false;`
- Which access modifier makes variables and methods visible only in the class where they are declared?
- public
- protected
- nonmodifier
- private
- What type of variable can be assigned to only once?
- private
- non-static
- final
- static
- How would you convert a String to an Int?
- `"21".intValue()`
- `String.toInt("21")`
- `Integer.parseInt("21")`
- `String.valueOf("21")`
- What method should be added to the Duck class to print the name Moby?
- `public String toString() { return name; } `
- `public void println() { System.out.println(name); } `
- `String toString() { return this.name; } `
- `public void toString() { System.out.println(this.name); } `
- Which operator is used to concatenate Strings in Java
- `+`
- `&`
- `.`
- `-`
- How many times does this loop print "exterminate"?
- two
- four
- three
- five
- What is the value of myCharacter after line 3 is run?
- p
- r
- e
- i
- When should you use a static method?
- when your method is related to the object's characteristics
- when you want your method to be available independently of class instances
- when your method uses an object's instance variable
- when your method is dependent on the specific instance that calls it
- What phrase indicates that a function receives a copy of each argument passed to it rather than a reference to the objects themselves?
- pass by reference
- pass by occurrence
- pass by value
- API call
- In Java, what is the scope of a method's argument or parameter?
- inside the method
- both inside and outside the method
- neither inside nor outside the method
- outside the method
- What is the output of this code?
- 5
- 8
- 1
- 3
- Which change will make this code compile successfully?
- Change line 2 to `public static final String message`
- Change line 6 to `public void print2(){}`
- Remove the body of the `print2` method and add a semicolon.
- Remove the body of the `print` method.
- What is the output of this code?
- falsefalse
- truetrue
- falsetrue
- truefalse
- Which code snippet is valid?
- `ArrayList
words = new ArrayList (){"Hello", "World"};` - `ArrayList words = Arrays.asList("Hello", "World");`
- `ArrayList
words = {"Hello", "World"};` - `ArrayList
words = new ArrayList<>(Arrays.asList("Hello", "World"));`
- `ArrayList
- What is the output of this code?
- A runtime exception is thrown.
- "HelloWorld!"
- "hello"
- ????
- How would you use the TaxCalculator to determine the amount of tax on $50?
- TaxCalculator.calculate(50);
- new TaxCalculator.calculate(50);
- calculate(50);
- new TaxCalculator.calculate($50);
- Which characteristic does not apply to instances of java.util.HashSet=
- uses hashcode of objects when inserted
- contains unordred elements
- contains unique elements
- contains sorted elements
- What is the output?
- 1 3 2 4
- 4 2 3 1
- 1 2 3 4
- 4 3 2 1
- What will this code print, assuming it is inside the main method of a class?
- my
- hellomyfriends
- hello
- friends
- You have an instance of type Map
named instruments containing the following key-value pairs: guitar=1200, cello=3000, and drum=2000. If you add the new key-value pair cello=4500 to the Map using the put method, how many elements do you have in the Map when you call instruments.size()? - 2
- When calling the put method, Java will throw an exception
- 4
- 3
- Which class acts as root class for Java Exception hierarchy?
- Clonable
- Throwable
- Object
- Serializable
- Which class does not implement the java.util.Collection interface?
- java.util.Vector
- java.util.ArrayList
- java.util.HashSet
- java.util.HashMap
- You have a variable of named `employees` of type `List
` containing multiple entries. The `Employee` type has a method `getName()` that returns te employee name. Which statement properly extracts a list of employee names? - `employees.collect(employee -> employee.getName());`
- `employees.filter(Employee::getName).collect(Collectors.toUnmodifiableList());`
- `employees.stream().map(Employee::getName).collect(Collectors.toList());`
- `employees.stream().collect((e) -> e.getName());`
- This code does not compile. What needs to be changed so that it does?
- Add a constructor that accepts a `String` parameter and assigns it to the field `shortCode`.
- Remove the `final` keyword for the field `shortCode`.
- All enums need to be defined on a single line of code.
- Add a setter method for the field `shortCode`.
- Which language feature ensures that objects implementing the `AutoCloseable` interface are closed when it completes?
- try-catch-finally
- try-finally-close
- try-with-resources
- try-catch-close
- What code should go in line 3?
- `int[][] array = new int[][];`
- `int[][] array = new int[3][3];`
- `int[][] array = new int[2][2];`
- `int[][] array = [][];`
- Is this an example of method overloading or overriding?
- neither
- both
- overloading
- overriding
- Which choice is the best data type for working with money in Java?
- float
- String
- double
- BigDecimal
- Which statement about constructors is not ture?
- A class can have multiple constructors with a different parameter list.
- You can call another constructor with `this` or `super`.
- A constructor does not define a return value.
- Every class must explicitly define a constructor without parameters.
- What language feature allows types to be parameters on classes, interfaces, and methods in order to reuse the same code for different data types?
- Regular Expressions
- Reflection
- Generics
- Concurrency
- What will be printed?
- raspberry
- strawberry
- blueberry
- rasp
- What is the value of `forestCount` after this code executes?
- 3
- 4
- 2
- When calling the put method, Java will throw an exception
- What is a problem with this code?
- String should be compared using == method instead of equals.
- Modifying a collection while iterating through it can throw a ConcurrentModificationException.
- The List interface does not allow an argument of type String to be passed to the remove method.
- ArrayList does not implement the List interface.
- How do you convert this method into a lambda expression?
- `Function
squareLambda = (int x) -> { x * x };` - `Function
squareLambda = () -> { return x * x };` - `Function
squareLambda = x -> x * x;` - `Function
squareLambda = x -> return x * x;`
- `Function
- Which choice is a valid implementation of this interface?
- A
- B
- C
- D
- What is the result of this program?
- 10
- 20
- null
- An error will occur when compiling.
- Which statement must be inserted on line 1 to print the value true?
- `Integer val = 15;`
- `String val = "Sam";`
- `String val = null;`
- `Optional
val = Optional.empty();`
- What will this code print, assuming it is inside the main method of a class?
- false true
- true true
- true false
- false false
- What will this code print?
- `[Two]`
- `[One, Two, Three]`
- `[One, Three]`
- `Two`
- Which code checks whether the characters in two Strings,named `time` and `money`, are the same?
- `if(time <> money){}`
- `if(time.equals(money)){}`
- `if(time == money){}`
- `if(time = money){}`
- An **\_** is a serious issue thrown by the JVM that the JVM is unlikely to recover from. An **
- exception,assertion
- AbnormalException, AccidentalException
- error, exception
- exception, error
- Which keyword would not be allowed here?
- static
- protected
- public
- void
- Which OOP concept is this code an example of?
- composition
- generics
- polymorphism
- encapsulation
- What does this code print?
- true; false
- false; false
- false; true
- true; true
- What keyword is added to a method declaration to ensure that two threads do not simultaneously execute it on the same object instance?
- native
- volatile
- synchronized
- lock
- Which is a valid type for this lambda function?
- `Function
` - `Function
` - `Function
` - `Function
`
- `Function
- What is displayed when this code is compiled and executed?
- 6
- 3
- 4
- 7
- What variable type should be declared for capitalize?
- `Function
` - `Stream
` - `String
` - `Map
`
- `Function
- Which is the correct return type for the processFunction method?
- `Integer`
- `String`
- `Consumer`
- `Function
`
- What function could you use to replace slashes for dashes in a list of dates?
- `UnaryOperator
replaceSlashes = date -> date.replace("/", "-");` - `Function
replaceSlashes = dates -> dates.replace("-", "/");` - `Map
replaceSlashes = dates.replace("/", "-");` - `Consumer
replaceSlashes = date -> date.replace("/", "-");`
- `UnaryOperator
- From which class do all other classes implicitly extend?
- `Object`
- `Main`
- `Java`
- `Class`
- How do you create and run a Thread for this class?
- `Thread thread = new Thread(new CurrentDateRunnable()); thread.start();`
- `new Thread(new CurrentDateRunnable()).join();`
- `new CurrentDateRunnable().run();`
- `new CurrentDateRunnable().start();`
- Which expression is a functional equivalent?
- A
- B
- C
- D