Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Friday, June 9, 2023

What is difference between HashMap and Hashtable in Java?

In Java, both HashMap and Hashtable are used to store and retrieve key-value pairs. However, there are some key differences between the two:


Synchronization: Hashtable is synchronized, which means it is thread-safe and multiple threads can access it concurrently without causing data inconsistencies. On the other hand, HashMap is not synchronized by default, and if you need synchronization, you can use Collections.synchronizedMap() to create a synchronized version of HashMap.


Null values: Hashtable does not allow null values for both keys and values. If you try to insert a null key or value, it will throw a NullPointerException. In contrast, HashMap allows null values and a single null key.


Performance: Since Hashtable is synchronized, it incurs the overhead of acquiring and releasing locks, making it slightly slower than HashMap. If you don't need thread-safety, using HashMap can result in better performance.


Iterator fail-fast behavior: Both HashMap and Hashtable provide fail-fast iterators, meaning if the underlying collection is modified structurally while iterating, an exception (ConcurrentModificationException) is thrown. However, the way they achieve this behavior is different. Hashtable uses a single lock for the whole table, while HashMap uses a fail-fast iterator on top of its internal data structure (bucket-array and linked list).


Inheritance: Hashtable is a subclass of Dictionary, whereas HashMap is a subclass of AbstractMap. The Dictionary class is obsolete, and it is recommended to use Map interfaces and their implementations (such as HashMap) instead.


In general, if you need thread-safety or you're working with legacy code that requires Dictionary or synchronized behavior, you can use Hashtable. If you don't need thread-safety and performance is a concern, HashMap is the preferred choice.

Saturday, May 27, 2023

Top 20 Spring Boot Interview Questions with Answers for Java Developers

Certainly! Here are 20 common Spring Boot interview questions along with their answers:


What is Spring Boot?

Spring Boot is an opinionated framework built on top of the Spring framework that simplifies the development of Java applications. It provides default configurations and conventions, reducing boilerplate code and enabling developers to quickly create production-ready applications.


What are the key features of Spring Boot?

Key features of Spring Boot include:

  • Auto-configuration
  • Embedded servers
  • Starter dependencies
  • Actuator
  • Production-ready metrics and monitoring
  • How does Spring Boot simplify the configuration of a Spring application?
  • Spring Boot uses convention over configuration. It provides default configurations based on classpath settings, annotations, and properties files. Developers can override these defaults by providing their own configurations.


What is the difference between Spring and Spring Boot?

Spring is a comprehensive framework that provides various modules for developing enterprise Java applications. Spring Boot is built on top of the Spring framework and focuses on simplifying the configuration and development of Spring applications.


What is the purpose of the @SpringBootApplication annotation?

The @SpringBootApplication annotation is used to indicate the main class of a Spring Boot application. It combines the @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations into a single annotation.


What is Spring Boot Starter?

A Spring Boot Starter is a dependency that includes a set of opinionated dependencies related to a specific feature or functionality. It simplifies dependency management and configuration for that specific feature.


What is the purpose of the application.properties (or application.yml) file in Spring Boot?

The application.properties or application.yml file is used to configure various settings of a Spring Boot application, such as server port, database connection details, logging configuration, etc.


What is the purpose of the Spring Boot Actuator?

Spring Boot Actuator provides production-ready features for monitoring and managing Spring Boot applications. It includes endpoints that expose useful information and metrics about the application, such as health checks, metrics, environment details, and more.


What is the difference between @RestController and @Controller?

The @RestController annotation is a specialized version of @Controller that combines @Controller and @ResponseBody. It is used to build RESTful web services, where the return values of methods are automatically serialized to JSON or XML.


Explain the concept of Spring Boot Auto-configuration.

Spring Boot Auto-configuration automatically configures the Spring application based on the dependencies and the classpath. It analyzes the project's dependencies and, if a specific library is found on the classpath, it automatically configures the necessary beans and settings.


What is the purpose of the @Autowired annotation?

The @Autowired annotation is used to automatically wire (inject) dependencies into a Spring bean. It can be applied to constructors, setter methods, or directly on fields.


What is the Spring Boot starter parent?

