Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, June 20, 2020

Java Interview @ Polaris

Hi friends,

In this post, I'm sharing interview questions asked in Polaris.


Question 1:

public class Quiz23{

    public static void main(String[] args){

        int x = 0;
        int[] nums = {1,2,3,5};

        for(int i : nums){

            switch(i){

                case 1:
                    x += i;
                case 5:
                    x += i;
                default:
                    x += i;
                case 2:
                    x  += i;

            }
            System.out.println(x);
        }
    }
}

What will be the output of above code?

Answer:

27

Explanation:

For case i = 1:  All the cases will run.
For case i = 2: only case 2 will run.
For case i = 3: Default and case 2 will run.
For case i = 5: case , default and case 2 will run.



Question 2:

What is the difference between Map and FlatMap?

Answer:

Map: Transforms the elements into something else. It accepts a function to apply to each element and returns a new Stream of values returned by the passed function.

It takes function object as the parameter e.g.: Function, ToIntFunction, ToIntDoubleFunction, ToLongFunction.


FlatMap: Combination of Map and Flat operations.So, we first apply map operation on each element and then flattens the result.

So, if function used by Map is returning a single value, then map is ok. But, if function used by Map operation is returning a stream of list or stream of stream, then we need to use flatmap to get stream of values.

For example:

If we have a stream of String containing {"12", "34"} and a method getPermutations() which returns a list of permutations of given string.

When we apply getPermutation() into each string of Stream using map , we get something like [["12","21"], ["34","43"]], but if we use flatMap, we get a stream of strings e.g.: ["12","21","34","43"].

Another example:

List evens = Arrays.asList(2,4,6);
List odds = Arras.asList(3,5,7);
List primes = Arrays.asList(2,3,5,7,11);

List numbers = Stream.of(evens, odds, primes).flatMap(list -> list.stream()).collect(Collectors.toList());

System.out.println("flattened list : "+numbers);

Output: flattened list : [2,4,6,3,5,7,2,3,5,7,11]


 
Question 3:

What is the difference between passing int array and String array to Stream.of()?

Answer:

Stream.of(int[]) gives Stream<int[]>
Stream.of(String[]) gives Stream<String>

So, when using Stream.of() with int[] , we get Stream<int[]> and then for getting ints from Stream, we use flatMapToInt(i -> Arrays.Stream(i)) to get IntStream and then we can either use map() or forEach().

e.g.:

int[] arr = {1,2,3,4};
Stream<int[]> streamArr = Stream.of(arr);
IntStream intStream = streamArr.flatMapToInt(i -> Arrays.Stream(i));
intStream.forEach(System.out :: println);



Question 4:

What is a Boxed Stream?

Answer:

If we want to convert stream of objects to collection:

List<String> strings = Stream.of("how", "to", "do", "in", "java").collect(Collectors.toList());

The same process doesn't work on streams of primitives, however.

//Compilation Error:
IntStream.of(1,2,3,4,5).collect(Collectors.toList());

To convert a stream of primitives, we must first box the elements in their wrapper class and then collect them. This type of stream is called boxed stream.

Example of IntStream to List of Integers:

List<Integer> ints = IntStream.of(1,2,3,4,5).boxed().collect(Collectors.toList());

System.out.println(ints);

Output: [1,2,3,4,5]

 

Question 5:

List Spring Core and Stereotype annotations.

Answer:

Spring Core Annotations:
  • @Qualifier
  • @Autowired
  • @Configuration
  • @ComponentScan
  • @Required
  • @Bean
  • @Lazy
  • @Value

Spring framework Stereotype annotations:
  • @Component
  • @Controller
  • @Service
  • @Repository


Question 6:

What is difference  between @Controller and @RestController?

Answer:

@Controller creates a Map of model object and finds a view for that.
@RestController simply returns the object and object data is directly written into HTTP response as JSON or XML.

