0% found this document useful (0 votes)
4 views60 pages

Advanced Java Quiz

The document consists of a series of quiz questions and answers related to Java programming concepts, including imperative and functional programming, lambda expressions, functional interfaces, streams, and design patterns. It covers various topics such as the usage of annotations, method references, input/output operations, and the importance of design principles like SOLID. Additionally, it discusses the advantages and disadvantages of design patterns like singletons and factories.

Uploaded by

manvisingh2618
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Advanced Java Quiz

The document consists of a series of quiz questions and answers related to Java programming concepts, including imperative and functional programming, lambda expressions, functional interfaces, streams, and design patterns. It covers various topics such as the usage of annotations, method references, input/output operations, and the importance of design principles like SOLID. Additionally, it discusses the advantages and disadvantages of design patterns like singletons and factories.

Uploaded by

manvisingh2618
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Question 1 of 2 Which of these are elements of imperative programs? Z| for loops and while loops lambda expresssions ¥| Individual steps about howa task is performed Streams Question 2 of 2 Which of these are elements of functional programming in Java? YJ] Lambda expressions v] Streams S step-by-step transformation of what is happening to inputs. for loops and while| loops Question 1 of 2 Which parts of the lambda expression syntax are optional? v v The return statement The parameter types The arrow -> The parentheses (when there is just one parameter) The curly braces ({, }), for single-statement lambdas. Question 2 of 2 Which of the following are valid lambda expressions? v| (Double x, int y) -> { return x * y; } Y) Oy) > xt y Yi x > x * xX ¥} OO -> 10 {x y} -> (x+y) (Double x, Double y) -> {x*y} Quiz Question Which of these statements are true? ¥] functional interface is an interface with exactly one abstract method. A functional interface is an abstract class with several abstract method. ¥] functional interface can be implemented by a lambda expression. VY] The @Functionalinterface annotation can help detect errors. Question 1 of 6 Why should you use the @FunctionalInterface annotation when writing your own functional interfaces? v It will cause a compilation error if the annotated interface is not a valid functional interface. The Java compiler requires functional interfaces to have that annotation. Ittells users of your interface that the interface is intended to be targeted by lambdas. Itallows the Java runtime to optimize lambdas that implement the functional interface. Question 2 of 6 What is the functional method of the Function interface above? © identity © ply © compose © andtThen abstract class Printable { abstract void print(String prefix); } Question 3 of 6 Is Printable a functional interface? O Yes © No interface Squareable { default int square(int a) { return a * a; } t Question 4 of 6 Is Squareable a functional interface? O Yes © No public interface BiFunction { R apply(T t, U u); + Question 5 of 6 Is BiFunction a functional interface? © Yes O No interface ConvertibleToString { @Override String toString(); Question 6 of 6 Is ConvertibleToString a functional interface? O Yes © No Question 1 of 2 Which of these statements are true for anonymous classes? Shorter code that can be defined in-line. ¥] The class is generated at compile-time ¥] Can override the equals() and hashCode()/ methods this refers to the enclosing class Question 2 of 2 What does the following program print? public final class Main { public static void main(String[] args) { Runnable r = () -> [Link]([Link]()); rerun()5 + Main class Main O00 class Main$1. © mit ©@© The program does not compile. Question 1 of 3 What is true of effectively final variables? The variable has the final, keyword in front of it first initialized, YJ] The value of the variable is never changed after The variable has no effect because it is not used inside of any lambdas. ¥] 'fyou add the final keyword to the variable, the code will still compile. Variables that hold primitive types like int and double cannot be effectively final. Question 2 of 3 Which variable(s) are captured in the lambda? input output ¥] bySize Question 3 of 3 In the code snippet above, a lambda captures the variable i. Is 4 effectively final? O ves © vo Question 1 of 3 Where can you use method references? O Outside classes © Anywhere you can use a lambda expression. O In for loops Question 2 of 3 Considering that s isa String, what would be the eq) reference to the following lambda expression? lent method S -> s,toUpperCase() © String->touppercase CE string: :touppercase() © string: :touppercase toUppercase Question 3 of 3 Why should you use a method reference instead of defining your own lambda? You need to capture a variable. [¥] There is already a method defined that does what you want. Because method references support better type inference. (Y¥] When the method reference results in better code readability. Question 1 of 3 What is the correct order of a Stream Pipeline? @ These are the correct matches. Order Operations 1 Pe eed Cera} 3 Oa ert Question 2 of 3 What is the terminal operator in the next code? [Link](“hello", “world") -map(String::toUpperCase) .collect (Collectors. joining(" ", © [Link](*hello", “world") © _ -map(string: :toupperCase) ©@ collect([Link](" ", Question 3 of 3 What does the following code print? [Link](1, 2, 3) .sorted([Link]()) -peek([Link]: :print) 5 nothing 123) 321 312 000 © Quiz Question What are the Collector s used for? Y] Aggregating stream elements into a data structure such as list, a map or a set. ¥]_ Performing reduction operations like summing or counting elements. ‘Transforming stream elements into new streams. Quiz Question How does the Optional class help you avoid Nul1PointerException in your code? Methods like equals and toString|are called on an object instead of a v] null reference. (¥] Signals that the AP! caller should check if there is a value before using it Methods like map and orE1se can be used on both empty and non-empty optional s. Calling) tostring in an [Link]() object will throw a NullPointerexception anyway. ‘variable of type Optional can never be null. Question 1 of 2 Which is true of data stored in program memory? © ifthe program restarts, the data in memory will be cleared. © ithe program restarts, it will be able to read the same data from memory. Question 2 of 2 Why is it useful to store data in files? Y] The file will be there when the program stops running. ‘YJ Other programs will be able to read the file. ¥] Files can store more data than can fit in program memory. Question 1 of 4 Which of the following is the Java Files AP! not useful for? © Reading and writing files on the local file system © Copying a local file to a mounted network drive © Giving yourself permissions to an existing file © Downloading a URL from the Internet O Telling whether a Path points to file or a directory Question 2 of 4 ‘Match each file open option to what it does: @ These are the correct matches. File Open Option What it Does READ Cee ace Tees CREATE [CREATE_NEW ree Mace eet WerTe eee aaa APPEND oe at ee ac ol ri Question 3 of 4 Match the kind of path with its description @ These are the correct matches. Kind of path Description Absolute path Seem aC Cle AOE) Maz, or a drive name on PT aves Relative path Deere a acre pO eee ClcetArL Perey Question 4 of 4 Which of the following are absolute paths? vj / ¥] C:/Documents/Udacity/[Link] udacity/Downloads ../home/../home/local/bin/ v¥| /usr/1ib/jvm/java-11-openjdk-amd64/bin/java Question 1 of 2 When would you need to write code that directly uses InputStream s and Outputstreams. (© When there's a need en access lom-level bytes of data, ke Implementing a custom network protocol or file format. © When calling a REST API over a network. © When writing text to a file. Question 2 of 2 How many bytes of data can be read from a single call to the [Link](..) method? vj 1 v} 10 ¥} 20 4] 2048 Quiz Question Reader's and Writer s are built on top of... © InputStreams and OutputStream s. © _ BufferedReader s and Bufferediiriter s Question 1 of 2 Why do we need to specify character encodings when reading and writing files? © THe fles only contan binary data (0s and 13), and programs need to know how to translate that into human-readable text. © Because the files may be encrypted to increase the security. O__Because the file contents could be ina diferent language and we need to translate that to English ot Question 2 of 2 Match each encoding with the corresponding description: @ These are the correct matches. Encoding Feature ure Bee ae HTML document urF-16 Ree en eet the text is non-ASCII or non- ee Gis OE a ean) Peete cee urF-32 eer ea eRe eines Question 1 of 4 Match each Input/Output utility with its description @ These are the correct matches. Input/Output Description Input/Output Streams i pt Peano Cn Readers/Writers CC Cee era rece go aoe) See Ra es Buffered Readers/Writers Can operate with lines of Cae UEC buffer. Question 2 of 4 You are writing a kilobyte of data (1 Kilobyte = 1000 bytes) to file with a Buffereduriter , 100 bytes at a time. Your code calls the write() method 10 times, but you noticed the program only wrote to disk twice. How big was the Bufferediiriter ‘s in-memory buffer? © 100 bytes © 600 bytes © 1000 bytes © 2000 bytes Question 3 of 4 Which of the following is not a good reason to use a BufferedReader instead of a Reader ? Reduces the number of read or write operations to disk. Creates an array of pointers to disk. Reading from memory is faster than reading from disk. OO@O°O It's easier to call readLine() than to read individual bytes into an array. Question 4 of 4 Which methods are present in BufferedReader or Bufferediiriter, but not present in Reader or Writer ? v) readLine() YJ) flush() read() write() Question 1 of 2 Why it is important to close streams that operate on files? v| To avoid wasting resources. YJ The operating system limits the number of open files. ¥}| Toensure the file has latest information. Open files use up disk space Question 2 of 2 Suppose you have a FileReader variable that points to a file. How can you be sure that the file is closed when you are done using it? YJ) Call the close() method inside a finally block. Y)_ Using try-with-resources. Assigning null to the FileReader variable. Manually deleting the file from the operating system. Quiz Question According to the naming convention, what prefixes are used to access the properties of a Java Bean? ‘v] get @ v] set ®@ update read mr) Quiz Question Why would we need to serialize a Java object? ¥| To save its contents to file. ¥| To send it over a network. To access its properties. To invoke its methods. Match the representation with the format it corresponds to. @ These are the correct matches. Example Format "id" : "122131", C name": "Diet co "name": "Snapple “items 122131 Snapple Question 1 of 2 Match each software design principle with its description. @ These are the correct matches. Description Principle Each class should have only one responsibility. co as iad Cer Software should be open for extension but closed for Ccume es ad modification. Objects that implement the same interface should be interchangeable Liskov Substitution Principle without breaking the program. Your code should only depend on aaa ll interfaces that it actually uses. Bee te Your code should only depend on Pee interfaces that it actually uses. INS Carer All parts of your code should depend on interfaces, or abstractions. Implementation Dee cua details should depend on Se interfaces, not the other way around. Question 2 of 2 Match each design pattern category with its description. @ These are the correct matches. Description Design pattern category Patterns that deal with creating objects. eect Patterns that deal with how different objects interact. eT ENS Patterns that deal with how different objects fit together. Swe | PESTS Question 1 of 2 Which statements apply to singletons? Singletons can be multiple instances that are globally accessible. Y]_ Asingleton is one instance that is used throughout entire system. ¥]_Asingleton is only initialized once. ¥] Enumeration values Java enum types) are always singletons. Question 2 of 2 why ©@ tis not very important. portant to call the singleton’s static method getInstance() ? © Following naming conventions can help callers find which method to call © Having a method name starting with "get helps automated toting discover instance. CO _Bettnstance() helps the ava compiler know that this is a singleton method that can only be created once. Quiz Question What are some disadvantages to using the singleton pattern? (¥] Your code may be hard to refactor if you ever need multiple instances. (¥] Code that depends on singletons can be hard to test. It’s impossible to ensure there's one and only one instance of the singleton object. Dependency injection is incompatible with the singleton pattern. Question 1 of 2 Why are factories useful? Factories can return different implementations of an interface, depending on v) how the factory is invoked. Y] Factories can create several related kinds of objects. Enable you to create just one instance of an object. ¥] Allows you to delegate the construction of objects. Question 2 of 2 Which SOLID design principles apply to the abstract factory pattern? Single Responsibility Principle Open-Closed Principle ¥]_ Liskov Substitution Principle ¥]_ interface Segregation Principle ¥] Dependency Inversion Principle Question 1 of 2 Why is the builder pattern useful? ¥] Lets you create mutable versions of immutable objects. ¥] Holds state that can be mutated before building an object. Can improve the AP! for object creation, especially when the class being instantiated has lots of constructor parameters. Allocates memory before creating the object. Question 2 of 2 Match each creational design pattern with its description. @ These are the correct matches. Description Pattern Astatic method that hides construction details, such as Pea Cee [Link](...). ‘An object that creates other objects, and hides the construction details. CREE) ‘A mutable factory that represents 7 the state of a to-be-created object. exes Question 1 of 3 Which statements are true about the strategy pattern? ¥] Client code is agnostic of which concrete implementation is being used. ¥]_ The strategies can be swapped at any time. ¥] Aninterface defines a task. There may be many concrete implementations. Once a strategy is defined, it cannot be changed. You always have a fixed number of predefined strategies to choose from. Question 2 of 3 When can you use lambdas to implement concrete strategies? © when the task is defined using an abstract class. © When the task is a functional interface. © You cannot use lambdas to implement the strategy pattern. Question 3 of 3 What is the role of polymorphism in the strategy pattern? @ o¥Morphism determines which concrete method implementation gets called when invoking the task interface. Each strategy has a single responsibility. on the method signature. The strategy pattern relies on the Liskov Substitution Principle, not O St2ticpolymorphism determines which overloaded method gets called, based oO polymorphism. ery Question 1 of 2 Which SOLID design principles apply to the template method pattern? Single Responsibility Principle ¥] Open-Closed Principle YJ Liskov Substitution Principle Interface Segregation Principle Y]_ Dependency Inversion Principle Question 2 of 2 Match each behavioral design pattern with its description. @ These are the correct matches. Description Pattern Different implementations of a task interface can be swapped at Strategy pattern runtime. Subclasses extend a base class and override different placeholder Seer crn) methods. "subject" notifies one or more subscribers that something has Cea changed about the subject. Quiz Question What's the main purpose of the adapter pattern? © To transform one API into another API. O To make new code compatible with legacy APIs. oO To add additional functionality to an existing API. Question 1 of 3 How does the decorator pattern work? (© 149 new functionality to an existing object dynamically by “wrapping” it Favoring composition. © Extends an existing class, favoring inheritance. Question 2 of 3 Why is composition important to the Adapter and Decorator patterns? © Both these patterns "wrap" a delegate class instead of inheriting from it. © Both adapters and decorators inherit from base classes to add functionality.

You might also like