The Spring Boot starter parent is a special Maven POM that provides default configurations and dependency management for Spring Boot applications. It simplifies the project's Maven configuration by inheriting common settings.


How can you create a custom starter in Spring Boot?

To create a custom starter, you can follow these steps:


Create a Maven module with a specific naming convention (e.g., spring-boot-starter-{name}).

Define the necessary dependencies and configurations in the module.

Package the module as a JAR and distribute it




Difference between getPath(), getCanonicalPath() and getAbsolutePath() of File in Java - Example

In Java, the File class provides several methods for working with file paths. Here are the differences between getPath(), getCanonicalPath(), and getAbsolutePath():

 getPath(): 

The getPath() method returns the path of the file or directory as it was specified when the File object was created. It may be a relative path or an absolute path depending on how the File object was instantiated. 

If the file path contains symbolic links or relative path components, getPath() does not resolve them. 

Example:


File file = new File("mydir/example.txt");
String path = file.getPath();
System.out.println(path);

Output:


mydir/example.txt

getCanonicalPath(): The getCanonicalPath() method returns the canonicalized path of the file or directory. 

It resolves the file path by removing any symbolic links, resolving relative paths, and returning the absolute path.

 It returns a standardized path representation without any unnecessary components or redundant separators.


File file = new File("mydir/../mydir/example.txt");
String canonicalPath = file.getCanonicalPath();
System.out.println(canonicalPath);

Output:


/home/user/mydir/example.txt

getAbsolutePath(): The getAbsolutePath() method returns the absolute path of the file or directory. It provides the complete path from the root of the file system. 

If the File object was created with a relative path, getAbsolutePath() resolves it to an absolute path by prepending the current working directory. 

Example:


File file = new File("mydir/example.txt");
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);

Output:


/home/user/current-working-directory/mydir/example.txt

It's important to note that all three methods may throw IOException if the file or directory does not exist or if an I/O error occurs during path resolution.

In summary, getPath() returns the path as provided, getCanonicalPath() returns the standardized, resolved path, and getAbsolutePath() returns the absolute path by resolving relative paths against the current working directory.

Wednesday, May 24, 2023

How to converts Java Object to XML - JAXB Example

 To convert a Java object to XML using JAXB (Java Architecture for XML Binding), you need to follow these steps:


Step 1: Set up your project

Make sure you have the necessary dependencies for JAXB in your project. JAXB is included in Java SE starting from Java SE 6, so you don't need to download any additional JAR files.


Step 2: Annotate your Java class

Annotate your Java class with JAXB annotations to specify how it should be marshalled (converted) to XML. These annotations provide instructions to JAXB for XML mapping.


Here's an example of a Java class with JAXB annotations:



