1. What is the better way to declare a string?
There are two ways to declare a string in java:
By String literal: Java String literal is created by using double quotes.
For Example:
String s= "Java String";
By new keyword: Java String is created by using the keyword “new”.
For example:
String s=new String(“Welcome”);
When we create an object using String literal which is using double quotes, it may return an existing object from the String pool, if it already exists. If Object not exist in String pool, it will create a new String object and put it in the string pool for future re-use.
When we declare String using new() operator, it create the object in heap memory.
Lets see some example to understand it better
import java.util.*;
public class Main
{
public static void main(String[] args) {
String str1 = "JavaString";
String str2 = "JavaString";
System.out.println(str1 == str2);
}
}
Output
true
In the above example both string object str1 and str2 have the same reference.
Now we are creating two different string objects using new Keywords
import java.util.*;
public class Main
{
public static void main(String[] args) {
String str1 = new String("JavaString");
String str2 = new String("JavaString");
System.out.println(str1 == str2);
}
}
Output
false
So If possible we should use String literal notation because it is easier to read and it helps compiler to optimize our code.
2. Java 8 Program to Remove duplicates of Employee objects from List
import java.util.*;
class Employee{
int empId;
String name;
int empSalary;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getEmpId(){
return this.empId;
}
public void setEmpId(int empId){
this.empId = empId;
}
public int getEmpSalary(){
return this.empSalary;
}
public void setEmpSalary(int empId){
this.empSalary = empSalary;
}
public Employee(int empId, String empName, int empSalary){
this.empId = empId;
this.name = empName;
this.empSalary = empSalary;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Employee) {
Employee temp = (Employee) obj;
if ((this.empId == temp.empId) && this.name.equals(temp.name) && (this.empSalary == temp.empSalary))
return true;
}
return false;
}
@Override
public int hashCode() {
return (this.empId + this.name.hashCode() + this.empSalary );
}
}
class Main {
public static void main(String[] args) {
List<Employee> employee = new ArrayList<Employee>();
employee.add(new Employee(1,"Mayank",2));
employee.add(new Employee(2,"Nishant",1));
employee.add(new Employee(3,"Subhesh",3));
employee.add(new Employee(2,"Nishant",1));
employee.add(new Employee(3,"Subhesh",3));
List <Employee> list = new ArrayList();
Set < Employee > s = new HashSet < Employee > ();
s.addAll(employee);
list = new ArrayList < Employee > ();
list.addAll(s);
list.stream().forEach(out -> System.out.println(out.getName()));
}
}
Output
Nishant
Mayank
Subhesh
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
3. Tell me about various phases of Hibernate.
There are mainly four states of the Hibernate Lifecycle
- Transient State
- Persistent State
- Detached State
- Removed State
Transient state
- This is the initial state of an object when an instance of POJO class is created.
- In the Transient State, object is not associated with the Session.
- This state is not related to any database.
- Here any modifications done in the will not affect the database changes.
- Transient objects exist in the heap memory and they are independent of Hibernate.
Employee emp=new Employee(); //When instance created, object enters in the transient state.
emp.setId(101);
emp.setName("TutorialWorld");
emp.setSalary("1000");
Persistent state
- When an object is Connected with Hibernate Session, it is entered into the persistent state.
- The object is in the persistence state when we save or persist it.
- There are two ways to convert the Transient State to the Persistent State Using the hibernated session, saving the entity object into the database table, and using the hibernated session, loading the entity object into the database table.
- Each object represents the row of the database table.
- So when we do some modifications to the data, hibernate will detect the changes and make changes in the database table.
Some methods of persistent state are
- session.persist(e);
- session.save(e);
- session.saveOrUpdate(e);
- session.update(e);
- session.merge(e);
- session.lock(e);
// Transient State
Employee emp=new Employee();
emp.setId(101);
emp.setName("TutorialWorld");
emp.setSalary("1000");
//Persistent State
session.save(emp);
Detached State
- An object entered into the detached state When we close the session or clear its cache.
- In this state modifications in the data do not affect the database changes because the object is no more associated with the Session.
- We can reconnect the detached object to a new hibernate session whenever required.
- There are some methods to reconnect the detached object to a new hibernate session.
Methods are :
- merge()
- update()
- load()
- refresh()
- save()
- update()
Methods used for detached state :
- session.detach(emp);
- session.evict(emp);
- session.clear();
- session.close();
// Transient State
Employee emp=new Employee();
emp.setId(101);
emp.setName("TutorialWorld");
emp.setSalary("1000");
//Persistent State
session.save(emp);
// Detached State
session.close();
Removed State
- This is the last state of hibernate life cycle.
- When an entity object is deleted from the database then the entity object is known to be in the removed state.
- In the removed state, any change in the data will not affect the database table.
- If the Entity Object is in the removed state, if any change will be done in the data will not affect the database table.
- session.delete() is called to make a removed entity object.
4. Different Design patterns used in your project.
There are mainly three design pattern that are further divided into subparts
Java Design Patterns
In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:
1. Creational Design Pattern
- Factory Pattern
- Abstract Factory Pattern
- Singleton Pattern
- Prototype Pattern
- Builder Pattern.
2. Structural Design Pattern
- Adapter Pattern
- Bridge Pattern
- Composite Pattern
- Decorator Pattern
- Facade Pattern
- Flyweight Pattern
- Proxy Pattern
3. Behavioral Design Pattern
- Chain Of Responsibility Pattern
- Command Pattern
- Interpreter Pattern
- Iterator Pattern
- Mediator Pattern
- Memento Pattern
- Observer Pattern
- State Pattern
- Strategy Pattern
- Template Pattern
- Visitor Pattern
5. What are default methods? How to call them.
The default methods were introduced in Java 8 to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class.
Default methods are also known as defender methods or virtual extension methods.
By default, default methods are implicitly public and we no need to specify it with public modifier.
And to declare default method we use default keyword at the beginning of the method signature.
Example of default method
public interface DefaultInterface {
default void defaultMethod() {
// default method implementation
}
}
Java 8 Program to demostrate default method
interface DefaultInterface {
public void cube(int a);
default void show() {
System.out.println("Default Method Called");
}
}
class Main implements DefaultInterface {
public void cube(int a) {
System.out.println(a * a * a);
}
public static void main(String args[]) {
Main obj = new Main();
obj.cube(5);
obj.show();
}
}
Output
125
Default Method Called
6. Difference between static and instance methods in java
- Static methods are defined at the class level. It can be accessed with a class name and we do not need to create an object to access or call the static methods. Whereas the instance method is a method without static keywords. So to access the instance method we need to create an object of the class to access.
- Also static methods exist as a single copy for a class while instance methods exist as multiple copies depending on the number of instances created for that particular class.
- Static methods can’t access instance methods/variables directly while instance methods can access static variables and static methods directly.
7. Tell some Various features of Java 8?
Java 8 provides following features for Java Programming:
- Lambda expressions,
- Method references,
- Functional interfaces,
- Stream API,
- Default methods,
- Base64 Encode Decode,
- Static methods in interface,
- Optional class,
- Collectors class,
- ForEach() method,
- Nashorn JavaScript Engine,
- Parallel Array Sorting,
- Type and Repating Annotations,
- IO Enhancements,
- Concurrency Enhancements,
- JDBC Enhancements etc.
8. What are lambdas 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.
Example:
Single parameter lambdas
parameter -> expression
lambdas with multiple parentheses
(parameter1, parameter2) -> expression
9. Importance of @FunctionalInterface annotation
Annotation @FunctionalInterface is used to mark Interface as Functional interfaces. This Functional Interface include only one abstract method. A functional interface can extend another interface only when it does not have any abstract method.
Example of FunctionalInterface :
@FunctionalInterface
interface FunctionalInterfaceExample{
void display(String msg);
}
public class Main implements FunctionalInterfaceExample{
public void display(String msg){
System.out.println(msg);
}
public static void main(String[] args) {
Main functionalInterface = new Main();
functionalInterface.display("Functional Interface Example");
}
}
Output
Functional Interface Example
11). What is default scope of Bean?
Default bean scope is singleton scope (meaning, one instance of that bean in the application).
11. What happens if I change it?
The scope of a bean defines the life cycle and visibility of that bean in the contexts we use it.
The latest version of the Spring framework defines 6 types of scopes:
- singleton
- prototype
- request
- session
- application
- websocket
The last four scopes mentioned, request, session, application and websocket, are only available in a web-aware application.
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}