@RestController = @Controller + @ResponseBody
@RestController was added in  Spring 4.



Question 7:

Why Spring introduced @RestController when this job could be done by using @Controller and @ResponseBody?

Answer:

The functioning or output of @Controller and @ResponseBody is the default behavior of RESTFUL web services, that's why Spring introduced @RestController which combined the behavior of @Controller and @ResponseBody.  



Question 8:

Tell something about Swagger tools which you have used.

Answer:

Swagger Editor:  Can edit OpenAPI specifications.

Swagger UI : A collection of HTML/CSS/Javascript assets that dynamically generate beautiful documentation.

Swagger Codegen: Allows generation of API client libraries.

Swagger Parser: Library for parsing OpenAPI definitions from java.

Swagger Core: Java related libraries for creating, consuming and working with OpenAPI definitions.

Swagger Inspector: API testing tool

SwaggerHub : Built for teams working with OpenAPI.








That's all for this post.
Thanks for reading!!

Tuesday, June 9, 2020

Java Interview @ Fresher Level - 1


Hi Friends, In this post, I'm writing Java and Android interview questions for freshers:




Question 1:

What is Polymorphism and many types of polymorphism are there?

Answer:

It is one of the OOPS concepts that allows us to perform single action in different ways.
Polymorphism is the capability of a method to do different things based on the object that it is acting upon.

Types of Polymorphism:

  • Runtime Polymorphism or Dynamic Polymorphism [Method Overloading]
  • Compile time polymorphism or static polymorphism [Method Overloading]




Question 2:

What is static binding and dynamic binding?


Answer:

Static binding or Early binding:

The binding which can be resolved at compile time by compiler is known as static or early binding. The binding of static , private and final methods is compile-time. Because these methods can't be overridden and the type of the class is determined at the compile time.

Dynamic binding or Late binding:

When compiler is not able to resolve call/binding at compile time, such binding is known as dynamic binding or late binding. 
Method overriding is the perfect example of dynamic binding.





Question 3:

What are the use of super keyword?

Answer:

The super keyword refers to the object of immediate parent class.

Use of super keyword:

1). To access the data members of parent class when both the child and parent class have member with same name.
2). To explicitly call no-arg and parameterized constructor of parent class.
3). To access the method of parent class when child class has overridden that method.

 

Question 4:

What is the difference between implements Runnable and extends Thread?

Answer:

There are few differences which are described as below:

  • Inheritance Option
  • Loosely-coupled
  • Functions overhead
  • Thread represents "how a thread of control runs". And Runnable represents "what a Thread runs".

Inheritance Option: Means, If class implements Runnable interface, it can extends one class as well. But if class extends Thread, then it cannot extend any other class.

Loosely-coupled: Runnable object can be used in multiple threads. And a Runnable can be changed independently.

Functions Overhead: If we extends Thread class just to run a task, then there will be overhead of all Thread functions.



Question 5:

What is difference between user thread and daemon thread?

Answer:

When we create a thread in java application, it is called user thread.
Daemon thread is a thread that acts as a service provider for other threads running in the same process. e.g. GC.

Daemon thread is terminated by JVM, when there is no other thread running.



Question 6:

Why will we take Daemon thread in our application?

Answer:

If we take a user thread and if it is polling some websites continuously, then if we exit the app, then user thread keeps running and it will not let JVM shutdown.

But, if we make it a daemon thread , then this thread will be terminated by JVM, when there is no other thread running.
  

Question 7:

What do you understand about thread priority?

Answer:

Every thread has a priority. Usually higher priority thread gets precedence in execution , but it depends upon Thread Scheduler implementation that is OS dependent.

We can specify thread priority using setPriority() method. We can use getPriority() method to get priority.

Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.

There are 3 variables defined in Thread class for priority:

  • MIN_PRIORITY
  • NORM_PRIORITY : This is the default priority. It has value 5. Default priority of a thread depends upon priority of parent thread.
  • MAX_PRIORITY

 

