Showing posts with label interview. Show all posts
Showing posts with label interview. Show all posts

August 01, 2021

Google Cloud questions and explanation

 Question: What is GAE and GCE in GCP?

Solution : Google App Engine (GAE) and Google Compute Engine (GCE) are both used for deploying applications and are equally popular with small and large businesses. Google App Engine is a Platform as a Service (PaaS) solution that makes deployment easier.The Google Compute Engine on the other hand is an Infrastructure as a Service (IaaS) tool.


Question: PaaS vs IaaS: What’s the Difference?

Solution : PaaS refers to cloud-based platform services that provide developers with a framework to build custom applications. Therefore, PaaS isn’t delivering software over the internet but provides a platform that’s accessible to different developers to create software that’s delivered over the internet.

IaaS cloud-based infrastructure resources are delivered to organizations with virtualization technology that helps them build and manage their servers, network, data storage and operating systems. IaaS customers can control their own data infrastructure without having to physically manage it on-site.


Reference: https://www.parallels.com/blogs/ras/app-engine-vs-compute-engine/


Question: What are the cloud databases in GCP?

Solution:

Relational

  Bare Metal Solution for Oracle(Lift and shift Oracle workloads to Google Cloud),

  Cloud SQL(Managed MySQL, PostgreSQL, and SQL Server),  

Cloud Spanner(Cloud-native with unlimited scale, consistency, and 99.999% availability)

Key value

Cloud Bigtable(Cloud-native NoSQL wide-column store for large scale, low-latency workloads)

Document

  Firestore(Cloud-native NoSQL to easily develop rich mobile, web, and IoT applications)

Firebase Realtime Database(Store and sync data in real time)

In-memory

Memorystore(Fully managed Redis and Memcached for sub-millisecond data access)

Additional NoSQL

MongoDB Atlas(Global cloud database service for modern applications)

Google Cloud Partner Services(Managed offerings from our open source partner network, including MongoDB, Datastax, Redis Labs, and Neo4j)

Reference: https://cloud.google.com/products/databases

Read more ...

Spring Boot question and explanations

 Question: What is diff BeanFactory and ApplicationContextFactory?

Solution:

The Spring Framework comes with two IOC containers – BeanFactory and ApplicationContext. The BeanFactory(Lazy Loading is the most basic version of IOC containers, and the ApplicationContext ( Eager Loading) extends the features of BeanFactory.BeanFactory loads beans on-demand, while ApplicationContext loads all beans at startup. 

Ex:  

Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); 

Student student = (Student) factory.getBean("student");

Or 

ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml");

Reference: https://www.baeldung.com/spring-beanfactory-vs-applicationcontext

 

Question: What Is Spring Security?

Solution:

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.

For more information, we have a whole series of articles related to security.

Question: Name Some of the Design Patterns Used in the Spring Framework?

Solution:

  • Singleton Pattern – singleton-scoped beans
  • Factory Pattern – Bean Factory classes
  • Prototype Pattern – prototype-scoped beans
  • Adapter Pattern – Spring Web and Spring MVC
  • Proxy Pattern – Spring Aspect-Oriented Programming support
  • Template Method Pattern – JdbcTemplateHibernateTemplate, etc.
  • Front Controller – Spring MVC DispatcherServlet
  • Data Access Object – Spring DAO support
  • Model View Controller – Spring MVC

Reference: https://www.baeldung.com/spring-interview-questions

 

Question: Spring WebFlux?

Solution:

The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux



Question: Spring REST – HTTP OPTIONS Request Handler Example

Solution:

HTTP OPTIONS Method

The HTTP OPTIONS method is used to describe the communication options for the target resource. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

  • If the Request-URI is an asterisk (“*”), the OPTIONS request is intended to apply to the server in general rather than to a specific resource.
  • If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
  • Responses to this method are not cacheable.


@RequestMapping(value="/buckets", method = RequestMethod.OPTIONS)

    ResponseEntity<?> collectionOptions() 

    {

         returnResponseEntity

                 .ok()

                 .allow(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)

                 .build();

    }

 

