Java EE

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What is method reference in Java 8? <1>

- Refer to a method by its name without actually invoking it. Used with lambda expressions. - Also called double colon operator - Example: - Compare: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); - with lambda numbers.stream() .map(i -> String.valueOf(i)) // lambda expression .forEach(i -> System.out.println(i)); // lambda expression - with method reference numbers.stream() .map(String::valueOf) // reference to static method .forEach(System.out::println); // reference to instance method

Why string is immutable in Java? <3>

- Security: parameters are typically represented as String in network connections, database connection urls, usernames/password etc. We don't want them to get changed. - Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. - Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test, and b="test") and thus you need only one string object (because of string pool, will point to the same object)

Java Accessibilities? <4> What is the scope for each one of them? <4> Rank from the most visible to least visible?

- public: accessible from anywhere - protected: accessible within the same class, subclass and same package - default: accessible within the same package - private: accessible only within the same class - Note that a subclass can access the protected members of its superclass, even if it is in a different package, as long as it extends the superclass.

How to start garbage collection using command line? <1>

- since Java 1.7, jcmd GC.run

Differences between Collection & Collections <2> Differences between Array & Arrays <2>

Collection --> root interface basic behaviors of all the collections objects, like CRUD Collections --> is a util classes contains only static function for working with collections. A class that has methods such as sorting, searching and filtering on collections, and as a framework includes List, Set, Queue and Map Array --> A data structure that stores fixed-size sequential collection of elements of the same type. Arrays --> is a util class that provides static methods for working with array. A class that have methods like sorting, searching and copying arrays.

How to use comparable?

Image

How to use comparator shorthand?

Image

Java ArrayList sorting: Let us say you have list of students(ArrayList), you need to sort the students by their scores highest to lowest and if the score is same you need to sort by their name in alphabetical order

Image

Java 8 new features <5>

1. Lambda expressions: A concise way to represent anonymous functions. 2. Stream API: A set of methods to process collections of data in a declarative way. 3. Default methods: Methods that can be added to an interface without breaking existing implementations. 4. Functional interfaces: Interfaces with only one abstract method, used as types for lambda expressions. 5. Method references: A shorthand syntax for creating lambda expressions that call existing methods. Math.abs() --> Math::abs ContainingClass::staticMethodName ContainingObject::instanceMethodName ContainingType::methodName ClassName::New

What are the basic structure of a JVM <2> Explain what happens when you start a Java Application <8>

the basic components of the JVM: - Class Loader: The class loader is responsible for loading Java class files into memory. It loads the necessary classes when they are first used by the program. - Runtime Data Area: The runtime data area is a memory area that is used by the JVM to store data during program execution. It is divided into several sections such as the Method Area, Heap, Stack, and PC Registers when you start a Java application, the following happens: 1. The operating system loads the JVM (Java Virtual Machine) into memory. 2. The JVM reads the bytecode of the application from the .class files that are stored on the file system. 3. The JVM starts the class loader, which loads the application classes into memory. The class loader also verifies that the bytecode is valid and conforms to the Java language specification. 4. Once the classes are loaded and verified, the JVM allocates memory for the application's objects and arrays on the heap. 5. The JVM creates a new thread of execution for the application's main method, which is the entry point for the application. 6. The execution engine reads the bytecode instructions and interprets them into machine code that can be executed by the processor. If the same instructions are executed multiple times, the execution engine may also use the JIT (Just-In-Time) compiler to optimize the code for better performance. 7. As the application runs, the JVM manages the memory allocation and deallocation, garbage collection, and other aspects of program execution. 8. Finally, when the application completes, the JVM terminates, and any memory used by the application is released.

Describe the deserialization result of public, static, transient, volatile, static transient

public --> can be serialized and deserialized static --> cannot be serialized and deserialized to null transient --> will not be serialized because it is not a persistent state, value will be lost and deserialize will restore to default value or empty string. volatile --> will be serialized and deserialized, visible to all threads, cached to main memory static transient --> cannot be serialized and deserialized to empty string

What is an example of static method? <1> What can we say when we need to use a static method? <1> What can we say when we need to use a non-static method? <1> What is a static member? <1> What is special about static member? <3> What can you say about non-static methods? <1>

