Metacube java interview questions for experienced

Metacube java interview questions for experienced

1. How do you ensure unauthorized access to service if OAuth can be shared by service.

2. How do you create an API?

3. Difference in Microservice and Monolithic?

4. How do you create Beans in Microservice?

Declaring a bean. To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .

@Configuration

Annotating a class with the @Configuration annotation indicates that the class will be used by JavaConfig as a source of bean definitions.

An application may make use of just one @Configuration-annotated class, or many. @Configuration can be considered the equivalent of XML’s <beans/> element. Like <beans/>, it provides an opportunity to explicitly set defaults for all enclosed bean definitions.

@Configuration(defaultAutowire = Autowire.BY_TYPE, defaultLazy = Lazy.FALSE)
public class DataSourceConfiguration {
    // bean definitions follow
}

Because the semantics of the attributes to the @Configuration annotation are 1:1 with the attributes to the <beans/> element, this documentation defers to the beans-definition section of Chapter 3, IoC from the Core Spring documentation.

4.2.  @Bean

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> such as init-methoddestroy-methodautowiringlazy-initdependency-checkdepends-on and scope.

4.2.1. Declaring a bean

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be that of the method name (see bean naming for details on how to customize this behavior).

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

The above is exactly equivalent to the following appConfig.xml:

<beans>
    <bean name="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

5. Can Hashmap have null value?

Yes

6. Can Hashmap have null key?

Yes

7. try with resource?

8. Features of Java 8? Streams, Lambda, Optional

9. Optional in Java 8

Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.

Program without optinal

// Java program without Optional Class
public class Main {
  public static void main(String[] args) {
    String[] str = new String[10];
    String lowerStr = str[5].toLowerCase();
    System.out.print(lowerStr);
  }
}

Output

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:4)

Program With optional

import java.util.Optional;
public class Main {
  public static void main(String[] args) {
    String[] str = new String[6];
    Optional <String> nullCheck = Optional.ofNullable(str[5]);
    if (nullCheck.isPresent()) {
      String word = str[5].toLowerCase();
      System.out.print(word);
    } else
      System.out.println("Word is null");
  }
}

Output

Word is null

10. Java Program to print name where salary > 15000 and name starts with “s”

import java.util.*;
import java.util.stream.Collectors;
class Emp {
  private int salary;
  private String name;
  public void setSalary(int salary) {
    this.salary = salary;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getSalary() {
    return this.salary;
  }
  public String getName() {
    return this.name;
  }
  Emp(String name, int salary) {
    this.salary = salary;
    this.name = name;
  }
}
public class Main {
  public static void main(String[] args) {
    List<Emp> list = new ArrayList<Emp>();
    list.add(new Emp("ramesh", 1200));
    list.add(new Emp("suresh", 1400));
    list.add(new Emp("prakash", 1400));
    list.add(new Emp("subhesh", 1300));
    list.add(new Emp("naira", 1100));
    list.add(new Emp("shankar", 1400));
    list.stream().filter(s -> s.getSalary() > 1200 && s.getName().startsWith("s")).forEach(s -> System.out.println(s.getName()));
  }
}

Output

suresh
subhesh
shankar

11). Functional Interfaces in java 8

@FunctionalInterface annotation is introduced in java 8. A interface annotated with @FunctionalInterface is used to ensure that the functional interface can’t have more than one abstract method.

If we define more than one abstract methods in functional interface, the compiler will gives error as ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.

@FunctionalInterface Java 8 Program

@FunctionalInterface
interface Square {
  int calculate(int x);
}
class Main {
  public static void main(String args[])
  {
    int a = 25;
    Square square = (int x) -> x * x;
    int result = square.calculate(a);
    System.out.println(result);
  }
}

Output

625

12. List of Some Built-in Java Functional Interfaces

Some Built-in Java Functional Interfaces that are annotated with @FunctionalInterface is given below : 

  • Runnable –> This interface only contains the run() method.
  • Comparable –> This interface only contains the compareTo() method.
  • ActionListener –> This interface only contains the actionPerformed() method.
  • Callable –> This interface only contains the call() method.

13. What java 8 provides for async calls

Status code of PUT , POST, DELETE, GET

HTTP PUT

