OOP and Basic and Advanced Java QC

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

When was the java.util.function package introduced?

Java 8, to implement functional programming in Java.

What are the states of a thread?

New Runnable Blocked Waiting Timed_Waiting Terminated

What are method references? Describe their syntax.

They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods Instance methods of particular objects Instance methods of an arbitrary object of a particular type Constructor

What is parametric polymorphism?

This is talking about generics. We're creating methods using generic variables without worrying about the actual type of parameter. Examples: T, E (Our ArrayList implementation uses these)

How can a String be created outside of the String Pool?

Using new keyword with constructor or String.intern() method.

What is the method signature of the abstract method in the Consumer interface?

void accept(T t); default Consumer<T> and Then(Consumer<? super T> after) {}

What is the "new" keyword used for?

"New" is used when calling a constructor for a class.

Do Stream operations manipulate the collection being streamed?

A stream can be composed of multiple functions that create a pipeline that data that flows through. This data cannot be mutated. That is to say the original data structure doesn't change. However the data can be transformed and later stored in another data structure or perhaps consumed by another operation.

What is the difference between an interface and an abstract class?

Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can't have any method implementations.

Pillars of OOP

Abstraction Encapsulation Inheritance Polymorphism

What are variable arguments?

Also known as Varargs, it is a features that simplifies the creation of methods that need to take a variable number of arguments.

What is an Optional?

An Optional is a kind of wrapper object which may or may not contain a value, with a few helper methods to handle existing or non-existent values. Optionals are useful as replacements for null values when returning an "empty" response from a method.

What is a Stream and how is it different than a Collection?

An abstraction which allow defining operations which do not modify the source data and are lazily executed. The main difference between a stream and a collection is that streams DO NOT store data where collections stores/holds all the data that the data structure currently has.

How can you convert an array into a Stream?

Arrays.stream(array) or Stream.of(array) both accomplish this.

Articulate the difference between Stream#map and Stream#flatMap.

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R> . The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

What are the main types of functional interfaces?

Consumer Predicate Function Supplier

What are default interface methods?

Default interface methods are methods created inside of an interface by using the default keyword in the creation of the method. These provide backwards compatibility so that existing interfaces can use lambda expressions.

What is a default method, and why should you use them?

Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces. In particular, default methods enable you to add methods that accept lambda expressions as parameters to existing interfaces.

What are intermediate Stream operations? Name a few.

Intermediate operations all take a stream and return a new stream. They are not actually invoked until a terminal operation is called. Common ones include map(), filter(), sorted(), distinct(),

What is the String Pool?

It is a pool of String values stored in Java Heap Memory.

What is the function of Stream#filter, what does it take as a parameter?

It returns a Stream consisting of the elements of the given stream that match the given predicate. The filter() argument should be stateless predicate which is applied to each element in the stream to determine if it should be included or not.

What is the keyword "synchronized" used for?

Using the synchronized keyword on a piece of logic enforces that only one thread can access the resource at any given time.

What is the function of Stream#flatMap, what does it take as a parameter?

With streams, the flatMap method takes a function as an argument, which returns another stream. This function is applied to each element of a stream, which would result in a stream of streams. However, flatMap has the effect of replacing each generated stream by the contents of that stream.

What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects. They are Byte, Short, Integer, Long, Float, Double, Boolean, and Character.

Are Java Strings thread-safe? Why?

Yes, Java Strings are thread safe because they're immutable - they don't change value after creation. The reference to the String object, however, is not thread safe.

Does Java employ "pass-by-value" or "pass-by-reference"?

Java is pass by value. Both primitives and non-primatives are passed by value - referring to the value on the stack - this is the address on the heap at which the real value resides.

Can exceptions be caught by multiple catch blocks in any order?

Multiple catch blocks are allowed. More specific exceptions must come before more general exception types. Multi-catch blocks (aka catching more than one exception in a given block) are also allowed, with exception types separated by |