import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {
    private String firstName;
    private String lastName;
    private int age;

    public Employee() {
    }

    public Employee(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlElement
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @XmlElement
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

In this example, the class Employee is annotated with @XmlRootElement to specify the root element name in the XML. The @XmlElement annotation is used for each property that should be included in the XML. 

Step 3: Convert the Java object to XML To convert an instance of your Java class to XML, you can use the javax.xml.bind.JAXB class. Here's an example of how to convert an Employee object to XML:


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class ObjectToXmlExample {
    public static void main(String[] args) {
        Employee employee = new Employee("John", "Doe", 30);

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
            Marshaller marshaller = jaxbContext.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(employee, stringWriter);

            String xml = stringWriter.toString();
            System.out.println(xml);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create an instance of Employee, and then we create a JAXBContext using the JAXBContext.newInstance() method, passing the Employee.class as the argument. Then we create a Marshaller from the JAXBContext and set the Marshaller.JAXB_FORMATTED_OUTPUT property to true to generate formatted XML. 

Next, we create a StringWriter to capture the XML output, and finally, we call the marshaller.marshal() method, passing the employee object and the StringWriter to convert the object to XML. The XML is then printed to the console. That's it! You have successfully converted a Java object to XML using JAXB.

Saturday, May 20, 2023

How to enclose a list of values into single quotes for SQL query? Microsoft Excel Example

To enclose a list of values in single quotes for an SQL query, you can use Excel formulas to generate the desired format. Here's an example using Microsoft Excel:


Suppose you have a list of values in cells A1 to A5: "value1", "value2", "value3", "value4", and "value5".

In cell B1, you can enter the following formula to enclose each value in single quotes and separate them with commas:

="'" & A1 & "'" & ", "

Drag the formula down from B1 to B5 to apply it to the entire range. This will generate the values in the desired format: "'value1', 'value2', 'value3', 'value4', 'value5', ".

In cell C1, you can enter the following formula to concatenate the values from column B into a single cell:

=TEXTJOIN("", TRUE, B1:B5)

This formula will concatenate all the values from B1 to B5 without any delimiter, resulting in the following value: "'value1', 'value2', 'value3', 'value4', 'value5'".

You can then copy the value from cell C1 and use it in your SQL query as a list of enclosed values.

Note that these formulas assume you are using Excel's standard quotation marks (") for cell references. If your Excel version requires a different character for referencing cells, make sure to adjust the formulas accordingly.


Friday, May 19, 2023

How to Read Write Excel file in Java - POI Example

 To read and write Excel files in Java using the Apache POI library, you can follow these steps:

Add Apache POI dependencies: First, you need to include the Apache POI dependencies in your Java project. You can download the JAR files from the Apache POI website (poi.apache.org) or use a build tool like Maven or Gradle to manage the dependencies.

Create a new Java class and import the necessary classes:


java

Copy code

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;


Reading an Excel file:

To read data from an existing Excel file, you can use the following code:

try {

    FileInputStream file = new FileInputStream("path/to/excel/file.xlsx");


    // Create Workbook instance for the Excel file

    Workbook workbook = new XSSFWorkbook(file);


    // Get the first sheet from the workbook

    Sheet sheet = workbook.getSheetAt(0);


    // Iterate over rows in the sheet

    for (Row row : sheet) {

        // Iterate over cells in the row

        for (Cell cell : row) {

            // Get the cell value and print it

            String cellValue = cell.getStringCellValue();

            System.out.println(cellValue);

        }

    }


    // Close the file

    file.close();

} catch (Exception e) {

    e.printStackTrace();

}


Writing to an Excel file:

To create a new Excel file or modify an existing one, you can use the following code:

try {

    // Create a new Workbook

    Workbook workbook = new XSSFWorkbook();


    // Create a new sheet

    Sheet sheet = workbook.createSheet("Sheet1");


    // Create a new row and set values

    Row row = sheet.createRow(0);

    Cell cell = row.createCell(0);

    cell.setCellValue("Hello");


    // Write the workbook to a file

    FileOutputStream file = new FileOutputStream("path/to/excel/file.xlsx");

    workbook.write(file);


    // Close the file

    file.close();

} catch (Exception e) {

    e.printStackTrace();

}


Make sure to replace "path/to/excel/file.xlsx" with the actual path to your Excel file.


These examples demonstrate the basic reading and writing operations using Apache POI. You can further explore the API documentation to work with more advanced features such as formatting, formulas, and multiple sheets within an Excel file.






How to Increase Console Buffer Size in Eclipse IDE - Output and Debug Console Example

To increase the console buffer size in Eclipse IDE for the Output and Debug consoles, you can follow these steps:

  1. Open Eclipse IDE and go to the "Window" menu at the top.
  2. From the dropdown menu, select "Preferences." This will open the Eclipse Preferences window.
  3. In the Preferences window, navigate to "Run/Debug" and expand the section.
  4. Click on "Console" to view the console settings.
  5. In the Console settings, you will see options for "Standard Output and Error" and "Java Debug." These correspond to the Output and Debug consoles, respectively.
  6. To increase the buffer size for either console, select the console type (Standard Output and Error or Java Debug) and modify the "Console buffer size" field. You can enter a higher value to increase the buffer size. The unit for buffer size is characters.
  7. After setting the desired buffer size, click "Apply" or "OK" to save the changes.
  8. Restart Eclipse IDE for the changes to take effect.
  9. By increasing the console buffer size, you allow Eclipse to store more lines of output or debug information in the console before it starts to remove the older lines. This can be helpful when you want to review a larger amount of output or debug logs.


Note: Keep in mind that setting a very large buffer size can consume more memory, so it's advisable to find a balance between having a sufficient buffer size and not overloading your system resources.





Thursday, May 18, 2023

Top 30 Eclipse Keyboard Shortcuts for Java Programmers [UPDATED]

Here are 30 useful Eclipse keyboard shortcuts for Java programmers:


  1. Ctrl + Shift + R: Open a resource (file, class, or package) by name.
  2. Ctrl + Space: Activate content assist (code completion) for the current context.
  3. Ctrl + Shift + O: Organize imports to add or remove import statements automatically.
  4. Ctrl + Shift + F: Format the selected code or the entire file according to the configured code formatter.
  5. Ctrl + 1: Quick fix suggestions for resolving errors or applying code changes.
  6. Ctrl + / or Ctrl + Shift + /: Comment/uncomment the selected code or the current line.
  7. Ctrl + D: Delete the current line or the selected code.
  8. Ctrl + Shift + L: Show a list of all available keyboard shortcuts.
  9. F3: Go to the declaration of a class, method, or variable.
  10. Ctrl + Shift + G: Find references to the selected element.
  11. Ctrl + Shift + T: Open a type (class, interface, enum) by name.
  12. Ctrl + H: Open the Search dialog to perform various types of searches in the workspace.
  13. Ctrl + Shift + L: Show the Eclipse context-sensitive help.
  14. Ctrl + J: Incremental search in the currently open file.
  15. Ctrl + F6: Switch between open editor tabs.
  16. Ctrl + E: Show a list of open editor tabs.
  17. Ctrl + F: Open the Find/Replace dialog to search within the currently open file.
  18. Ctrl + K: Find the next occurrence of the current selection.
  19. Ctrl + Shift + K: Find the previous occurrence of the current selection.
  20. Ctrl + Shift + X: Convert the selected text to uppercase.
  21. Ctrl + Shift + Y: Convert the selected text to lowercase.
  22. Ctrl + Shift + C: Toggle line comment for the current line or the selected block.
  23. Ctrl + Shift + F7: Toggle between open perspectives.
  24. Ctrl + Shift + L: Show the list of available templates.
  25. Ctrl + F11: Run the last launched application.
  26. F5: Debug the current application.
  27. F6: Step over during debugging.
  28. F7: Step into during debugging.
  29. F8: Resume or continue during debugging.
  30. Ctrl + Shift + F11: Run the JUnit test for the current class.


These shortcuts can significantly boost your productivity in Eclipse by allowing you to navigate, edit, and debug your Java code more efficiently. Feel free to incorporate these shortcuts into your workflow to enhance your development experience.

How use Spaces instead of Tabs in Eclipse Java editor? Example

 To configure Eclipse to use spaces instead of tabs in the Java editor, you can follow these steps:

  • Open Eclipse preferences: Launch Eclipse and go to "Window" -> "Preferences" (on Windows) or "Eclipse" -> "Preferences" (on macOS).

  • Navigate to the Java editor settings: In the Preferences window, expand the "Java" category and select "Code Style" -> "Formatter".

  • Create or edit the formatter profile: In the Formatter tab, you can either create a new formatter profile or modify an existing one. If you want to create a new profile, click on the "New" button and give it a name. Otherwise, select the existing profile you want to modify.

  • Configure the indentation settings: In the "Indentation" tab, you'll find options to customize the indentation settings. To use spaces instead of tabs, follow these steps:

  • Select the "Spaces only" option for "Tab policy".

  • Set the "Indentation size" to the number of spaces you want to use for each level of indentation. For example, if you want to use 4 spaces for indentation, enter "4" in the "Indentation size" field.

  • Optionally, you can also set the "Tab size" to the same value as the "Indentation size" to ensure consistent spacing when mixing tabs and spaces (though it's recommended to use spaces consistently).

  • Apply and save the formatter settings: Click "Apply" to see a preview of the changes in the "Preview" section. If you're satisfied with the preview, click "OK" to save the formatter settings.
  • Set the formatter profile as the default: In the Preferences window, go to "Java" -> "Code Style" -> "Formatter". Select the formatter profile you created or modified in the "Active profile" dropdown list. Click "OK" to apply the changes.


By following these steps, you have configured Eclipse to use spaces instead of tabs for indentation in the Java editor. Any new code you write or format using Eclipse's auto-formatting feature will adhere to these indentation settings.