Tuesday, 29 August 2023

Akkodis company Java technical Lead(Exp - 9 to 12 yrs) interview questions

       Below are the list of java technical lead interview questions asked in Akkodis during the firstround.

1) What are the features in java8 ?

2) Why introduced default method in java 8 ?

3) What is the use of static method in java 8 ?

4) What is functional interface in java8 ?

5) What is the use of flatMap in streams and explain with example

6) List<Integer> list = Arrays.asList(10, 23, 8, null);

Write a program to sort the list in ascending and descending order and remove the nulls --using streams

7) what is generics in java ? Is this supports polymorphism ? (Answer -- yes)
if yes then which polymorphism supports compile or runtime(Answer - runtime)  

8) How many ways to create thread ? which one prefer and why ?

9) What implemenation or changes done in HashMap in java 8 ?

10) Which scenario's to use ArrayList and LinkedList

11) Asked some Linux commands.

12) Explain contract between equals and hashcode method.

13) What are the intermediate functions in streams.

14) How to make ArrayList as final - as final is immutable.

15) How to create singleton object and how to restrict for clone and deserialization

16) How to handle global the exception in spring boot

17) What is checked and unchecked exception

18) How to set the priority thread in threads.

19) What is completable future in java 8.


Thank you for visiting the blog.

Thursday, 24 August 2023

Find duplicate elements from the given a list using Java 8 Stream

       In this post, we need to have a look one of the important coding interview questions asked for java 8 streams. Given list contains either String or Integers. Refer all coding questions here

1) Print duplicate elements using frequency and toSet methods    . 

      In the below code used Collections.frequency to filter the data with occurance value greater than 1 and toSet method used to remove the duplicated in output.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

	 Set<Integer> list = integerList.stream().filter(
			        s -> Collections.frequency(integerList, s) > 1)
                                  .collect(Collectors.toSet());
		
	 list.stream().forEach(s -> System.out.println("Duplicate element - "+s));
     }
}

Output:- Duplicate element - 3
              Duplicate element - 6

2) Using frequency and toMap method(map used to store element with occurance)

Used frequency and toMap method to store duplicates into the Map with occurance as a value.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

		// store duplicate into the map
	  Map<Integer, Long> map = 
                         integerList.stream().filter(
	                    s -> Collections.frequency(integerList, s) > 1).collect(
			    Collectors.toMap(Function.identity(), v -> 1L, Long::sum));

		map.entrySet().stream().forEach(s -> System.out.println(s));
	}
}

Output: - 3=2
               6=3

3) Using groupingBy and counting methods - group the similar elements and to find the occarance used counting.

To write the code to find the duplicate using groupingBy,

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

     public static void main(String[] args) {

          List<String> listOfString = Arrays.asList("A", "B", "C", "A", "A", "D", "B");

	  Map<String, Long> mapOfStrings = 
			listOfString.stream().filter(
			    s -> Collections.frequency(listOfString, s) > 1)
			    .collect(Collectors.groupingBy(Function.identity(), 
			        Collectors.counting()));

	   mapOfStrings.entrySet().stream().forEach(s -> System.out.println(s));
    }
}

Output:-A=3
             B=2


Thank you for visiting blog.

Refer the post for coding questions - coding questions

Monday, 21 August 2023

LTIMindtree Java technical Lead interview questions

       Below are the list of java technical lead interview questions asked in LTIMindtree during the first round

1) Explain Saga design pattern used in Microservice(Answer)

2) What is orchestrator in Saga pattern?(Answer)

3) Which authentication mechanism used in project and how to implemented(AOuth2 with bearer token)?

3) What is the use of Eureka server?(Answer)

4) What is Functional interface in java 8? do we have default method in Functional interface(Answer)

5) Why introduced deafult method in interface in java 8?(Answer)

6) What is lambda expression ?(Answer)

7) What is difference between collection and stream?(Answer)

8) What is the use of status code in Rest API ?(Answer)

9) What is database/memory lock expeption?

10) What are HTTP idempotent methods?(Answer)

11) What are the key components in spring boot?

12) What is the use of @WebMvcTest . Difference between @WebMvcTest and @SpringBootTest(Answer)

13) Write a program to find second largest word in the sentence.

14) Write a query to find the max salary from the employee table whose name is Reta


Thank you for visiting blog.

Previous                                                   Home