Are you required to handle RuntimeExceptions?

No, because they are most likely a bad idea to try and handle.

Can garbage collected be forced in Java?

No. You can use System.gc and "suggest" it, but there is no guarantee.

Describe the characteristics of the object-oriented paradigm (for example, Java language is OOP)

Object-oriented, bundle data and behavior into a single unit, the class, which is an example of encapsulation High-level, it's abstracted away from hardware and makes the process of programming simpler and easier to understand. Class-based, everything written is inside a class and utilizes inheritance.

Describe the Open-closed principle

Objects or entities should be open for extension but closed for modification. Objects should be able to be inherited from but not able to be changed.

What are packages used for?

Packages are group of similar types of classes, interfaces, and sub-packages. The directory structure within our own Java projects are also packages. The primary benefits of Java's packages are: Categorization Access protection Avoid naming collisions

What is a POJO?

Plain Old Java Object - ordinary java object, not bound by any special restriction. Commonly used to increase reusability of java code.

What is the function of Stream#reduce, what does it take as a parameter?

Reducing is the repeated process of combining all elements. Reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.

What are some examples of functional interfaces?

Runnable, Action Listener, Comparable, Consumer, Supplier, Function, Predicate.

What kinds of methods can be references using method references?

Static Method Reference. Instance Method Reference of a particular object. Instance Method Reference of an arbitrary object of a particular type. Constructor Reference.

What are static imports?

Static imports are a feature that allow access to static members of a class without having to use the class name. e.g: import static java.lang.Math; System.out.println(sqrt(4));

What is the method signature of the abstract method in the Supplier interface?

T get ( ) The abstract method get ( ) is a functional method. It does not accept any argument but return newly generated values ( T ) in the stream.

What are terminal Stream operations? Name a few.

Terminal operations all take in a stream but do not return another stream. Once a series of streams hits a terminal operation, the intermediate operations are called and the final return type is produced. Some examples: forEach(), toArray(), collect(), min(), max()

List the Java primitive types

The eight primitive types defined in Java are int, byte, short, long, float, double, boolean, and char

What is the purpose of the .finalize() method?

The finalize method gets called when the garbage is about to be collected. Although it is possible that the object never gets collected and finalize never gets called.

Define Encapsulation and provide advantages to using it

The idea of combining data and behaviors into a single logical unit, the class. It also includes hiding and preventing changes to class members. The encapsulated object controls access to its own internal state using getters and setters.Access Modifiers: Public, Private, Default, Protected

In what way does Java employ inheritance?

Through the use of the "extends" keyword or the use of interfaces with default methods.

What property of a Java primitive array tells us the size of the array?

array.length tells us the size of the array

What does the "static" keyword mean?

denotes "class" scope, meaning the member resides on the class itself, not object instances. - static variables can be accessed through the class (ex- MyClass.staticVariable) - static methods can be called directly without needing an instance of the class (ex- MyClass.someMethod())

What is the main method signature?

public static void main(String[] args)

What modifying keywords are implicitly applied to variable members declared within an interface?

public, static & final. - all methods declared in interfaces are implicitly public and abstract.

What is the function of Stream#map, what does it take as a parameter?

takes a function as a parameter and applies that function to the incoming stream and returns a stream of the elements after the function has been applied.

What are some ways of making Optional objects, since its constructor is declared as private?

