Java Interview Questions – Java Developer

By | June 18, 2024

1. String vs. StringBuilder | When to use String and StringBuilder in Java?

FeatureStringStringBuilder
DefinitionString is an immutable class in Java, which means once an object is created, its value cannot be changed.StringBuilder is used to create mutable string objects, which means we can change the content of the StringBuilder object.
OperationAny operation that tries to modify the string will eventually create a new string object in the string pool constant.We can modify the content of a StringBuilder object without creating a new object.
Thread-safetyString is thread-safe in Java.StringBuilder is not thread-safe in Java.
ConcatenateIn Java, when you concatenate two string objects using the + operation, a new string object is created to store the result.We can concatenate two StringBuilder objects by using the append method.
When to useA string should be used when the contents of the string won’t change frequently.StringBuilder should be used to create a string when we want multiple modifications to it. Say, concatenation, insertion, or deletion.

2. Difference between BufferedReader and Scanner class in Java?

BufferedReaderScanner
BufferedReader is a class in Java, present in java.io package.Scanner class is present in java.util package in Java.
BufferedReader reads text from character based input stream.Scanner is used to parse and process primitive values from various sources such as standard input, files or string.
It is efficient for reading larger amount of character dataIt is suitable for simpler inputs.
It throws checked exception.
Example: IOException.
Scanner uses exception for flow control.
Example: InputMismatchException, NoSuchElementException.

3. Can Entity class in Hibernate (JPA) required @Id annotation or primary key?

According to JPA documentation, every entity class must have a primary key that uniquely identifies each record in the database table.

There are situations where we are required to create an entity class without a primary key. In JPA, those entities are considered embedded entities that are part of another entity and do not have a separate existence in the database. In order to use embedded entities, we need to use the @Embeddable annotation over the entities that we want to add to another entity.

Address.java
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.Setter;

/**
 * 1. Mark the Address class with @Embeddable annotation
 * 2. This annotation will make it of Embeddable type so,
 * that it can be embedded in another class
 * @author paulsofts
 */

@Getter
@Setter
@Embeddable
public class Address {
	
	private String street;
	private int pin;
	private String city;
	private String state;
	private String country;

}

Above, we have annotated the Address class with the @Embeddable annotation, and we will add it to the Employee class.

Employee.java
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import lombok.Getter;
import lombok.Setter;

/**
 * 1. We have created Employee class as Entity
 * 2. Embedded the Address class
 * @author paulsofts
 */

@Entity
@Getter
@Setter
public class Employee {
	
	private int empId;
	private String empName;
	@Embedded
	private Address address;

}

4. What is the default maven dependency scope?

The Maven dependency scope is an attribute that is used to set the visibility of the dependency in different lifecycle stages such as build, run, compile, test, etc. The default dependency scope in Maven is compile.

XML
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <!-- We can skip this scope, as it is the default scope -->
    <scope>compile</scope>
  </dependency>

Maven has the following dependency scopes:

  • <scope>compile</scope>
  • <scope>runtime</scope>
  • <scope>provided</scope>
  • <scope>test</scope>
  • <scope>import</scope>
  • <scope>system</scope>

5. In a Spring Boot application, if any exception occurs in the repository layer and we do not want to handle it in the repository layer, instead we want to handle it in the service layer, how can we do that?

In Java, the throws keyword is used for exception propagation. The above scenario can be easily achieved with the help of the throws declaration.

6. How to convert Java object to JSON string?

In order to convert a Java object to a JSON string, we can use any library that supports serialization and de-serialization. For example, Jackson.

Java
import com.fasterxml.jackson.databind.ObjectMapper;

public class Employee {
	
	int empId;
	String empName;
	
	public Employee(int empId, String empName) {
		super();
		this.empId = empId;
		this.empName = empName;
	}
	
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public static void main(String[] args) {
		String output = "";
		Employee employee = new Employee(101, "Bindhiya");
		ObjectMapper mapper = new ObjectMapper();
		try {
			 output = mapper.writeValueAsString(employee);
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println(output);
	}

}

7. How to lock version of dependency in Maven?

We can lock the version of a dependency in Maven by specifying the <version> tag in the pom.xml file.

pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>3.3.0</version>
</dependency>

8. What is Bean and bean lifecycle in Spring?

In Spring, the object that forms the backbone of the application and are managed by the Spring IOC are called beans.

When we run a Spring application, First of all, the Spring container gets started; after that, the container creates the instances of the bean as per requirement, and then their dependencies are injected. After the application completes its execution, the beans are destroyed when the spring container is closed.

Leave a Reply

Your email address will not be published. Required fields are marked *