Related Posts:-

1) Publicis Sapient Java Technical Lead Interview questions

2) mobtexting company Java Technical Lead interview questions

Wednesday, 16 August 2023

Java 8 Optional Class with examples

          In java8 introduced new class called Optional, using optional we can handle NullPointerException without using any null check condition.( Refer - Java 8 featuresIt provided many methods and using those it will be helpful to write cleanable code.

         Using optional if variable value is null then using orElse method we can have a null functionality code inside it.

 Below are the methods available in Optional class,

Java 8 optional class methods

The Optional.ofNullable() --- > method returns a Non-empty Optional if a value present in the given object. Otherwise returns an empty Optional. 

Optional.empty() -- > method is useful to create an empty Optional object.

Optional.of(value) --> creates an Optional object using value. 

Optional.ifPresent -- > If optional variable value is present, invoke the specified consumer with the value, otherwise, do nothing.

orElse --> If optional variable value is null then invokes orElse method.

 orElseGet --> If optional variable value is null then invokes orElse method and return the result of that invocation.

 orElseThrow --> If optional variable value is null then invokes orElseThrow method and throws the exception provided in the method.

 get -- > method returns the value from the optional.

 isPresent - if optional variable value is present/exist then return true else it's false.


Optional Class Code Example - 

import java.util.Optional;

public class OptionalClassUsages {
	
	public static void main(String[] args) {
		
		//ofNullable, orElse, orElseGet and orElseThrow method example
		String str = "Optional with ofNullable method usage";
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		
		str = null;
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		System.out.println(Optional.ofNullable(str).orElseGet(() -> "orElseGet method"));
		
		try {
			Optional.ofNullable(str).orElseThrow(() -> {
				return new Exception("orElseThrow Exception");
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//optional of, ifPresent, filter usages
		Optional<String> optional = Optional.of("ab");
		optional.ifPresent(s-> System.out.println(s));
		optional.filter(s->s.equals("ab"))
				.ifPresent(s-> System.out.println("ifPresent method usage"));
		
		//isPresent and get method usage example
		System.out.println(optional.isPresent());
		System.out.println(optional.get());	
	}
}

Output:- 

Optional with ofNullable method usage
null logic
orElseGet method
java.lang.Exception: orElseThrow Exception
	at com.main.OptionalClassUsages.lambda$1(OptionalClassUsages.java:19)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at com.main.OptionalClassUsages.main(OptionalClassUsages.java:18)
ab
ifPresent method usage
true
ab


Thank you for visiting the blog.

Previous                                                    Home                                                                            Next

Reference posts:

Tuesday, 15 August 2023

Java program to find the Second largest number in an Array or List

     Given an unsorted array of an integers or a List, to write a Java program to find the second largest number or element from the Array or a List

1) Given input is an array of integers

import java.util.Arrays;

public class SecondLargest {

	public static void main(String[] args) {	
		SecondLargest secondLargest = new SecondLargest();
		int[] array = { 2, 8, 3, 4, 5, 7 };
		System.out.println("Second largest number - " + secondLargest.findSecondLargestNumber(array));
	}

	private int findSecondLargestNumber(int[] array) {
		Arrays.sort(array);
		return array[array.length - 2];
	}

}

Output :- Second largest number - 7


2) Given input is a list

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		Collections.sort(listOfIntegers);
		return listOfIntegers.get(listOfIntegers.size() - 2);
	}

}

Output:- Second largest number - 7

3) Given input as a List, find second largest number using Stream(Java8)

import java.util.Arrays;
import java.util.List;

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		return listOfIntegers.stream().sorted()
				.skip(listOfIntegers.size() - 2)
				.findFirst()
				.get();
	}

}

Output:- Second largest number - 7.


Thank you for visiting the blog.

Related page:-

Monday, 14 August 2023

How to resolve circular dependency in spring Framework

 In this tutorial, we can dsicuss about circular dependency in Spring, first need to understand what's the circular dependency and how to fix it.

What is Circular Dependency in Spring ?

In Spring, circular dependency is a dependency chain where two or more beans depends on each other.

For example - Class A requires an instance of class B and class B also requires an instance of class A through any type of injection. In this case, the Spring IoC container detects circular reference at runtime, and throws a BeanCurrentlyInCreationException.

In Spring Boot, circular dependency can occur when using the constructor injection as see below code,

