Java Core And Advanced Java

 

1. What is the use of garbage collection in Java?
The use of garbage collection in Java is to recognize and remove objects that are no more required by a program and are unnecessary consuming the program resources that could be freed and reused by other objects. An object in Java is subject to garbage collection when it turns inaccessible to the Java program in which it is initiated.

2. What are Lambda Expressions?
Lambda Expressions, often called lambdas, are a new feature introduced with Java 8. They provide an easier way to work with interfaces that have only got one method, and they are often used in places where the programmer use anonymous classes.

3.What do you understand by thread in Java?
A thread is a single sequential flow of control within a process where each process can contain two or more "threads". In Java, a thread is created and coordinated by the java.lang.Thread class.

4.Write a Program to Swap Two Numbers.
import java.util.*;
class SwapDemo {
static void swapValuesUsingThirdVariable(int m, int n)
{
int temp = m;
m = n;
n = temp;
System.out.println("Value of m is " + m
+ " and Value of n is " + n);
}
public static void main(String[] args)
{
// Random integer values
int m = 9, n = 5;
swapValuesUsingThirdVariable(m, n);
}
}

5. When and how a deadlock occurs in any program?
A deadlock occurs when two or more threads are blocked on locks and every thread that's blocked is holding a lock that another block thread wants. For example: thread 1 is holding lock 1 and waiting to acquire lock 2 but thread 2 is holding lock 2 and waiting to acquire lock 1.

 It creates a situation where all the threads holding the locks are blocked therefore it will never release the locks they're holding and so none of the waiting threads will actually ever run.

6. Why developers use BufferedReader to read any file in Java?
A BufferedReader reads text from the input stream and buffers the characters into a character array. Reading chunks of data from a stream (unlike a file) is more efficient than reading just a few characters at a time.

Therefore we can conclude that BufferReader is more streamlined and faster. Also, we can specify the size of the buffer, but the default is 8k, and that is also sufficient for most purposes.

7. What do you understand by synchronization? How does it benefits in multithreading?
With respect to multithreading, synchronization is the process of controlling the access of multiple threads to shared resources. In Java, we can synchronize methods and statements. Whenever we synchronize any method in Java program, it allows only one thread to execute at one time.

Therefore, if a thread is using a synchronize method, all the other threads that want to execute the same method or any other synchronized method initiated in the same class will suspend until the execution of the running thread is completed.

8. What is the role of RequestDispatcher Interface in Servlet?
The RequestDispacher interface in Servlet is used to dispatch requests to other resources such as HTML, Servlet or JSP. However, it can also be used to incorporate the content of another resource.

9. Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

10. What if the main method is declared as private?
The program compiles properly but at runtime, it will give a "Main method not public." Message.

11. Do I need to import Java.lang package any time? Why?
No. It is by default loaded internally by the JVM.

12. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

13. Explain the throw and throws keywords in Java?
The throw keyword can be specified within any block of code. It can be used to explicitly throw an exception (both in-built as well as custom exception). It is followed by an Exception object.

The throws keyword is specified in a method declaration. It indicates that the method is capable of throwing an exception but does not handle it and that the code that invokes the method needs to handle the exception. It is followed by the exception class name.

14. What will be the output of the following code? Explain?
File file = new File("C:/test");
file.mkdir(); The code above creates a File object corresponding to the C:/test path and then invokes the mkdir() method on this File object. This method creates a directory corresponding to the specified path. So, once the code above executes, a directory called “test” will be created in c:/

15. What is an immutable class? How to create an immutable class?
An immutable class is a class that once created, contents cannot be changed. Immutable objects are objects whose state cannot be changed once constructed. - Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.Immutable objects are automatically thread-safe since the state of the immutable objects can not be changed once they are created -All wrapper classes in Java. lang are immutable

16. List some ORM frameworks.
Following are the various frameworks that function on ORM mechanism: -
  • Hibernate
  • TopLink
  • ORMLite
  • iBATIS
  • JPOX

17. Explain the concept of CascadeType in JPA and provide examples of when to use it.
CascadeType in JPA defines the propagation behavior of entity state transitions to associated entities. It allows you to specify what actions should be cascaded from one entity to its associated entities when an operation (such as persist, remove, or merge) is performed on the owning entity

18. What are the benefits of using second-level caching in JPA?
Second-level caching in JPA improves performance by reducing the number of database queries and increasing data retrieval speed. It stores entities or query results in a cache shared by all entity managers within an application, allowing for quicker access to frequently accessed data. This can lead to significant performance improvements, especially in applications with high read-heavy workloads.