Question 8:

What is thread scheduler and time slicing?

Answer:

Thread scheduler is OS service that allocates CPU time to the available threads.
Time slicing is the process of divide the available CPU time to the available runnable threads.


That's all for this post.
Thanks for reading!!

Sunday, June 7, 2020

Java Interview @ Indie Games


Hi Friends,

In this post, I'm sharing java interview questions and answers asked in Indie games.



Question 1:

How do you kill a thread in java?

Answer:

There are two ways to kill a thread:

  • Stop the thread [Deprecated now]
  • Use a volatile variable and running thread will keep checking it's value and return from it's run method in an orderly fashion. 


Question 2:

Why is Thread.stop() deprecated?

Answer:

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked.(The monitors are unlocked as the ThreadDeath exception propagates up the stack.)
If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged.

When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect.

ThreadDeath exception kills thread silently, thus the user has no warning that this program may be corrupted.
 


Question 3:

How to check if a String is numeric in java?

Answer:

We can use Apache Commons Lang 3.4 and 3.5 versions.

StringUtils.isNumeric() or NumberUtils.isParsable().



Question 4:

How can we timeout a thread? I want to run a thread for some fixed amount of time.If it is not completed within that time, I want to either kill it or throw some exception. How to do it?


Answer:

We can use ExecutorService framework of Java 5.

public class Test{

    public static void main(String[] args){

        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<String> future = service.submit(new Task());

        try{

            future.get(4, Timeout.SECONDS);
        }
        catch(Exception e){
            future.cancel(true);
        }

        executor.shutDownNow();
    
    }

}


class Task implements Callable<String>{

    @Override
    public String call() throws Exception{

        Thread.sleep(5000);
        return "";
    }

}


In this code, thread sleeps for 5 seconds, but future will wait for 4 seconds and it will timeout and cancel it.




Question 5:

How to wait for all threads to finish using ExecutorService?

Answer:

We can use shutdown() and awaitTermination() methods of ExecutorService.

ExecutorService service = Executors.newFixedThreadPool(4);