Reference: https://howtodoinjava.com/spring-rest/http-options-request-handler/


Question: Spring – Inversion of Control vs Dependency Injection

Solution:

What is Inversion of Control (IoC)

In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection, although some argue that the use of a service locator also provides inversion of control.

Inversion of control as a design guideline serves the following purposes:

  1. There is a decoupling of the execution of a certain task from implementation.
  2. Every module can focus on what it is designed for.
  3. Modules make no assumptions about what other systems do but rely on their contracts.
  4. Replacing modules has no side effect on other modules.

What is Dependency Injection (DI)

IoC is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done. While Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. IoC relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.

How to implement IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    • a constructor injection
    • a setter injection
    • an interface injection

Inversion of control in Spring

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in we

Reference: https://stackoverflow.com/questions/3715967/when-should-we-call-system-exit-in-java


Question: What  is System.exit()?

Solution:

The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.

Following is the declaration for java.lang.System.exit() method:

public static void exit(int status)

exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination.


Additional info:

System.exit(0);

System.out.println("This line will never be reached");


System.exit(0) terminates the JVM. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.

System.exit(42)  == A script that called the application. Works in Windows, Unix and all other scriptable environments.


Reference: https://www.geeksforgeeks.org/system-exit-in-java/


Question: What is spring bean lifecycle?

Solution:


Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed

  

Reference: https://www.geeksforgeeks.org/bean-life-cycle-in-java-spring/

https://reflectoring.io/spring-bean-lifecycle/


Question: Error Handling for REST with Spring  or Spring Boot @ControllerAdvice

Solution:

There are couple of ways to handle exception in springbok

Solution 1: the Controller-Level @ExceptionHandler

Solution 2: the HandlerExceptionResolver

Solution 3: @ControllerAdvice

Solution 4: ResponseStatusException (Spring 5 and Above)

Handle the Access Denied in Spring Security


Default Spring Boot Support exception messages:

In a nutshell, it serves a fallback error page for browsers (a.k.a. the Whitelabel Error Page) and a JSON response for RESTful, non-HTML requests:

{

    "timestamp": "2019-01-17T16:12:45.977+0000",

    "status": 500,

    "error": "Internal Server Error",

    "message": "Error processing the request!",

    "path": "/my-endpoint-with-exceptions"

}


Using @ControllerAdvice:

  • SpringBoot @ControllerAdvice tutorial shows how to use @ControllerAdvice annotation to manage exceptions in a Spring Boot application.
  • @ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.
  • ResponseEntityExceptionHandler is a convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. It provides an methods for handling internal Spring MVC exceptions. It returns a ResponseEntity in contrast to DefaultHandlerExceptionResolver which returns a ModelAndView.


Using the Controller-Level @ExceptionHandler:

The first solution works at the @Controller level. We will define a method to handle exceptions and annotate that with @ExceptionHandler:

public class FooController{

    //...

    @ExceptionHandler({ CustomException1.class, CustomException2.class })

    public void handleException() {

        //

    }

}

Reference: https://zetcode.com/springboot/controlleradvice/

https://www.baeldung.com/exception-handling-for-rest-with-spring


Read more ...

Core Concepts and Brief Explanation



Question : Why to Override equals(Object) and hashCode() method ?
Solution: HashMap and HashSet use the hashcode value of an object to find out how the object would be stored in the collection, and subsequently hashcode is used to help locate the object in the collection. Hashing retrieval involves:
  1. First, find out the right bucket using hashCode().
  1. Secondly, search the bucket for the right element using equals()
Reference: https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/
  
Question : Strategy design pattern


Solution: The strategy pattern is a Behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.




Question: Advantages of MongoDB are as follows:

Solution:

  • MongoDB supports field, range-based, string pattern matching type queries. for searching the data in the database 
  • MongoDB support primary and secondary index on any fields
  • MongoDB basically uses JavaScript objects in place of procedures
  • MongoDB uses a dynamic database schema
  • MongoDB is very easy to scale up or down
  • MongoDB has inbuilt support for data partitioning (Sharding).

