Nagarro Java developer Interview Questions

Nagarro Java developer Interview Questions

1. Difference in ArrayList and Hashset

Some difference between ArrayList and Hashset are:

  1. ArrayList implements List interface while HashSet implements Set interface in Java.
  2. ArrayList can have duplicate values while HashSet doesn’t allow any duplicates values.
  3. ArrayList maintains the insertion order that means the object in which they are inserted will be intact while HashSet is an unordered collection that doesn’t maintain any insertion order.
  4. ArrayList is backed by an Array while HashSet is backed by an HashMap.
  5. ArrayList allow any number of null value while HashSet allow one null value.
  6. Syntax:
    1. ArrayList:-ArrayList list=new ArrayList();
    2. HashSet:-HashSet set=new HashSet();

2. Using Lambda Function print given List of Integers

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		List<Integer> arr = Arrays.asList(1,2,3,4);
		arr.forEach(System.out::println);
		arr.stream().forEach(s->System.out.println(s));
	}
}

Output

1
2
3
4

3. new ArrayList(2); What does this mean?

4. Difference in Synchronization and Lock

Differences between lock and synchronized:

  • with locks, you can release and acquire the locks in any order.
  • with synchronized, you can release the locks only in the order it was acquired.

5. What is Closeable interface?

A Closeable is a source or destination of the data that needs to be closed. The close() method is invoked when we need to release resources that are being held by objects such as open files.

The close() method of an AutoCloseable object is called automatically when exiting a try -with-resources block for which the object has been declared in the resource specification header.

Closeable is defined in java.io and it is idempotent. Idempotent means calling the close() method more than once has no side effects.

Declaration

public interface Closeable extends AutoCloseable 
{
    public void close() throws IOException;
}

Implementing the Closeable interface

import java.io.*; 
class Main { 
	public static void main(String s[]) 
	{ 
		try (Demo1 d1 = new Demo1(); Demo2 d2 = new Demo2()) { 
			d1.show1(); 
			d2.show2(); 
		} 
		catch (ArithmeticException e) { 
			System.out.println(e); 
		} 
	} 
} 
//Resource1
class Demo1 implements Closeable { 
	void show1() { System.out.println("inside show1"); } 
	public void close() 
	{ 
		System.out.println("close from demo1"); 
	} 
} 
//Resource2
class Demo2 implements Closeable { 
	void show2() { System.out.println("inside show2"); } 
	public void close() 
	{ 
		System.out.println("close from demo2"); 
	} 
}

Output

inside show1
inside show2
close from demo2
close from demo1

6. What are Lambda Functions?

A lambda expression is a block of code that takes parameters and returns a value

Syntax of Lambda Expression

Lambda expression contains a single parameter and an expression

parameter -> expression

Lambda expression contains a Two parameter and an expression

(parameter1, parameter2) -> expression

Expressions cannot contain variables, assignments or statements such as if or for. If you wanted to do some more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.

(parameter1, parameter2) -> { code block }
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.forEach( (n) -> { System.out.println(n); } );
  }
}

Output

1
2
3
4

7. What are @Component and @Service used for?

@Component

@Component annotation is used across the application to mark the beans as Spring’s managed components.  Spring check for @Component annotation and will only pick up and register beans with @Componentand doesn’t look for @Service and @Repository in general.

@Repository

@Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

@Service

We mark beans with @Service to indicate that they’re holding the business logic. Besides being used in the service layer, there isn’t any other special use for this annotation.

8. Why ‘get’ type in REST API called idempotent?

An idempotent HTTP method is a method that can be invoked many times without the different outcomes. It should not matter if the method has been called only once, or ten times over. The result should always be the same.

  • POST is NOT idempotent.
  • GET, PUT, DELETE, HEAD, OPTIONS and TRACE are idempotent.
  • A PATCH is not necessarily idempotent, although it can be.

9. Working of HashMap

HashMap contains an array of Node and Node can represent a class having the following objects : 

  1. int hash
  2. K key
  3. V value
  4. Node next

10. What are different types of method in REST API?

Some different types of REST API Methods are GET, POST,  PUT,  PATCH,  DELETE.

11. How to load application.yml file in application.

To Work with application.yml file, create a application.yml in the src/resources folder. Spring Boot will load and parse yml file automatically and bind the values into the classes which annotated with @ConfigurationProperties

12. /users/:id and /user/name={“Saurabh”} convert into API

13. What is Transaction Management in Spring?

A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency.

The concept of transactions can be described with the following four key properties described as ACID 

  • Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful.
  • Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc.
  • Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption.
  • Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.

14. How to load application.yml file in application?

Ans: @EnableConfigurationProperties

15. Backward Compatibility of Java 1.8

Java versions are expected to be binary backwards-compatible. For example, JDK 8 can run code compiled by JDK 7 or JDK 6. It is common to see applications leverage this backwards compatibility by using components built by different Java version. A Compatibility Guide (explained later) exists for each major release to provide special mention when something is not backwards compatible.

The backwards compatibility means that you can run Java 7 program on Java 8 runtime, not the other way around.

16. Input- [2,1,3,2,4,5,3,5,6] Output- [1,2,3,4,5,6] How to do this?

import java.util.*; 
class Main { 
	public static void main(String s[]) 
	{ 
        ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(4,2,6,8,9,1,3,4));
        Set<Integer> set = new  HashSet<Integer>(); 
        set.addAll(arr);
        arr.clear();
        arr.addAll(set);
        System.out.println(arr); 
	} 
}

Output

[1, 2, 3, 4, 6, 8, 9]

17. Default size of HashSet?

Default size of HashSet is 16.

18.  What is Functional Interface and it’s example?
Functional Interface is a Interface that contains only one abstract method. It can contains any number of default, static methods but can have only one abstract method.

Abstract method is a method that does not have a body

@FunctionalInterface
interface CustomFunctionalInterface {
   void display();
}
public class Main {    
   public static void main(String[] args) {    
      CustomFunctionalInterface functionalInterface = () -> { 
         System.out.println("Functional Interface Example");
      };
      functionalInterface.display();
   }    
}

Output

Functional Interface Example

19. Difference between Encapsulation and Data Hiding.

Key Differences Between Data Hiding and Encapsulation

  1. Encapsulation deals with hiding the complexity of a program. On the other hand, data hiding deals with the security of data in a program.
  2. Encapsulation focuses on wrapping (encapsulating) the complex data in order to present a simpler view for the user. On the other hand, data hiding focuses on restricting the use of data, intending to assure the data security.
  3. In encapsulation data can be public or private but, in data hiding, data must be private only.
  4. Data hiding is a process as well as a technique whereas, encapsulation is subprocess in data hiding.

20. What are generics?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity.

class GenericTest<T> { 
    T obj; 
    GenericTest(T obj) { this.obj = obj; }
    public T getObject() { return this.obj; } 
} 
class Main { 
    public static void main(String[] args) 
    { 
        GenericTest<Integer> obj1 = new GenericTest<Integer>(10); 
        System.out.println(obj1.getObject()); 
        GenericTest<String> obj2 
            = new GenericTest<String>("Generic Example"); 
        System.out.println(obj2.getObject()); 
    } 
}

Output

10
Generic Example