- A "Static" method DOES NOT require instantiating an object to access it. Examples : Main and MATH methods - A "Non Static" method requires instantiating an object to access it. - Examples of static members include static variables and static methods. - Static members are shared among all instances of a class, and there is only one copy of them in memory. - Static members can be accessed using the class name, without creating an instance of the class. - A static member can exist before the instantiation of the class - Non-static members are specific to each instance of a class.

What is JVM memory leak? <1> How to detect JVM memory leak? <3>

- A JVM memory leak is a scenario that occurs when objects are no longer being used by the application, but the Garbage Collector is unable to remove them from working memory -- because they are still being referenced. - You can use a JVM profiler to monitor a running JVM, by tracking the objects and the performance of each thread, method etc. - You can also create a Heap Dump - a snapshot of all the objects that are in memory in the JVM at a certain moment, and then use a Heap Dump Analyzer to analyze the JVM status - JDK contains some of certain profiler or dump analyzers, like jvisualvm or jmap, jcmd...

Explain final keyword? <3>

- A final class cannot be inherited - A final method cannot be overridden - A final object's reference cannot be changed

What is a functional interface? <1> How many default methods can functional interface have? <1>

- A functional interface is an interface that contains only one abstract method. - From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. - A functional interface can have any number of default methods

What is thread pool? <1> Different types of thread pool? <3>

- A thread pool is a collection of threads that can be used to execute tasks concurrently - Fixed Thread Pool: This type of thread pool has a fixed number of threads that are created when the pool is initialized. Once all threads are occupied, any new tasks are put into a queue until a thread becomes available. This is useful when the number of tasks is known in advance. - Cached Thread Pool: This type of thread pool creates new threads as needed and reuses existing threads when they become available. If a thread is not used for a certain amount of time, it is terminated and removed from the pool. This is useful when the number of tasks is not known in advance. - Scheduled Thread Pool: This type of thread pool is used for executing tasks at a specific time or at fixed intervals. It has a fixed number of threads and a queue for holding tasks. Tasks are executed at a specified time or at a fixed interval.

How is ArrayList implemented? <1> How is LinkedList implemented? <1> Advantages and Disadvantages of ArrayList? <2> Advantages and Disadvantages of LinkedList? <2>

- ArrayList is implemented as a dynamic array, meaning that it is essentially a resizable array of objects. - LinkedList, on the other hand, is implemented as a doubly linked list, meaning that each element in the list contains a reference to the previous and next elements in the list. - When elements are added or removed from an ArrayList, it may need to resize the internal array to accommodate the new size. This can be expensive, especially if the ArrayList is large, because it requires copying all the elements to a new array. - However, once the internal array is resized, accessing elements in an ArrayList is very fast because elements are stored in contiguous memory locations. - When elements are added or removed from a LinkedList, the references to neighboring elements are updated, but no resizing is necessary. - Accessing elements in a LinkedList is slower than in an ArrayList because the elements are not stored in contiguous memory locations, but rather must be traversed through the linked references.

How does BlockingQueue work? <1> Explain the producer and consumer interaction <1>

- Blocking queues support this pattern by providing a way for producers to add items to the queue and consumers to remove them. - In this pattern, a producer creates data and puts it into a shared buffer or queue. A consumer then takes data from the queue and processes it. The queue is used as a buffer between the producer and consumer threads. The BlockingQueue simplifies the implementation of producer-consumer designs with any number of producers and consumers.

What are Comparable and Comparator in Java? <1> In what order do we need to use Comparable? <1> In what order do we need to use Comparator? <1> What method do we override for each one of them? <2> What method do we use to compare objects? <1>

- Both classes are interfaces, designed for sorting - Purpose: The Comparable interface is used to define the natural order of an object, whereas the Comparator interface is used to define a custom order(for objects) for sorting objects. - Method: The Comparable interface defines "compareTo()", . The Comparator interface defines "compare()" - Default is from smallest to the largest (Collection.sort)

Differences between checked and unchecked exception? <2> When will you expect to see a checked exception? <1> When will you expect to see a unchecked exception? <1>

- Check exception is also called compile time exception. It has to be handled or it will be a compile error - Unchecked exception is also called a runtime exception. You may or may not handle the exception during compile time. - Checked exceptions are typically related to external factors (things that we cannot control such as file read and write) - Unchecked exceptions are usually related to programming errors.

How to create an immutable class in Java? <2>