to create an empty Optional object: Optional<String> empty = Optional.empty(); String name = "Java"; Optional<String> item = Optional.of(name); (can't be null) Optional<String> item2 = Optional.ofNullable(name); (can be null)

What is ad hoc polymorphism?

A technique used to define the same method with different implementations and different arguments. Example: method overloading

What is the difference between a HashSet and a TreeSet?

A TreeSet is a set where the elements are sorted, a HashSet are where the elements are not sorted or ordered. A HashSet is faster than a TreeSet. HashSet allows null objects, TreeSet does not. HashSet is backed by HashMap while TreeSet is backed by NavigableMap HashSet uses .equals() to compare two objects in Set but TreeSet uses .compareTo()

Describe the Single Responsibility Principle

A class should have one and only one reason to change, meaning that a class should only have one job.

What is the difference between a while and a do-while loop?

A do-while loop will always run at least once.

What is the difference between an exception and an error in Java?

An exception can be handled whereas an error cannot and probably should not be handled.

What is the difference between an object and a class?

An object is a member or an "instance" of a class. A class is the blueprint, or code-template for the objects. An object is the cookie, the class is the cookie cutter.

What are annotations used for in Java?

Annotations are a method of associating metadata with program elements (class/interface/methods/fields) enabling the extraction of program behaviors and the generation of interdependent code via the compiler or the JVM. It's an alternative to XML and marker interfaces.

What is autoboxing and unboxing?

Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. For example, the compiler converts an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this operation is called unboxing.

Describe the characteristics and application of the singleton design pattern

Characteristics: - Provides a single instance of an object with a global access point to that instance. - Makes use of a private constructor. Application: - Used to restrict the instantiation of a class and ensures that only one instance of the class exists in the JVM. Singleton pattern is mostly used in multi-threaded and database applications. - Used in logging, caching, thread pools, configuration settings.

What is the difference between a checked and an unchecked exception?

Checked exceptions are the exception class and all its subclasses. They represent occasions where it is reasonable to anticipate an unexpected condition. They are required to be handled or the code won't be compiled. Unchecked exceptions are RuntimeExceptions and all its subclasses. Unchecked exceptions are not required to be handled like checked exceptions are.

What are the scopes in which a variable can exist in Java?

Class level - highest level, anything defined inside a class but outside of any methods of blocks are included. Method level - Anything defined inside a method are included and are accessible by it and any deeper blocks but not by other methods or blocks in the same. Block level - Anything defining in that block are accessible by that block and any deeper block, but not outside of it. Instance scope (object scope) - Each object has its own copy of its variables and methods. For example: changing one object's variables does not change another object's variables.

What are some different types of polymorphism?

Compile time polymorphism: Method overloading- the practice of implementing methods with the same name but with different parameter lists. This allows us to provide similar implementations depending on parameters. Runtime polymorphism: Method overriding- modifying a method that a child class inherits from their parent. Implementing the method with the exact same signature in the child class but writing a different implementations.

What are some constructs used in Java for flow control?

Decision-making statements : if-then, if-then-else, switch. Looping statements : for, while, do-while. Branching statements : break, continue, return.

What causes a deadlock?

Describes a situation where 2 or more threads are blocked trying to access the same resource, waiting for the other. Neither thread can continue execution, so the program halts indefinitely.

In what way does Java employ encapsulation?

Encapsulation can be achieved by declaring all variables in the class as private and writing public methods in the class to get and set the values of variables.

Describe the Dependency Inversion Principle

Entities must depend on abstractions, not on concretions. It states that the high-level modules must not depend on the low-level modules.

What is the Object class's function in the Java language?

Every class in Java is directly or indirectly derived from the Object class.

What are the characteristics of a Queue?

First in, first out - like line queue.. Enqueue adds an element at the end of the queue, dequeue removes the oldest element from the start of the queue. Peek returns the oldest element from the queue but doesn't remove it (it's just telling the value) it has a capacity for the number of elements it can hold, and as elements are added it automatically increases via growth. Queues can accept null as a valid value for ref types and allow duplicate elements - can hold a spot with null and can have twins in a line right? makes sense.

How can exceptions be handled in Java?

Handling or Ducking Exceptions are handled by placing the risky code inside of a try/catch block, or by ducking it and declaring it so the type of exception to be thrown is listed in the method signature, letting the method deal with it.

What causes a NullPointerException?

It's an exception that occurs when a reference points to no location in memory as though it were referencing an object.

Describe the Interface Segregation Principle