PUT means update an existing resource. if resource does not exist then create a new resource or not.

PUT Response Code

  • If a new resource has been created the origin server return HTTP response code <strong>201 </strong>(Created) response.
  • If an existing resource is modified, either the 200 (OK) or 204 (No Content) response sent by server to indicate successful completion of the request.

HTTP POST

HTTP POST Request is used to create new resource.

POST Response code

  • If a resource is created then HTTP response code 201 (Created) .
  • If the action performed by the POST method not result a resource that can be identified by a URI. Then either HTTP response code 200 (OK) or 204 (No Content) is the appropriate response status will be returned by server.

HTTP DELETE

DELETE APIs is used to delete the resources. DELETE operations are idempotent.

DELETE API Response Codes

  • Successful DELETE requests return HTTP response code 200 (OK).
  • If the action has been queued, The status should be 202 (Accepted) .
  • If the action is performed the status should be 204 (No Content).
  • Calling DELETE on a deleted resource will not return 404 (NOT FOUND) since it was already removed.

HTTP GET

HTTP GET is used to retrieve resource representation/information only. GET requests won’t change the state of resource and it is a safe methods.

  • If the resource is found when HTTP GET called, then it must return HTTP response code <a href="https://restfulapi.net/http-status-200-ok/">200 (OK)</a> along with the response body.
  • If no resource found then server must return HTTP response code 404 (NOT FOUND).
  • If the GET request is not formed correctly, then server will return the HTTP response code 400 (BAD REQUEST).

14. Tell some Build tool used for local

There are three main options in the Java build tool market: 

  • Apache Ant with Ivy
  • Apache Maven
  • Gradle

15. Build life cycle of Maven Install

Maven Lifecycle: Below is a representation of the default Maven lifecycle and its 8 steps: Validate, Compile, Test, Package, Integration test, Verify, Install and Deploy.

https://www.geeksforgeeks.org/maven-lifecycle-and-basic-maven-commands/

16. Use of ANT and Gradle

Gradle is a Groovy-based build automation tool. Ant is a Java-based build automation tool. It uses XML files to determine build scripts. Gradle is developed to overcome the drawbacks of Maven and Ant.

17. What is Quality GATE sonar?

Sonarqube which is a code analysis tool, helps us gain visibility into our code base. Soon at MIQ, we realized that having visibility into code was not enough and in order to address the issues flagged by code analysis, we had to make use of different data insights that we were getting from sonarqube.

Few good reasons why this should be included in the development lifecycle

  • It helps in detecting areas in the code that needs refactoring or simplification.
  • It can help to find the bug early in the development cycle, which means less cost to fix them.
  • Overall improvement in the quality of the code.
  • We can define project specific rules which will then be implemented without manual intervention.

11. How to mock private methods using mockito.

Suppose we have a class like

public class Main {
    public void method(boolean b){
          if (b == true)
               method1();
          else
               method2();
    }
    private void method1() {}
    private void method2() {}
}

Here our concern is how to test private method from test class

1). By using reflection, private methods can be called from test classes.

public class TestMain  {
    @Test
    public void testMethod() {
    Main  a= new Main();
    Method privateMethod = Main.class.getDeclaredMethod("method1", null);
    privateMethod.setAccessible(true);
    privateMethod.invoke(Main, null);
    }
}

2). If the private method calls any other private method, then we need to spy the object and stub the another method

public class TestMain  {
  @Test
    public void testMethod() {
    Main a= new Main();
    Main spyA = spy(a);
    Method privateMethod = A.class.getDeclaredMethod("method1", null);
    privateMethod.setAccessible(true);
    doReturn("Test").when(spyA, "method2"); 
    privateMethod.invoke(spyA , null);
    }
}

source : stackoverflow

12. What is circuit breaker?

A circuit breaker is a solution to handle failure in microservices.

These are the three steps to use circuit breaker in spring boot project

  1. Add the springframework.cloud:spring-cloud-starter-hystrix dependency to your build file.
  2. Add the @EnableCircuitBreaker annotation to your main application class (typically the class with the @SpringBootApplication annotation on it).
  3. Annotate with @HystrixCommand the methods in your @Service or @Component classes that you wish to protect.