- Class should be final - Fields are private and provide only getters (no setters)

Given Collections.sort(), how to sort in descending order? <3>

- Collections.sort(numbers, Collections.reverseOrder()); - Collections.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); - Collections.sort(numbers, (o1, o2) -> Integer.compare(o2, o1));

What is the steps to run a Java Program? <3>

- Create .java files which contain the source code - Compile all .java files into .class files - Start the java program by executing the class (or jar)

What is SOLID principles for code review? <5>

- Five design pattern principles intended to make OOD more understandable, flexible and maintainable. - Single-responsibility principle: every class should have only one responsibility - Open-closed principle: Software entities should be open for extension but closed for modification - Liskov substitution principle: Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application. - Interface segregation principle: Clients should not be forced to depend upon interfaces that they do not use. - Dependency Inversion: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

What is garbage collection in Java? <1> List (4) some garbage collection algorithm you know.

- GC is an automatic process of freeing up memory of object that is no longer referenced by program. - Serial Garbage Collector: Simple and single threaded algorithm. It is good for small applications. Have low CPU overhead. Will have long pauses. - Parallel Garbage Collector: This algo uses multi-thread. Reduce pause time and allow high throughput. But have high CPU overhead. - CMS Garbage Collector: CMS (Concurrent Mark and Sweep) algorithm is designed to reduce pause times and is suitable for applications that require low-latency. Multi-thread but high CPU overhead. - G1 Garbage Collector: G1 (Garbage-First) algo is a low pause, server-style collector that is suitable for large memory applications. It divides the heap into regions and performs garbage collection on individual regions, which reduces the pause time. Good for low-latency, large amount of memory and long-lived objects. But high CPU overhead and may cause fragmentation.

Difference between HashMap and Hashtable? <2>

- HashMap allows one null key and multiple null values. Not thread safe, better performance. - Hashtable does not allow null key or null value. Thread safe.

Internal process of HashMap. - What does HashMap use to store data? <1> - How does put method work? <2> - What do we need to do for storing objects as key? <1> - How HashMap resizes? <1> - What is the default capacity and load factor? <2>

- HashMap uses an array of linkedList buckets and Red Black Tree. - When we put an object, it will use key's hashCode() to calculate the index of the bucket for insertion. - If bucket not empty, it will use key's equals() to determine if the object should be appended, or replace existing entry - For storing objects, we will need to rewrite the hashCode() and equals() method because we are comparing objects. - Resizing: double the capacity when we have more than (initial capacity * load factor) number of objects in the hashMap. - Initial capacity is 16, default load factor is 0.75

How to start a Thread? <2> What is Thread.sleep? About lock? <2> What is Thread.wait? How to wake it up? About lock? <3> What is Thread.join? Why should we use it? <2> What is Thread.yield? <1>

- Implement a Runnable interface or extend Thread Class - We will define a Thread, the use thread.start() to start the thread. - Thread.sleep(long millis) - This method puts the currently executing thread to sleep for the specified number of milliseconds. It doesn't release any locks or monitors held by the thread. - Thread.wait(long millis) - This method puts the currently executing thread to sleep until another thread calls the notify() or notifyAll() method on the same object. If a timeout value is specified, the thread will wait for the specified number of milliseconds or until it is notified by another thread, whichever comes first. This method also releases any locks or monitors held by the thread. - Thread.join() - This method waits for the thread on which it is called to terminate. It can be useful for coordinating the execution of multiple threads. When a thread calls join() on another thread, it will block until the other thread completes its execution. - Thread.yield() - This method tells the thread scheduler to give up the current thread's CPU time so that other threads can run.

When will ConcurrentModificationException happen? <1>

- In multithreading environment, if one thread is iterating over a collection, while another thread is modifying the same collection, it will throw ConcurrentModificationException.

What can interface have? <1> What is new for interface since Java 8? <2> What can abstract class have? <2> For what purpose when we need to use interface? <1> For what purpose when we need to use abstract class? <1> How many for extension, how many for implementation? <1>

- Interface can only have public abstract methods. - From Java 8, interface can have default and static methods too, and we have functional interface. - Abstract class can have abstract and non-abstract methods. - Abstract class is for abstracting the root of an object, but interface is abstracting an behavior - We can only extend one abstract class, but can implement many interfaces

What goes into JVM Stack? <2> What goes into JVM Heap? <1> How does Heap free memory? <1>