Shouldn't have an interface that has things you aren't interested in. If someone goes to implement your interface and there are a lot of methods that they don't need, you should split your one interface into two or more.

What is the difference between String, StringBuilder, and StringBuffer?

String: immutable - slowest, not used in threaded environments. StringBuffer and StringBuilder: mutable StringBuilder is fastest single threaded, non-synchronized - not thread safe. StringBuffer is Multi-treaded (synchronized) medium speed.

What is the "super" keyword used for?

The "super" class is used when referring to an immediate parent class object. It is used to call superclass methods, and to access the superclass constructor.

Describe the JDK, JRE, and the JVM

The Java Virtual Machine reads the compiled code and translate it for whatever operating system it's on. The Java Runtime Environment contains the JVM and the libraries used by the code. The Java Development Kit contains the JRE and by extension the JVM as well as a host of tools that the developer needs. It's what the coders use.

Define Inheritance and provide advantages to using it

The ability of an entity acquiring some or all the data and behaviors of another entity. The child inherits all non-private classes from the parent. Saves time and effort and increases code reusability.

Is the @FunctionalInterface annotation required to denote a functional interface?

The annotation is optional, it's used to ENSURE an interface can't have more than one abstract method, but is not required.

What is sub-type polymorphism?

The process of substituting a parent for any child of theirs that inherits from it. Any testable item for the parent should also be testable for the child. If S inherits from T, S can be used in place of T safely.

Does the logic in a static block member of a class run before or after the class's constructor logic is called?

The static block is executed BEFORE the main method at the time of class loading.

What is the function of the .join() method?

This method is used to hold the execution of a currently running thread until the calling thread is dead (finished execution).

Describe the characteristics and application of the factory design pattern

Under creational pattern. Create objects without exposing the creation logic to the client and refer to a newly created object using a common interface. Factory method does this through use of a defined interface so that concrete subclasses utilize the methods.

When would you use an ArrayList over a Vector?

Use ArrayList since it's faster if you are in a Single threaded environment and use Vector if you need a thread-safe collection.

What is the purpose of the finally block?

Used in association with a "try" block. Always executed regardless of whether and exception is thrown. Often used to clean up code such as closing a connection.

What are functional interfaces?

a functional interface contains only one abstract method, an example of this would be Runnable, ActionListener, and Comparable interfaces. In Java 8 and up, lambda expressions can be used to represent the instance of a functional interface: new Thread(() → {System.out.println("Thread created");}).start();

What is the DRY principle?

"Don't Repeat Yourself" Don't write the same code repeatedly. You can fix this by placing the methods in place of all repeated codes and define the code inside the method.

What are short-circuit boolean operators?

&& (logical and) and || (logical or) don't have to evaluate the right hand side if it isn't necessary. Where as & and | operators when used as logical operators always evaluate both sides. There is only one case of short-circuiting each and they are: 1) false && ... if first result is false then no need to complete the rest of the case statement. 2) true || ... no need to check the remainder of the check because this resolves to false no matter what.

What are the differences between a lambda expression and a local anonymous class?

- Anonymous classes can be used in case of more than one abstract method while a lambda expression specifically used for functional interfaces. - We need to provide the function body only in lambda expression while in the case of an anonymous class, we need to write the redundant class definition. - We use this keyword to represent the current class in lambda expression while in the case of an anonymous class, this keyword can represent that particular anonymous class.

How can you create a thread in Java?

1. Create a class that implements the Runnable functional interface 2. implement the run method 3. pass an instance of your class to a Thread constructor 4. call the start() method on the thread. OR 1. Create a class that extends Thread 2. Implement the run() method 3. Instantiate your class 4. Call the start() method.

What are the types of constructors in Java?

1. Default constructor - this constructor is automatically created only if you do not make your own constructor. 2. NoArgs constructor - this is a constructor that does not have any arguments declared. 3. Args constructor -

What is the difference between a HashMap and a Hashtable?

