23 April, 2022

interview q4

 diff b/w @get and @getmapping:

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

In the @javax.ws.rs package there are annotations for each HTTP method. @GET, @POST, @PUT, @DELETE

 no sql db in aws : dynamo db

@controller vs @restcontroller:

@restcontroller combination of the @controller and @ResponseBody annotation.


What is the difference between @controller and @component?

@Component is a generic stereotype for any Spring-managed component or bean. @Repository is a stereotype for the persistence layer. @Service is a stereotype for the service layer. @Controller is a stereotype for the presentation layer (spring-MVC).


@Component vs @Bean:

@Component is a class level annotation whereas @Bean is a method level annotation 

@Bean annotation has to be used with @Configuration.

@Configuration
class MyConfiguration{
    @Bean
    public User getUser() {
        return new User();
    }
}

class User{
}    
        
// Getting Bean 
User user = applicationContext.getBean("getUser");

@Component
class User {
}

// to get Bean
@Autowired
User user;

Relational db in aws:

Amazon RDS

hashmap implementation in java 8:

In Java 8, HashMap replaces linked list with a binary tree when the number of elements in a bucket reaches certain threshold. While converting the list to binary tree, hashcode is used as a branching variable. If there are two different hashcodes in the same bucket, one is considered bigger and goes to the right of the tree and other one to the left. But when both the hashcodes are equal, HashMap assumes that the keys are comparable, and compares the key to determine the direction so that some order can be maintained. It is a good practice to make the keys of HashMap comparable.

what happens if we don't override hashcode

Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

diff between runnable and callable

Runnable object does not return a result whereas a Callable object returns a result.

future vs CompletableFuture:

ompletableFuture has some functional features that a regular Future does not have, like the ability to chain executions with thenApply or thenAccept that take a function that process the result after it´s available. get() is blocking which is present in Future. But if you do not need the results for further processing (Eg. you just want to insert the results in a Database) a CompletableFuture will have the advantage that you can provide a function that takes the result and does something with it. Eg. like this completableFuture.thenAccept(result -> DB::storeInDB); This way you would not have to wait for the result with get().

how to join results from multiple futures?

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");

String combined = Stream.of(future1, future2, future3) .map(CompletableFuture::join) .collect(Collectors.joining(" ")); assertEquals("Hello Beautiful World", combined);


asynchronous process : we can achieve in 2 ways 1) ExecutorService 2) CompletableFuture

A) ExecutorService executorService = Executors.newFixedThreadPool(3);
  Runnable service1 = () -> {
     MyFileService.service1();
  };

  Runnable service2 = () -> {
      MyFileService.service2();
  };

  Runnable service3 = () -> {
      MyFileService.service3();
  };

  executorService.submit(service1);
  executorService.submit(service2);
  executorService.submit(service3);

B) CompletableFuture.supplyAsync(() -> MyFileService.service1();
    CompletableFuture.supplyAsync(() ->  MyFileService.service2();
    CompletableFuture.supplyAsync(() ->  MyFileService.service3();

CompletableFuture API allows to easily chain more calls with thenApply(), thenCompose().
CompletableFuture.allOf() : wait for all futures

CompletableFuture runAsync vs supplyAsync:

runAsync :it does not return any result
suppyAsync: it takes Supplier as argument and returns result

 java8 new features:

1) Consumer<T> :Its a part of java.util.function package. Consumer can be used in all contexts where an object needs to be consumed,i.e. taken as input, and some operation is to be performed on the object without returning any result. 

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;


public class ConsumerFunctionEx{

  public static void main(String args[]){

    Consumer<Integer> consumer= i-> System.out.print(i+",");

    List<Integer> integerList=Arrays.asList(new Integer(1), 

                              new Integer(10), new Integer(200),

                              new Integer(101), new Integer(-10),

                              new Integer(0));

    print(integerList, consumer);

 }

 public static void print(List<Integer> listOfIntegers, Consumer<Integer> consumer){

  for(Integer integer:listOfIntegers){

    consumer.accept(integer);

  }

 }

}

================

output:

1,10,200,101,-10,0,


2)Functional Interface : it contains only one abstract method.

Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).
@FunctionalInterface
interface add_cal{
    int add(int a, int b);
}
public class Sample{
    public static void main(String[] args){
        add_cal a1 = (a,b) -> {
            return a+b;
        };
        System.out.println(a1.add(5,10));
    }
}
============
output
15

3) Optional Class :used to deal with NullPointerException

import java.util.Optional;  
public class OptionalExample {  
    public static void main(String[] args) {  
        String x = "hello";
        Optional<String> opt = Optional.ofNullable(x);
        if(opt.isPresent()){
            System.out.println(opt.get());
        }
    }  
} 

===============
output:
hello

4) forEach loop:new method forEach() to iterate the elements
public class ForEachExample {  
    public static void main(String[] args) {  
        List<String> gamesList = new ArrayList<String>();  
        gamesList.add("Football");  
        gamesList.add("Cricket");  
        gamesList.add("Chess");  
       gamesList.forEach(games -> System.out.println(games));  
          
    }  
}  

=============
output:
Football
Cricket
Chess

5) Default Methods :defined inside the interface and tagged with default are known as default methods. These methods are non-abstract methods. This has implementation.

interface Sayable{  
    default void say(){  
        System.out.println("Hello, this is default method");  
    }  
}  
public class DefaultMethods implements Sayable{  
    public static void main(String[] args) {  
        DefaultMethods dm = new DefaultMethods();  
        dm.say();   
     }  
}

6) StringJoiner: 
sed to construct a sequence of characters separated by a delimiter
public class StringJoinerExample {  
    public static void main(String[] args) {  
        StringJoiner joinNames = new StringJoiner(","); 
        joinNames.add("hello");  
        joinNames.add("world");  
        
        System.out.println(joinNames);  
    }  
} 

=====
output: hello,world

7) Collectors : It provides reduction operations
import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList;  

public class CollectorsExample {  
    public static void main(String[] args) {  
        List<Integer> list = new ArrayList<Integer>(); 
        List<Integer> list1 = new ArrayList<Integer>(); 
        list.add(1);
        list.add(2);
        list.add(3);
        list1 = list.stream().map(x->x*x).collect(Collectors.toList());
        System.out.println(list1); 
        
    }  
} 
============
output: [1, 4, 9]

8)Stream: does not store elements.lazy and evaluates code only when required
public class StreamExample {  
    public static void main(String[] args) {  
        List<Integer> list = new ArrayList<Integer>(); 
        List<Integer> list1 = new ArrayList<Integer>(); 
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list1 = list.
        stream().filter(x->x%2==0).
        map(x->x*x).
        collect(Collectors.toList());
        System.out.println(list1); 
        
    }  
}
============
output: [4, 16]

9) CompletableFuture:extension of Future’s API.
Future:The get() method in the Future Interface is blocking operation.Multiple futures cannot be chained together with Future.