Reference: https://www.interviewbit.com/mongodb-interview-questions/

 

Question: Write program: get the employee salary > 10000 rupees in the provided list

Solution:

packagecom.test; 

importjava.util.*;

importjava.util.stream.Collectors;

 

publicclassTestEmployee {

        publicstaticvoidmain(String... args) {

                List<Employee> empList= newArrayList<>();

                empList.add(newEmployee("test1", 1235));

                empList.add(newEmployee("test2", 12353));

                empList.add(newEmployee("test3", 12352));

                empList.add(newEmployee("test4", 12345));

                empList.add(newEmployee("test5", 1235));

                List<String> resEmpList= empList.stream().filter(e-> e.getSalary() > 10000).map(e-> e.getName())

                                .collect(Collectors.toList());

                resEmpList.stream().forEach(System.out::println);

        }

}

 

classEmployee {

        privateString name;

        privateInteger salary;

        publicString getName() {

                return name;

        }

        publicvoidsetName(String name) {

                this.name= name;

        }

        publicInteger getSalary() {

                return salary;

        }

        publicvoidsetSalary(Integer salary) {

                this.salary= salary;

        }

        publicEmployee(String name, Integer salary) {

 

                this.name= name;

                this.salary= salary;

        }

}



Question: What is docker?

Solution:

Docker is a very popular and powerful open-source containerization platform that is used for building, deploying, and running applications. Docker allows you to decouple the application/software from the underlying infrastructure.

In order to get the status of all the containers, we run the below command:  

docker ps -a


docker save command and the syntax is: 

docker save -o <exported_name>.tar <container-name>


docker load command and the syntax is 

docker load -i <export_image_name>.tar

 

There are three docker components, they are - Docker Client, Docker Host, and Docker Registry.

  • Docker Client: This component performs “build” and “run” operations for the purpose of opening communication with the docker host.
  • Docker Host: This component has the main docker daemon and hosts containers and their associated images. The daemon establishes a connection with the docker registry.
  • Docker Registry: This component stores the docker images. There can be a public registry or a private one. The most famous public registries are Docker Hub and Docker Cloud.

Reference: https://www.interviewbit.com/docker-interview-questions/


 

Question: What is Thread life Cycle?

Solution:

The java.lang.Thread class contains a static State enum – which defines its potential states. During any given point of time, the thread can only be in one of these states:

  1. NEW – a newly created thread that has not yet started the execution
  2. RUNNABLE – either running or ready for execution but it's waiting for resource allocation
  3. BLOCKED – waiting to acquire a monitor lock to enter or re-enter a synchronized block/method
  4. WAITING – waiting for some other thread to perform a particular action without any time limit
  5. TIMED_WAITING – waiting for some other thread to perform a specific action for a specified period
  6. TERMINATED – has completed its execution 

Reference: https://www.baeldung.com/java-thread-lifecycle

 

Question: What is Hibernate Lifecycle?

Solution:

There are mainly four states of the Hibernate Lifecycle :

  1. Transient State
  2. Persistent State
  3. Detached State
  4. Removed State

Reference: https://www.geeksforgeeks.org/hibernate-lifecycle/

 


Read more ...

July 27, 2021

Interview learning process flow: It may help for the charts using coggle









Reference: https://coggle.it/diagram/YP-O2iqjIO9jM8Up/t/master-the-interview

 

Read more ...

August 22, 2017

Few java basic understanding interview questions and answers



JVM architecture in Java and the different components of the JVM.

What is the JVM?
Virtual Machine is a software implementation of a physical machine. Java was developed with the concept of WORA (Write Once Run Anywhere), which runs on a VM. Thecompiler compiles the Java file into a Java .class file, then that .class file is input into the JVM, which Loads and executes the class file. Below is a diagram of the Architecture of the JVM.
JVM Architecture Diagram:
How Does the JVM Work?
As shown in the above architecture diagram, the JVM is divided into three main subsystems:
  1. Class Loader Subsystem
  2. Runtime Data Area
  3. Execution Engine