1. HashMap is non synchronized. It is not thread-safe. Hashtable is synchronized and thread-safe. 2. HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value. 3. HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class. 4. HashMap is fast, and Hashtable is slow. 5. HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

What does the "final" keyword mean?

1. Methods declared as final cannot be overridden. 2. Classes declared as final cannot be inherited. Declaring a class as final implicitly declares all of its methods are final. (A class cannot be both abstract and final) 3. Final applied to variables creates named constraints. The value cannot be changed throughout the lifetime of the program.

What is the difference between a Queue and a Deque?

A queue is like a line at the grocery store, the first one in line gets processed first. A stack is where you make a pile and the last one on is the first one you pull off. A Queue is First In First Out, and a Stack is First In Last Out. A Deque has both the capabilities of a Stack and a Queue together. You can put on the back or front and you can take from the front or back.

What does the acronym SOLID stand for?

A set of 5 standards that guide how we design classes and objects to follow the pillars of OOP. S - Single Responsibility Principle O - Open-closed Principle L - Liskov Substitution Principle I - Interface Segregation Principle D - Dependency Inversion Principle

What is a constructor?

A special type of method used to instantiate an object of a class. A constructor is called with the "new" keyword and may optionally include a parameter list. Typically are public access so they can be instantiated from anywhere. They must have the same name as the class. ex - public MyClass();

Why do abstract classes have constructors?

Abstract classes are inheritable, so the constructor properties will also be inherited, if there is no constructor the compiler will automatically include one. When concrete sub-classes are instantiated there's an implicit call to its super class with super().

What are access modifiers?

Access modifiers are keywords which define the ability of other code to access the given entity. Modifiers can be placed on classes, interfaces, enums, and class members. public, protected, default, private

When would you use an ArrayList over a LinkedList?

An ArrayList should be used over a LinkedList when you need to access specific elements inside it (random access). A LinkedList should be used over an ArrayList when you need to add or remove an element in the middle of the list.

What is the difference between a for loop and an enhanced for loop?

An enhanced for loop will iterate each element in a sequence where in a for loop you can change the order it goes through.

Define Abstraction and provide advantages to using it

Hides underlying complexities and exposes a simplified interface. The main advantage is reducing the complexity of the design of your program, and increases reusability of code (because of interfaces)

What is Java?

High-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible

Describe the Liskov Substitution Principle

If there was a property of objects of T, and S is a subtype of T, then S has the same properties as T. Every subclass or derived class should be substitutable for its parent or superclass.

What is reflection?

In Java, reflection allows an executing program to examine or "introspect" upon itself and manipulate internal properties of the program.

What are some different inheritance strategies?

Inheritance strategies would include implementing and extending. A child class extending a parent class. A class implementing an interface.

What is a functional interface?

Interfaces that have only one abstract method. This method is what lambdas are implementing when they are declared - the parameter types and return types of the lambda must match the functional interface method declaration.

What is string interning?

It's the process of storing only one copy of each distinct String values. String immutability helps make this possible. It is the method of placing a string in the string pool if it doesn't exist there yet, otherwise it refers to another string obj. from the string pool having the same value. It returns a string from the pool if the pool already contains a string equal to the String object. - this determination is made by using the String.equals(Object) method. If the string is not already existing, the String obj. is added to the pool and a ref. to this String obj. is returned.

Describe the core interface/class hierarchy of the Java Collections API

Iterable is the parent interface, which is extended by Collection is extended by List, Queue and Set interfaces List interface is implemented by ArrayList, LinkedList, Vector Classes (which is extended by Stack Class) Queue is implemented by PriorityQueue Class and is extended by the Deque interface - Deque is implemented by ArrayDeque and LinkedList classes. Set is implemented by HashSet and LinkedHashSet classes and extended by the SortedSet interface SortedSet interface is implemented by TreeSet class.

Is multiple inheritance supported in Java?