import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    public BeanA(BeanB beanB) {
         this.beanB= beanB;
    }
}

Second bean,
import org.springframework.stereotype.Component;

@Component
public class BeanB {
    private final BeanA beanA;

    public BeanB(BeanA beanA) {
        this.beanA = beanA;
    }
}

Main Application Class,
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoSpringBootApplication{

    public static void main(String[] args) {
        SpringApplication.run(HMSApplication.class);
    }

}

When we run the application using IDE or command(mvn spring-boot:run) during runtime throws below error,

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

Solution: 

1) Use Setter injection

        As see in the above example about circular dependency as there used construction injection so here the solution is to edit the source code of the class to be configured by setter injection instead of constructor injection.
       In such example need to avoid constructor injection and to use setter injection only. 

import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    @Autowired
    public void setBeanB(BeanB beanB) {
         this.beanB= beanB;
    }
}

Second Bean,
import org.springframework.stereotype.Component;

@Component
public class BeanB {
    private final BeanA beanA;
    
    @Autowired
    public void setBeanA(BeanA beanA) {
         this.beanA= beanA;
    }
}

The above approach is not recommended, you can configure circular dependencies with setter injection as well.

2)  Use Lazy Initialization

One of the dependency bean to define as @Lazy so it will load the bean whenever it's called. It's not being intialized during the application start up. So this is one of the way to handle the circular dependency issue.

In the previous example, need to use @Lazy annotation at BeanA class with BeanB setter injenction.

import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    @Autowired
    @Lazy
    public void setBeanB(BeanB beanB) {
         this.beanB= beanB;
    }
}


Thank you for visiting the blog.


Reference Post:-

Wednesday, 2 August 2023

mobtexting company Java Technical Lead interview questions

  Below are the list of java technical lead interview questions asked in mobtexting company.

1) 

List<String> list = new ArrayList<String>();
list.add("abc");
List<String> linkedList = new LinkedList<String>();
linkedList.add("abc");

list.get()     
linkedList.get(); 

In the above code, which one is faster, whether list.get or linkedList.get ?

Answer :- list.get is faster than linkedList. more details refer Time Complexity of Collection API

2) 
HashMap<String, String> map = new HashMap<String, String>();
map.put("a", "abc");
TreeMap<String, String> treeMap = new TreeMap<String, String>();
treeMap.put("a", "abc");

map.get("a");
treeMap.get("a");

Which one is faster HashMap or TreeMap retrieval ? (Answer)
and also explain the internal working of HashMap and TreeMap ?

3) 
public class Key{
   private String name,
   private String id;
   
   //constructir and Setters and getters
}

public class Main {
    
    public static void main(String[] args) {
   
         Map<Key, String> map = new HahsMap<Key, String>();
   
         Key a = new Key("XYZ", "123");
         Key b = new Key("XYZ", "234");
   
         map.put(a, "Value");
   
         map.get(b);
         map.get(a);
    }
}

What is the output for map.get code ?

4) What is dependency injection ? (Answer) What is diffrence between Spring MVC and Spring boot?(Spring)

5) What is difference between setter injection and constructor injection.(Answer)

6) What are the different ways to create bean ? (Answer)

7) Explain Spring bean scopes and Spring bean singleton is thread safe or not ?(Answer)

8) What are IOC containers in spring ?(Answer)

9) What is difference between Hibernate and JPA? can we use hibernate without JPA?

10) Explain JPA entity lifecycle/status.(Answer)

11) What is eager and lazy loading ? whats N+1 problem and solution(Answer)

12) Explain first level and second level caching in hibernate(Answer)

13) Explain ACID properties of transaction  (Answer)

14) SQL
create table person(
  id integer,
  name varchar,
  primary key(id)
);
 
create car_owner(
   person_id integer(it's primary key of person table),
   car_id integer (it's primary key of car table)
);

create table car(
  id integer,
  car_brand varchar,
  car_color varchar,
);
 
 Write a query to return car brand and car owner name for all the owners
 
 Answer :- 
SELECT p.name, c.brand FROM person p, car_owner co, car c 
 WHERE p.id = co.person_id AND 
       co.car_id = c.id
 
 Write a query to count the total cars for each color greater than 10.
 
 Answer
SELECT count(*), color FROM car 
group by color HAVING count(*) > 10;


Thank you for visiting the blog.