while(...){

    service.execute(new Task());

}    
service.shutdown();
try{
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch(InterruptedException e){

}



Question 6:

Can we create deadlock without thread in java?

Answer:

It is not possible to run the code without atleast one thread. A single thread can block itself in some cases e.g. attempting to upgrade a read lock to a write lock.
When a thread resource starves, it is called a livelock.

It is also possible to create a deadlock without creating an additional thread e.g. the finalizer thread and the main thread can deadlock each other.




That's all for this interview post.

Thanks for reading!!










Monday, April 27, 2020

Java Technical Architect interview @ Tech Mahindra - Round - 1

Hi Friends,

In this post, I'm sharing Technical Architect interview round questions asked in Tech Mahindra.

Kindly also go through my other interview posts:







Question 1:

What are Spring boot actuator endpoints?

Answer 1:

Spring boot actuator is used to monitor and manage application usage in production environment without coding and configuration for any of them.

This monitoring and managing information is exposed via REST like endpoint URL's.

Actuator endpoints:

/env  : Returns list of properties of current environment.

/health : Returns application health information.

/beans : Returns a complete list of all the spring beans in the application.

/trace : Returns trace logs [By default last 100 HTTP requests]

/dump : It performs a thread dump.

/metrics : It shows several useful metrics information like JVM memory usage, CPU usage, open files and much more.

Note: These endpoints can be explicitly enabled/disabled.

If we need to list all endpoints in the browser:
Just run the application and from the browser, use localhost:8080/actuator. It will list 2 endpoints by default : info and health.

For other endpoints, we need to expose them manually.

Now, if we want to explore health endpoint, then just open localhost:8080/actuator/health URL and it will just display "status" : "UP"

We can enable or disable the endpoint from application.properties file:

management.endpoint.shutdown.enabled = true

By default , all the endpoints are enabled except shutdown endpoint.



Question 2:

What is the difference between map and flatmap in java 8?


Answer 2:

map() method is used to map an object or entry from stream to some other value.
flatMap() method on the other hand applies map() on the entries and then flatten the result.

e.g.:

Suppose we have a string array with entries:
String[] strArray = {"12", "46"};

And we have to find all permutations of these strings.
So output with map() method will be: [12, 21] , [46, 64]

While the output with flatMap() method will be : [12, 21, 46, 64]

Lets take another example:

List<Integer> evens = Arrays.asList(2,4,6,8);
List<Integer> odds = Arrays.asList(1,3,5,7);
List<Integer> primes = Arrays.asList(5,7,11,13);

List numbers = Stream.of(evens, odds, primes).flatMap(list-> list.stream()).collect(Collectors.toList());

System.out.println("List = "+numbers);

Note: this output is possible only with flatMap() method.




Question 3:

Explain Spring Data JPA versus Hibernate?


Answer 3:

JPA : Java Persistence API provides specification for creation, deletion, persistence and data management from java objects to relations [tables] in database.

Hibernate : There are various providers which implement JPA. Hibernate is one of them. So , we have other providers as well e.g.: Eclipse Link.

Spring Data JPA: This is another layer on top of JPA which spring provides to make coding easier.




Question 4:

When to use @Component and when to use @Bean?

Answer 4:

@Component is a class level annotation while @Bean is a method level annotation.

@Component is preferable for component scanning and automatic wiring.
Sometimes automatic configuratin is not an option. When? Let's imagine that we want to wire components from 3rd party libraries[where we don't have the source code ,so we can't annotate the class with @Component ], so automatic configuration is not possible.

So, in this case , we should use @Bean.

The @Bean annotation returns an object that spring should register as bean in application context/Spring IOC container. The body of the method bears the logic responsible for creating the instance.

Another difference is that:

@Component does not decouple the declaration of bean from the class definition whereas @Bean decouples the declaration of the bean from the class definition.


There are two ways to create beans:

One is to create a class with an annotation @Component. The other is to create a method and annotate it with @Bean.


@Bean requires the @Configuration annotation on the class in which @Bean is used. Whereas @Component doesn't require the class to be annotated with @Configuration.

Once we run the spring project, the class with @ComponentScan  annotation would scan every class with @Component on it and store the instance of this class to the IOC container.

Another thing , the @ComponentScan would do is , running the methods with @Bean on it and store the returned object to the IOC container as a bean.




Question 5:

Explain the use case with example where @Bean is more beneficial to use than @Component?

Answer 5:

Lets suppose, we want some specific implementation depending on some dynamic state. @Bean is perfect for that case.

@Bean
@Scope("prototype")
public Service anyService(){

    switch(state){
        case 1:
            return new Impl1();

        case 2:
            return new Impl2();

        case 3:
            return new Impl3();

        default:
            return new Impl();
 
    }
}


In the above case, only @Bean can be used , not the @Component.

Note:  We can use both @Component and @Configuration annotations in our same application/module.



Question 6:

Explain the difference between @Service and @Component in Spring.

Answer 6:

@Component is a generic for other stereotypes. 
So, we can replace @Component with @Service, @Repository or @Controller and nothing will change. But for better readability , we should use @Repository, @Service and @Controller.

They all inform spring that the class is involved in the DI context.

In order to configure spring so that it can provide us with the instances of the class we need , we are supposed to tell spring what objects are involved and how they are built. To do this, we can use XML configuration file or java annotations.

They also have semantic meaning:


  • @Controller : @Component belonging to presentation layer
  • @Service : @Component belonging to Service/Use case layer
  • @Repository : @Component belonging to Persistence layer 






That's all for this post.
Hope this post helps everybody in their interviews.

Thanks for reading !!

Friday, March 27, 2020

Technical Architect interview in Incedo - Part - II

Hi Friends,

In this post I'm sharing interview questions-answers from one more interview @ Incedo.

Also go through my other interesting interview posts:




Technical Architect interview in Incedo :


Question 1:

Explain when and why to use Factory Design Pattern.

Answer 1:

Factory Design Pattern is used in following scenarios:


  • When we need to separate  the logic of object creation from our other code or client code.
  • Whenever we need the ability to add more subclasses to the system and modified them without changing the client code.
  • We let subclasses to decide which object to instantiate by overriding the factory method.

UML diagram for Factory Design Pattern is :





Question 2:

Explain when and why to use Abstract Factory Design Pattern.

Answer 2:


Whenever we have to work with two or more objects  which work together forming a set/kit and there can be multiple sets or kits  that can be created by client code, then we will use Abstract Factory Design Pattern.

Lets take an example of a War Game:

Medieval:
  • Land Unit
  • Naval Unit
Industrial:
  • Land Unit
  • Naval Unit

Here , we have two types of objects Land Unit and Naval Unit under Medieval age.
And also two types of objects under Industrial age.

So, we can take two factories : Medieval Age Factory and Industrial Age Factory.

UML Diagram for above scenario is :







Another example we can take is :







Question 3:

When and why to use Generic class? Explain with example. Can we use generics with array?

Answer 3:

A generic type is a type with formal type parameters.

e.g.:

interface Collection<E>{

    public void add(E e);
    public Iterator<E> iterator();

}

A parameterized type is an instantiation of a generic type with actual type arguments.

Example of a parameterized type:

Collection<String> coll = new LinkedList<String>();


Generic class is used when we need to create similar types of object with similar features.

e.g.:

Suppose , we are developing a database library called Data Access Object (DAO) for a program that manages resources in a university.

We would write a DAO class for managing Students like:

public class StudentDAO{

    public void save(Student st){
          // some code here ....
    }

    public Student get(long id){

        // Some code here ...
    }

}

This looks fine. But if we need to persist Professor objects to database. Then we would write another DAO class as:

public class ProfessorDAO{

    public void save(Professor st){
          // some code here ....
    }

    public Professor get(long id){

        // Some code here ...
    }

}

Note: These two classes are same. And if we need to add more entity classes to the system like course, facility etc, then?

So, to avoid such situation ,we write a Generic class:

public class GeneralDAO<T>{

    public void save(T entity){

    }

    public T  get(long id){

    }

}

Here T is called type parameter of GeneralDAO class. T stands for any type. The following code illustrates how to use this generic class:

GeneralDAO<Student> studentDAO = new GeneralDAO<Student>();

Student student = new Student();

studentDAO.save(student);

Note: Type parameters are never added in names of methods and constructors. They are only added in names of classes and interfaces.




Question 4:

What is Type Erasure?

Answer 4:

Generics provide compile time type safety and ensures we only insert correct type in Collection and avoids ClassCastException.

Generics in java are implemented using Type Erasures.

It is a process of enforcing type constraints only at compile time and discarding the element type information at runtime.

There are two types of Type Erasures:


  • Class Type Erasure
  • Method Type Erasure 


e.g.:

public static <E> boolean  containsElement(E[] elements , E element){

    for(E e : elements){

        if(e.equals(element)){
            return true;
        }
    }
    return false;
}

When compiled, the unbound type E gets replaced with an actual type of Object as:

public static  boolean  containsElement(Object[] elements , Object element){

    for(Object e : elements){

        if(e.equals(element)){
            return true;
        }
    }
    return false;
}

The compiler ensures type safety of our code and prevents runtime errors.



Question 5:

Explain Exception handling in java.


Answer 5:

Types of Exceptions:


  • Checked Exceptions
  • Unchecked Exceptions
  • Error

Checked Exception: Exceptions that are directly inherit from Throwable class except RuntimeException and Error are known as checked exceptions.


Unchecked Exceptions: The classes which inherit RuntimeException are known as unchecked exception.








Question 6:

What is static import in java? How to use it?

Answer 6:

Static import allows developers to access static members of a class directly.There is no need to qualify it by the class name.

Example:

import static java.lang.System.*;

class StaticImport{

    public static void main(String[] args){

        out.println("Ok"); // No need to use System.out
        out.println("Java");
    }

}

O/P:

Ok
Java



That's all for this post.

Hope these interview questions help everybody.

Thanks for reading !!



Saturday, March 14, 2020

Technical Architect interview in Incedo - Part - I

Hi friends,

In this post, I'm sharing Techincal architect interview questions-answers asked in Incedo.

You can also go through other interviews posts here:





Question 1:

What is database sharding? Why we need database sharding?


Answer:

Sharding involves breaking up one's data into two or more smaller chunks, called logical shards. The logical shards are then distributed across separate database nodes, referred to as physical shards, which can hold multiple logical shards.

Sharding is a method of splitting and storing a single logical dataset in multiple databases.
Sharding adds more servers to a database and automatically balances data and load across various servers. These databases are called shards.


Sharding is also referred as horizontal partitioning. The distinction of horizontal vs vertical comes from the traditional tabular view of a database. 




Question 2:

What are the types of database sharding?

Answer:


A database can be split vertically — storing different tables & columns in a separate database, or horizontally — storing rows of a same table in multiple database nodes.













Example of Vertical partitioning:

fetch_user_data(user_id) -> db["USER"].fetch(user_id)
fetch_photo(photo_id) -> db["PHOTO"].fetch(photo_id)

Example of Horizontal partitioning:

fetch_user_data(user_id) -> user_db[user_id % 2].fetch(user_id)


Vertical sharding is implemented at application level – A piece of code routing reads and writes to a designated database.
Natively sharded DB’s are : Cassandra, MongoDB

Non-sharded DB’s are : Sqlite, Memcached etc.


When we need to do sharding?

Answer:

·         When the data set outgrows the storage capacity of a single MongoDB instance.
·         When a single MongoDB instance is unable to manage write operations.




Question 3:

How to implement sharding in MongoDB?

Answer:


When deploying sharding, we need to choose a key from a collection and split the data using the key's value.

Task that the key performs:


  • Determines document distribution among the different shards in a cluster.




Choosing the correct shard key:

To enhance and optimize the performance, functioning and capability of the DB, we need to choose the correct shard key.


Choosing correct shard key depends on two factors:

  •          The schema of the data
  •          The way database applications query and perform write operations.



Using range-based Shard key:

In range-based sharding, MongoDB divides data sets into different ranges based on the values of shard keys. In range-based sharding, documents having "close" shard key values reside in the same chunk and shard.







Data distribution in range-based partitioning can be uneven, which may negate some benefits of sharding.

For example, if a shard key field size increases linearly, such as time, then all requests for a given time range will map to the same chunk and shard. In such cases, a small set of shards may receive most of the requests and system would fail to scale.


Hash-based sharding:

In this , MongoDB first calculates the hash of a field’s value and then creates chunks using those values. In this sharding, collections in a cluster are randomly distributed.

No real schema is enforced:
  •          We can have different fields in every document if we want to.
  •          No single key as in other databases:

o   But we can create indices on any fields we want, or even combinations of fields.
o   If we want to shard, then we must do so on some index.






Question 4:

What is the use of Amazon EC2? What are the steps to deploy on EC2?

Answer:

Amazon EC2 : Amazon Elastic Compute Cloud

It offers ability to run applications on the public cloud.

It eliminates investment for hardware. There is no need to maintain the hardware. We can use EC2  to launch as many virtual servers as we need.

Steps to deploy on EC2:

·         Launch an EC2 instance and SSH into it. Note: This instance needs to be created first on AWS console[console.aws.amazon.com]. And we should also have certificate to connect to EC2 instance.

·         Install Node on  EC2 instance, if our app is in Angular.

·         Copy paste code on EC2 instance and install dependencies.

·         Start server to run.


OR:

  •          Build out Spring boot app in our own computer. Make .jar file.
  •          Upload this .jar on S3
  •          Create EC2 instance.
  •          SSH into it from our computer.
  •          Now, we are in EC2 instance.
  •          We can install JDK now.
  •          And using java - .jar file path, we can run our application.





Question 5:

How will we use Amazon S3?

Answer:

For using S3, we need to first choose S3 from AWS console and then we need to create a bucket in that for storing our files.

After creating the bucket, we need to click on the upload option and select jar file or any file from our computer and upload it to S3.

While uploading file to S3, we need to provide it some access level so that we can download it from S3 to EC2 instance.

So before that we need to make EC2 instance up and running.
And then we need to connect from local to EC2 instance using private key that we have. For connecting to EC2, we need to do SSH login [from terminal] using some certificate and using some SSH command.

Now we need to install java on EC2 [As , it is not there by default]. After that we can download our jar file from S3 to EC2 instance.

Now just run this jar using java -jar <filename> to run the springboot application.




Question 6:

What are the best Code Review Practices?

Answer:


Clean Code
·         Use intention-revealing names
·         Use Solution-Problem domain names
·         Classes should be small
·         Functions should be small
·         Functions should do one thing
·         Don’t repeat yourself(Avoid duplication)
·         Explain yourself in code : Comments
·         Use Exceptions rather than return codes
·         Don’t return Null



Security
·         Make class final if not being used for inheritance
·         Avoid duplication of code
·         Minimize the accessibility of classes and members
·         Document security related information
·         Input into a system should be checked for valid data size and range
·         Release resources (Streams, Connections) in all cases
·         Purge sensitive information from exceptions
·         Don’t log highly sensitive information
·         Avoid dynamic SQL, use prepared statement
·         Limit the accessibility of packages, classes, interfaces, methods and fields
·         Avoid exposing constructors of sensitive classes
·         Avoid serialization of sensitive classes
·         Only use JNI when necessary




Performance
·         Avoid excessive synchronization
·         Keep synchronized sections small
·         Beware the performance of String concatenations
·         Avoid creating unnecessary objects

General
·         Don’t ignore exceptions
·         Return empty arrays or collections , not nulls
·         In public classes, use accessor methods not public fields
·         Avoid finalizers
·         Refer to objects by their interfaces
·         Always override toString()
·         Document thread safety
·         Use marker interfaces to define types

Static Code Analysis

·         Check static code analyzer report for the classes added/modified



Question 7:

What are the types of Http Error codes?

Answer:

There are 5 types of Error codes:

1XX Informational:

100: Continue


2XX Success:

200 : OK
201 : Created
202 : Accepted
204 : No Content


3XX Redirection:


4XX Client Error:

400 : Bad Request
401 : Unauthorized
402 : Payment Required
403 : Forbidden
404 : Not Found


5XX Server Error:

500 : Internal Server Error
501 : Not Implemented
502 : Bad Gateway
503 : Service Unavailable [Website's server is simply not available]



Question 8:

What are the Asymptotic Notations?

Answer:

To calculate running time complexity of an algorithm, we use following asymptotic notations:





Big Oh Notation O:

The notation O(n) is the formal way to express the upper bound of an algorithm's running time.
It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete.




For example, for a function f(n)

O(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) <= c.g(n) for all n > n0. }



Omega Notation:

The Omega notation is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of time an algorithm can possibly take to complete.




For example, for a function f(n)






Theta Notation:

The notation theta (n) is the formal way to express both the lower bound and upper bound of an algorithm's running time.It is represented as follows:


    





That's all for this interview post.
Hope this post helps everybody in their java Technical interviews.

Thanks for reading!!


CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...