Java doesn't allow multiple inheritance and how we can use interfaces instead of classes to achieve the same purpose.

Why is the main method declared static in Java?

Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined. Without having declared main method static , your program will successfully compile but won't execute and report error at run time.

What is a lambda expression?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method. Expressions are limited. They have to immediately return a value, and they cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces.

Are lambda expressions replacements to local anonymous classes?

Lambda expressions are very powerful and can replace many usages of anonymous class but not all. It can only replace the anonymous class when the former is used to implement a single method, if your anonymous class is implementing more than one interface, Lambdas cannot help.

What are the characteristics of a Stack?

Last in, First Out. Push adds an element to the collection Pop removes the most recently added element that was not yet removed. Each time an element is added, it goes to the top of the stack. The only element that can be removed is the element at the top of the stack, like a pile of real objects.

What is the difference between a List and a Set?

List maintains insertion order, Set doesnt. List allows duplicates, Set doesnt. List allows nulls whereas Set only allows one. List elements are accessed by position, Set doesnt. List implementations: ArrayList, LinkedList, Vector Stack. Set implementations: HashSet, LinkedHashSet. Set has similar features to a Math set List interface: public abstract interface List extends Collection Set interface: public interface Set extends Collection

What is the difference between the .run() and .start() methods?

Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread. While if you call run() method directly no new Thread is created and the code inside run() will execute on the current Thread.

What are marker interfaces?

Marker interfaces are interfaces that do not contain methods, fields, and constants. AKA tag interfaces. they deliver run-time info about an object. Examples: Serializable, Clonable, & Remote

In what way does Java employ polymorphism?

Method overloading- the practice of implementing methods with the same name but with different parameter lists. This allows us to provide similar implementations depending on parameters. Method overriding- modifying a method that a child class inherits from their parent. Implementing the method with the exact same signature in the child class but writing a different implementations.

What are some non-access modifying keywords used in Java?

Static, abstract, final, synchronized... static - denotes "class" scope, member resides on the class itself, not object instances final - when applied to a variable, class, or method: means the variable cannot be re-assigned, or a class cannot be extended, or a method cannot be overridden abstract - when applied to a class, means cannot be instantiated directly (instead inherited)

What is the "this" keyword used for?

The "this" keyword is used to represent the methods and attributes of the current instance of the class.

What is the difference between the == operator and .equals() method?

The == operator for reference comparison and .equals() method for content comparison.

What is a Map? Are they considered to be a part of the Java Collection API?

Used to identify a value by a key, and each entry in a map is a key-value pair. It does not implement the Collection interface, but it is considered to be part of the Collections framework. Because it does not implement Iterable, it cannot be iterated over directly. Instead, one must either: - use the entrySet() method to iterate over the set of Map.Entry - use the keySet() method to iterate over the set of keys. - use the values() method to return a Collection of values which can then be iterated over.

What is a thread in Java?

We can think of a thread as a "path of execution", but they can access the same objects in memory. Every thread that is created in a program is given its own call stack, where it stores local variables references. However, all threads share the same heap, where the objects live in memory.

What are imports?

We import packages into our Java program to use the methods and classes defined in those packages.

In what way does Java employ abstraction?

abstraction is achieved by using the abstract keyword for classes and interfaces


Set pelajaran terkait

Civics (History and Government) Questions for the Naturalization Test URDU AND ENGLISH

View Set

substance abuse counseling test 3

View Set

C724 (Information Systems Management) - (EDITED)

View Set

CRC3 chapter 10 Rollovers between and distributions from qualified plans and IRAs

View Set

Nutrition Chapter 1, NUTRITION CHAPTER 2, NUTRITION CHAPTER 3, Nutrition chapter 4, Diet and Nutrition Ch.7, Diet and Nutrition Ch. 8, Diet and Nutrition Ch 9, Diet and Nutrition Ch. 10, Diet and Nutrition Ch 11, Diet and Nutrition Ch. 12, Diet and N...

View Set