- JVM Stack will create a stack frame for every method invocation in each thread. It also contains local variables, operators, dynamic linking, and other method results. - Heap is designed to store objects. We will need garbage collection to recycle unused objects to free some memory.

What is ForkJoin? <1> Example of using it? <1>

- Java Fork/Join is a framework that is used to implement parallel processing in Java. It was introduced in Java 7 as part of the Java Concurrency API - The Fork/Join framework works by breaking down a large task into smaller sub-tasks, which can be executed in parallel on multiple threads.

Thread life cycle <5>

- New: When a thread is created, it is in the New state. In this state, the thread has not yet started executing, and its start() method has not yet been called. - Runnable (Ready): When the start() method is called, the thread enters the Runnable state. In this state, the thread is eligible to run, but it may or may not be executing, depending on the CPU availability. - Running: When the thread gets the CPU time to execute, it enters the Running state. In this state, the thread is actively executing its code. - Blocked/Waiting: We can use wait or sleep method to put thread into Waiting status, and then we use notify or notifyAll method to turn thread to Ready state - Terminated: A thread enters the Terminated state when its run() method has completed, or when it is stopped using the stop() method (which is not recommended), or when an unhandled exception is thrown during its execution.

What is Serialization? <1> Why do we need Serialization? <2> How does Java implement Serialization? <2> Serializable? - What kind of interface? <1> - Input and Output data type? <2> Externalizable? - Benefit of using Externalizable? <1>

- Serialization is the process of converting an object into a stream of bytes - It is useful to transfer data over a network, stored in a file. It enables us to send data between different programming language and platforms. Also, it enable us to store data in a compact and efficient way by reducing the space needed. - Java provides two interfaces for controlling the serialization process: Serializable and Externalizable - Serializable: Serializable is a marker interface that indicates that a class can be serialized. If a class implements Serializable, its object state can be written to an ObjectOutputStream and restored from an ObjectInputStream. Serializable uses a default serialization mechanism provided by Java. - Externalizable: Externalizable is an interface that provides more fine-grained control over the serialization process.

How to define a Java Singleton in different ways? <2>

- Singleton is a design pattern that ensures that only one instance of a class can be created and that it can be accessed globally - Eager Initialization: In this approach, the instance of the Singleton is created at the time of class loading. - Lazy Initialization: In this approach, the instance of the Singleton is created only when it is needed for the first time. (Check if null)

What's the difference between Java Singleton and Spring Singleton? <2>

- Singleton is a design pattern to describe that if in 1 scope, for 1 blue print, only 1 object can be created, then we call this blue print a Singleton. - Java singleton means in 1 JVM, 1 class can only have 1 object - Spring singleton means in 1 Spring container, 1 Spring Bean can only have 1 object.

What is Stream API? <1> What are some common methods? <4> What is one characteristic about Stream API? <1>

- Stream API contains classes for processing sequences of elements - Perform operations such as filtering, mapping, sorting, and reducing on the data elements. - One of the main benefits of the Stream API is that it encourages functional programming practices, which can lead to more concise and expressive code.

Differences between String, StringBuilder, StringBuffer

- String is immutable --> costly to use "+" to append - We can StringBuilder to connect words - Use StringBuffer for thread-safe

Explain the keyword "volatile" in Java <2>

- That variable's value may be modified by multiple threads. - volatile variable will be visible to all threads, rather than being cached

What is the structure of ConCurrentHashMap? <1> How does it achieve thread-safe? <2>

- The ConcurrentHashMap class is implemented as an array of buckets, where each bucket is a linked list of key-value pairs. - ConcurrentHashMap achieves thread-safety and concurrency by using a technique called "lock striping". 1. This technique involves dividing the map into a fixed number of segments, each with its own lock. 2. When a thread wants to access a particular segment, it only needs to acquire the lock for that segment, rather than acquiring a single global lock for the entire map. This reduces contention for the lock and allows multiple threads to access different segments of the map concurrently.

What is ReentrantLock? <2> How is it designed? <1>

- The ReentrantLock class implements the Lock interface and provides synchronization to methods while accessing shared resources. - When the thread first enters into lock, a hold count is set to one. Before unlocking the thread can re-enter into lock again and every time hold count is incremented by one. - For every unlock request, hold count is decremented by one and when hold count is 0, the resource is unlocked. It's more flexible compared to synchronized keyword way.