1. Class Loader Subsystem
Java's dynamic class loading functionality is handled by the class loader subsystem. It loads, links. and initializes the class file when it refers to a class for the first time at runtime, not compile time. 
1.1 Loading
Classes will be loaded by this component. Boot Strap class Loader, Extension class Loader, and Application class Loader are the three class loader which will help in achieving it.
  1. Boot Strap ClassLoader – Responsible for loading classes from the bootstrap classpath, nothing but rt.jar. Highest priority will be given to this loader.
  2. Extension ClassLoader – Responsible for loading classes which are inside ext folder (jre\lib).
  3. Application ClassLoader –Responsible for loading Application Level Classpath, path mentioned Environment Variable etc.
The above Class Loaders will follow Delegation Hierarchy Algorithm while loading the class files.
1.2 Linking
  1. Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if verification fails we will get the verification error.
  2. Prepare – For all static variables memory will be allocated and assigned with default values.
  3. Resolve – All symbolic memory references are replaced with the original referencesfrom Method Area.
1.3 Initialization
This is the final phase of Class Loading, here all static variables will be assigned with the original values, and the static block will be executed.
2. Runtime Data Area
The Runtime Data Area is divided into 5 major components:
  1. Method Area – All the class level data will be stored here, including static variables. There is only one method area per JVM, and it is a shared resource.
  2. Heap Area – All the Objects and their corresponding instance variables and arrays will be stored here. There is also one Heap Area per JVM. Since the Method and Heap areas share memory for multiple threads, the data stored is not thread safe.
  3. Stack Area – For every thread, a separate runtime stack will be created. For every method call, one entry will be made in the stack memory which is called as Stack Frame. All local variables will be created in the stack memory. The stack area is thread safe since it is not a shared resource. The Stack Frame is divided into three subentities:
    1. Local Variable Array – Related to the method how many local variables are involved and the corresponding values will be stored here.
    2. Operand stack – If any intermediate operation is required to perform, operand stackacts as runtime workspace to perform the operation.
    3. Frame data – All symbols corresponding to the method is stored here. In the case of any exception, the catch block information will be maintained in the frame data.
  4. PC Registers – Each thread will have separate PC Registers, to hold the address of current executing instruction once the instruction is executed the PC register will be updated with the next instruction.
  5. Native Method stacks – Native Method Stack holds native method information. For every thread, a separate native method stack will be created.
3. Execution Engine
The bytecode which is assigned to the Runtime Data Area will be executed by the Execution Engine. The Execution Engine reads the bytecode and executes it piece by piece.
  1. Interpreter – The interpreter interprets the bytecode faster, but executes slowly. The disadvantage of the interpreter is that when one method is called multiple times, every time a new interpretation is required.
  2. JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The Execution Engine will be using the help of the interpreter in converting byte code, but when it finds repeated code it uses the JIT compiler, which compiles the entire bytecode and changes it to native code. This native code will be used directly for repeated method calls, which improve the performance of the system.
    1. Intermediate Code generator – Produces intermediate code
    2. Code Optimizer – Responsible for optimizing the intermediate code generated above
    3. Target Code Generator – Responsible for Generating Machine Code or Native Code
    4. Profiler – A special component, responsible for finding hotspots, i.e. whether the method is called multiple times or not.
  3. Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be triggered by calling "System.gc()", but the execution is not guaranteed. Garbage collection of the JVM collects the objects that are created.
Java Native Interface (JNI)JNI will be interacting with the Native Method Libraries and provides the Native Libraries required for the Execution Engine.
Native Method Libraries:It is a collection of the Native Libraries which is required for the Execution Engine.


Few of the basic java interview questions:
Language-Fundamentals

Reference website:
Intellipaat
Indiabix
Placement.Freshersworld
JVM-architecture-explained
Read more ...

My Favorite Site's List

#update below script more than 500 posts