19. How does JPA handle concurrency control, and what are the different locking strategies available?
JPA provides support for concurrency control through locking mechanisms. Different locking strategies include:
  • Optimistic locking: This strategy allows multiple transactions to read the same data simultaneously but prevents conflicting updates by checking for concurrent modifications during transaction commit.
  • Pessimistic locking: This strategy locks the database rows associated with entities during the transaction, preventing other transactions from accessing or modifying the same data until the lock is released.
  • Lock modes: JPA provides different lock modes, such as READ, WRITE, and OPTIMISTIC, which allow developers to control the granularity and behavior of locks.

20. Discuss the differences between FetchType.LAZY and FetchType.EAGER, and when would you use each?
FetchType.LAZY: With this setting, related entities are loaded lazily, meaning they are fetched from the database only when accessed for the first time. Use this setting when you want to minimize database access and improve performance, especially for large object graphs.

FetchType.EAGER: With this setting, related entities are loaded eagerly along with the owning entity. Use this setting when you frequently access the related entities together with the owning entity and when the related entities are small in size to avoid N+1 query issues.

21. What are the differences between MyISAM and InnoDB storage engines in MySQL?
MyISAM: MyISAM is an older storage engine in MySQL. It supports table-level locking, which can lead to performance issues in high-concurrency environments. MyISAM does not support transactions or foreign keys, but it is known for its simplicity and fast read operations, making it suitable for read-heavy workloads such as data warehousing or reporting.

InnoDB: InnoDB is a more modern storage engine that supports row-level locking and provides features like transactions, foreign keys, and crash recovery. I t offers better performance for write-heavy workloads and is the default storage engine for MySQL starting from version 5.5. InnoDB is well-suited for OLTP (Online Transaction Processing) applications where data integrity and concurrency control are critical.

22. Explain the purpose and usage of MySQL's EXPLAIN statement.
The EXPLAIN statement is used to analyze MySQL queries and understand how the MySQL optimizer executes them. By prefixing a SELECT statement with EXPLAIN, MySQL provides information about the query execution plan, including the tables involved, the order in which they are accessed, the indexes used, and the type of join operations performed.

23. What is database normalization, and why is it important?
Database normalization is the process of organizing data in a database to reduce redundancy and improve data integrity.
  • The normalization process involves breaking down large tables into smaller, related tables and defining relationships between them using foreign keys.
  • Normalization helps in minimizing data duplication, which reduces storage space and ensures consistency by avoiding update anomalies such as insertion, deletion, and modification anomalies.
  • There are different levels of normalization, from First Normal Form (1NF) to Boyce-Codd Normal Form (BCNF) and beyond, each addressing specific normalization requirements.

24. How does MySQL handle transactions, and what are the properties of ACID?
Atomicity: Transactions are atomic, meaning they are either fully completed or fully rolled back if an error occurs, ensuring that the database remains in a c onsistent state.
Consistency: Transactions preserve the consistency of the database by transitioning it from one valid state to another.
Isolation: Transactions are isolated from each other, meaning changes made by one transaction are not visible to other transactions until the changes are committed.
Durability: Once a transaction is committed, its changes are durable and persistent, even in the event of a system failure.

25. Explain the purpose and usage of MySQL's stored procedures.
Stored procedures are precompiled SQL code blocks that are stored in the database and can be invoked by applications or other stored procedures.
  • They help improve performance by reducing the amount of data transferred between the database server and clients, as well as by reducing the overhead of parsing and compiling SQL statements repeatedly.

26. What are some built-in annotations in Java?
Java provides several built-in annotations in packages like java.langjava.lang.annotation, and java.lang.reflect. Some common built-in annotations include @Override@Deprecated@SuppressWarnings@FunctionalInterface, and @ SafeVarargs.

27. What is an annotation in Java?
 Annotations in Java provide metadata about the program that can be accessed at runtime or compile time. They do not directly affect the execution of the code but can be used by the compiler or other tools to generate code, perform validations, or control behavior.

28. How do you define a custom annotation in Java?
To define a custom annotation in Java, you use the @interface keyword followed by the annotation name. Here's an example:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation
{
String value() default "default value";
}

29. What is the purpose of the @Override annotation?
The @Override annotation in Java indicates that a method is overriding a method in its superclass. It helps catch errors at compile time if the annotated method doesn't actually override a method in the superclass.

30. What is the purpose of the @WebServlet annotation?
The @WebServlet annotation is used to define a servlet component in a web application and provides metadata for the servlet, including its URL mappings.

No comments:

Post a Comment