Can you tell me about the difference between Unit Testing and TDD

- Unit Testing tests each function individually and we need to test the smallest testable part - Software Dev approach in which developers write tests before writing code

How to stop a thread? <1>

- Use a boolean flag: You can use a boolean flag to signal to the thread that it should stop. The thread can check this flag periodically and exit its run() method if the flag is set to true. Here is an example: public class MyThread extends Thread { private volatile boolean running = true; public void stopRunning() { running = false; } public void run() { while (running) { // do some work } } }

How to make a field not serializable? <2>

- Use transient keyword. - Make it static

Two ways to handle an exception <2>

- Use try-catch-finally block - Use throw clause in the method declaration

How to return data from thread? <1> What is the data type of the returned data? <1>

- We can use Callable interface to create a thread which can return data in its call() method. - Data returned from callable thread will be a future.

How to create parallel stream? <1> What is the internal structure? <1>

- We can use parallelStream() to create parallel stream which internally uses ForkJoin for better performance.

What is garbage collection in Java? <1> Why do we need garbage collection? <1> How to use it? <1>

- What? - Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. - Why? - It makes Java memory-efficient because the garbage collector removes the unreferenced objects from heap memory. - It is automatically done by the garbage collector (a part of JVM), so we don't need extra effort. - It frees the programmer from manually dealing with memory allocation and deallocation. How? - To use garbage collection in Java, you don't need to do anything special. It is automatically done by the garbage collector (a part of JVM). However, you can tune garbage collection in Java to improve performance. For example, you can change the heap size or choose a different garbage collector algorithm

Choose the most appropriate data structure for each problem type: 1: A hierarchical file system model 2: An undo / redo history in an app 3: Orders to be processed in-order and sequentially 4: Boolean option flags in a memory constrained device

1: Tree: each node represents a directory or file and its child nodes represent its contents. 2: Stack: undo/redo operations can be performed by popping or pushing items from the stack. 3: Queue: each order is added to the back of the queue and processed in the order they were added (FIFO - first in, first out). 4: Bit array, where each bit represents a single option flag. This is more memory efficient than using separate boolean variables for each flag.

Why we need default method in interface? <1>

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided by ALL THE CLASSES implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

What is the @Component and @Scope annotation <2> Types of scopes in Spring <5>

The @Component annotation is a core annotation in the Spring Framework that is used to declare a class as a Spring-managed bean. When you annotate a class with @Component, Spring will automatically detect and instantiate the bean when the application starts up, making it available for injection into other beans. The @Scope annotation is used in conjunction with @Component to specify the scope of the Spring-managed bean. The scope determines how many instances of the bean should be created and how long they should be kept in memory. There are several standard scopes in Spring, including: singleton: Only one instance of the bean is created and shared across the entire application. prototype: A new instance of the bean is created each time it is requested. request: A new instance of the bean is created for each HTTP request in a web application. session: A new instance of the bean is created for each user session in a web application. application: A single instance of the bean is created for the entire web application.

What is the Date API in Java? <1> How do you create a Date object in Java? <1>

The Date API in Java provides a set of classes that allow developers to work with dates, times, and time zones. It includes classes such as Date, Calendar, SimpleDateFormat, and TimeZone... Date currentDate = new Date(); This will create a new Date object with the current date and time.


संबंधित स्टडी सेट्स

Clyde Barrow (worksheet, exam 2)

View Set

Med Concepts - Medication and I.V. Administration - ML6

View Set

K12/AmHis/Unit 01/Lesson 05/Anasazi - part 2

View Set

Texas Principles of Real Estate - Part 2 - Chapter 4 Quiz

View Set

Microeconomics Quiz (Ch. 11 and 13)

View Set

Chapter 24: Newborn Nutrition and Feeding Perry: Maternal Child Nursing Care, 6th Edition, Chapter 23: Nursing Care of the Newborn and Family Perry: Maternal Child Nursing Care, 6th Edition, Chapter 22: Physiologic and Behavioral Adaptations of the N...

View Set

Econ 110: Spring; Al Hamdi (Exam 2 HWs)

View Set

Joey's handy dandy econ final study guide part 3, Ch. 16-17

View Set

Vector Practice--Dot Product and Addition

View Set