Sunday, 10 September 2023

Java Most asked Coding/Programming Interview Questions

1. Find the first non-repeating character in a string.

package com.javaforsomeone.example;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

class Main {

    public static void main(String[] args) {
	  String name = "this is the java coding test";
	  firstNonRepeated(name);
	}

	public static void firstNonRepeated(String k) {

	Map hMap = new LinkedHashMap();
	for (char data : k.toCharArray()) {

		if (hMap.containsKey(data)) {
			hMap.put(data, hMap.get(data) + 1);
		} else {
			hMap.put(data, 1);
		}
	}
	Set data = hMap.keySet();
	for (Character a : data) {
	  if (hMap.get(a) == 1) {
		  System.out.println("First Non 
		  Repeated Character is " + a);
		  break;
	  }
	}

	}

}

Output: First Non Repeated Character is j

  

2. The sum of largest contiguous subarray.

package com.javaforsomeone.example;

public class Main {

	public static void main(String[] args) {

	  int[] arr = { -2, 1, -3, 4, -1, 2 };

	  System.out.println("The sum of contiguous subarray with the " 
	  + "largest sum is " + testMaxSum(arr));
	}

	private static Integer testMaxSum(int[] arr) {

	  int maxSum = 0;
	  int currentSum = 0;
	  for (Integer k : arr) {
	    currentSum = currentSum + k;
	    if (currentSum > maxSum) {
		    maxSum = currentSum;
	       } else if (currentSum < 0) {
		     currentSum = 0;
           }
		}
		return maxSum;
	}

}

Output: The sum of contiguous subarray with the largest sum is 5

  

3. Write a program to delete the Mid element from the Stack.

package com.javaforsomeone.example;

import java.util.Stack;

public class Main {

	public static void main(String[] args) {
		
		Stack stack=new Stack();
		stack.push('A');
		stack.push('B');
		stack.push('C');
		stack.push('D');
		stack.push('E');
		System.out.println("The Stack after the deletion 
		of Mid Element "+deleteMid(stack));

	}
	
	public static Stack deleteMid(Stack st){
		
		int n=st.size();
		Stack tempStack =new Stack();
		int count=0;
		while(count<n/2) {
			char c =st.peek();
			st.pop();
			tempStack.push(c);
			count++;
		}
		st.pop();
		while(!tempStack.empty())
		{
			st.push(tempStack.peek());
			tempStack.pop();
		}
		return st;
	}

}

Output: The Stack after the deletion of Mid Element [A, B, D, E]
  

Sunday, 3 September 2023

Capco Java Interview Questions and answers

 Capco Java Interview questions and answers

1. Can you explain your roles and responsibilities in your current project.

2.  What are the coding advantages we have in coding using Java 8 over other below Java 8 versions
  • Functional Interfaces 
  • Lambda Expressions
  • forEach() Method In Iterable Interface
  • Optional Class
  • Default And Static Methods In Interfaces
  • Java Stream API For Bulk Data Operations On Collections
  • Java Date Time API
  • Collection API Improvements
  • Java IO Improvements
  • Miscellaneous Core API Improvements
  • Base64 Encode Decode
3. Give me an Example of you used Java 8 features in your project and significant advantage of it

4. Take a scenario of employee class has employee name, salary, manager attributes and we want to filter employee based on salary, later after some days we tell you to filter using employee name starting with some character. How would you design this class.

5. What do you mean by Dependency Injection?

6. How does Dependency Injection make the code loosely coupled?

7. Is it possible to do what Spring is doing like Dependency Injection by our self without using Spring?

















Sunday, 5 July 2020

Java Interview questions

Top 50 Java Interview Questions and Answers

1. Difference between Hash map, Concurrent Hash map and Synchronized Hash map?

2. What is IdentityHashMap?

3. What is Concurrent Modification exception?

4. What is Spring boot Actuator?

5. How does Hash Map works in java?

6. Difference between Comparable versus Comparator?

7. What is difference between sleep and yield method in threads?

8. How to Sort Map using value?

9. Explain Design Patterns used in your applications?

10. How do we create a singleton class, Singleton design pattern snippet?

11. What is load factor, Threshold, initial/default capacity of Collection Elements?

12. What is covariant return type in java?

13. Different kinds of spring bean scopes?

14. contract between equals and hashcode?

15. how to create immutable class in java?

16. How does HashSet Work?

17. what is the difference between Log4j 1 and log4j 2?

18. Optimistic and Pessimistic Locking in Hibernate?

19. How can we create a Cache and cache in spring boot?

20. What is Second level cache in Hibernate?

21. Difference between topic versus queue?

22. What happens when JMS server crash what happens to the queue Web logic server?

23. Any other methods required in comparable implementation?

24. Read property from property file in a class?

25. Write a program to print something but should not execute PSVM?

26. What annotations we have in Entity classes?

27. Giving Class not found exception in spring boot?

28. How we do validation in spring?

29. Two classes implement same Interface and how do we create reference of 1 class in spring(not use new keyword)?

30. How do you do your db connections in property files?

31. Explain SOLID principles?

32. What is Co-relation id in micro services?

33. How do we monitor micro services?

34. How objects converted to json in restful web services?

35. What is Volatile and where it is used?

36. Where you do database configuration in Spring boot?

37. Why set does not allow duplicates – reason?

38. How do we Configure classes in Spring boot?

39. what is the difference between component, bean, Services, Repository?

40. How you configured jdbc template in Springboot?

41What changes required to deploy spring boot as war file in Server?

42How to Iterate over hash set?

43. JPA how you write a query in JPA

44. what is the difference between RestController and controller?

45. what are default methods in interface added in Java 8?

46. When String created using new, "", where it will be present in heap or string pool?

47. what new features are there in java 8?

48.Does toUpper. toLower creates new string object or not?

49. Serializable interface is a marker interface

50What is Static synchronization & non static synchronization?

                Answers for the above Questions

1. Difference between Hash Map, Concurrent Hash Map, Hash Table and Synchronized Hash Map.

Concurrent Hash Map: is a concurrent version of the standard class, which allows the concurrent modification of a map by multiple threads. It works by locking the bucket, which is being updated while other buckets are free to be accessed by other threads.

Synchronized HashMap is HashMap version with full synchronization

Collections.SynchronizedMap() locks the entire table which blocks parallel access for multiple threads. In other words, only one thread can access the map at a time which ultimately leads to the poor performance.

Concurrent Hash Map and Hash table does not permit null keys or values, whereas the behavior of  depends on the backing map. So if null keys and values is required, Hash Map can be used.

1) As I said the earlier first significant difference between HashMap and ConcurrentHashMap is that later is thread-safe and can be used in a concurrent environment without external synchronization. Though it doesn't provide the same level of synchronization as achieved by using Hashtable but it's enough for the most practical purpose.

2) You can make HashMap synchronized by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object while in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.

3) ConcurrentHashMap is more scalable and performs better than Synchronized HashMap in the multi-threaded environment while in Single threaded environment both HashMap and ConcurrentHashMap gives comparable performance, where HashMap only slightly better.



2. What is IdentityHashMap?

IdentityHashMap in Java was added in Java 1.4 but still it's one of those lesser known class in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses equality operator "=="  to compare keys and values in Java which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality.

3. What is Concurrent Modification exception.

ConcurrentModificationException is a very common exception when working with Java collection classes. Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the iterator. next() will throw ConcurrentModificationException.

4. What is Spring boot Actuator?

Spring Boot Actuator - Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. This module helps you monitor and manage your Spring Boot application by providing production-ready features like health check-up, auditing, metrics gathering, HTTP tracing etc.

http://localhost:8080/env

This will give all the environmental configuration about the server.

http://localhost:8080/beans

This will give all the spring beans loaded in the context.

http://localhost:8080/health

This will give generic health of the application and server.

http://localhost:8080/metrics

The /metrics endpoint lists all the metrics that are available for you to track

5.    How does Hash Map works in java

It uses a technique called Hashing.

Hashing.

It is the process of converting an object into an integer value. The integer value helps in indexing and faster searches.

It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.

Before understanding the internal working of HashMap, you must be aware of hashCode() and equals() method.

  • equals(): It checks the equality of two objects. It compares the Key, whether they are equal or not. It is a method of the Object class. It can be overridden. If you override the equals() method, then it is mandatory to override the hashCode() method.
  • hashCode(): This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.
  • Buckets: Array of the node is called buckets. Each node has a data structure like a LinkedList. More than one node can share the same bucket. It may be different in capacity.

Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap. The default size of HashMap is 16 (0 to 15).

6.    Comparator versus comparable

To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.

Comparable.compareTo(Object o) method implementation can provide default sorting and we can’t change it dynamically. Whereas with Comparator, we can define multiple methods with different ways of sorting and then choose the sorting method based on our requirements

  • sort(List list): It sorts the elements of the List in ascending order of their natural order.
  • sort(List list, Comparator <T>): It sorts the elements of the list according to the order included by the comparator.

7.     Difference between sleep and yield?

  • Sleep - The Java Thread. sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds.
  • Yield - It causes to pause the currently executing thread to give the chance for waiting thread of same priority.

8.    Sort Hash Map by value

Convert map into List and Sort using Comparator

package com.javaforsomeone.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    public static void main(String[] args) {
        HashMap map = new HashMap<>();
        LinkedHashMap sortedMap = new LinkedHashMap<>();
        ArrayList list = new ArrayList<>();
        map.put("2", "B");
        map.put("8", "A");
        map.put("4", "D");
        map.put("7", "F");
        map.put("6", "W");
        map.put("19", "J");
        map.put("1", "Z");

        for (Map.Entry entry : map.entrySet()) {
            list.add(entry.getValue());
        }

        Collections.sort(list, new Comparator() {
            public int compare(String str, String str1) {
                return (str).compareTo(str1);
            }
        });

        for (String str : list) {
            for (Entry entry : map.entrySet()) {
                if (entry.getValue().equals(str)) {
                    sortedMap.put(entry.getKey(), str);
                }
            }
        }
        System.out.println(sortedMap);
    }
}
Output :

{8=A, 5=B, 3=D, 7=F, 10=J, 2=W, 1=Z}

9.   Explain Design Patterns in Java?

Based on how they are to be used, patterns are primarily categorized as:

·         Creational

·         Structural

·         Behavioral

 

Creational

Creational patterns define mechanisms for instantiating objects. The implementation of the creational pattern is responsible for managing the lifecycle of the instantiated object. A few examples of Creational design patterns are listed below.

Factory

One of the easily recognized and frequently used design patterns is the Factory pattern. If you have designed any object that is responsible for creating and maintaining the lifecycle of another object, you have used the Factory pattern. Obtaining a database connection in your application using a connection manager or connection factory object is a good example of the Factory pattern.



Figure 1. Factory pattern

Singleton

A singleton is another example of a factory pattern. What makes the Singleton pattern unique is that one and only one instance of the object can exist irrespective of the number of times the object is instantiated. The most common use of a Singleton pattern is for server applications like a Java based Remote Method Invocation (RMI) server application.



Figure 2. Singleton pattern

Structural

 

The composition of objects and their organization to obtain new and varied functionality is the underlying basis of Structural patterns. A few examples of Structural design patterns are listed below.

Adapter

In the Adapter pattern, an object provides an implementation of an interface used by other objects in a consistent way. The adapter object wraps different disparate implementations of the interface and presents a unified interface for other objects to access. A good example of this is a database driver like an ODBC (Open Database Connectivity) or JDBC (Java Database Connectivity) driver that wraps the custom database accessing implementation for different databases and yet, presents a consistent interface that is a published and standardized API.



Figure 3. Adapter pattern

Proxy

A Proxy pattern constitutes use of proxy objects during object interaction. A proxy object acts as a substitute for the actual object. Use of proxy objects is prevalent in remote object interaction protocols. As an example, when an object needs to interact with a remote object, say across a network, the most preferred way of encapsulating and hiding the interaction mechanism is by using a proxy object that mediates communication between the requesting object and the remote object.

RMI



Figure 4. Proxy pattern

Behavioral

 

Interaction between different objects is specifically covered by Behavioral patterns. Some examples of behavioral patterns are given below.

Observer pattern
This design pattern falls under behavioral pattern category.

The Observer (Publish/Subscribe) Design Pattern

The Observer pattern is used to notify dependent observer (subscriber) objects that state information has changed in the subject (topic). The intent is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

The object interaction diagram for the Observer design pattern is shown in the figure below:

The Observer objects are dependent on the Subject object and therefore should be notified of any change in its state. There's no reason, to limit the number of objects to two — there may be any number of Observers for the same subject.

The Observer pattern, also known as the Publish/Subscribe or the Dependents pattern, describes how to establish these relationships. All observers are notified whenever the subject undergoes a change in state. In response, each observer synchronizes its state with the subject's state. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.

Command

The Command pattern is commonly used for gathering requests from client objects and packaging them into a single object for processing. The Command pattern allows for having well defined command interfaces that are implemented by the object that provides the processing for the client requests packaged as commands.



Figure 5. Command pattern

Iterator

A simple mechanism to traverse and access a list of objects is defined by the Iterator pattern. The Iterator pattern encapsulates the internal implementation of the list while providing a standardized mechanism for list traversal.



Figure 6. Iterator pattern

10.    Singleton design pattern snippet.

Sometimes we need to have only one instance of our class for example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers.

Definition:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Let’s see various design options for implementing such a class. If you have a good handle on static class variables and access modifiers this should not be a difficult task.

 
Method 1: Classic Implementation

// Classical Java implementation of singleton 
// design pattern
class Singleton {
    private static Singleton obj;
    // private constructor to force use of
    // getInstance() to create Singleton object

    private Singleton() {}

    public static Singleton getInstance()
    {
        if (obj==null)
            obj = new Singleton();
        return obj;
    }
}

Here we have declared getInstance() static so that we can call it without instantiating the class. The first time getInstance() is called it creates a new singleton object and after that it just returns the same object. Note that Singleton obj is not created until we need it and call getInstance() method. This is called lazy instantiation.

The main problem with above method is that it is not thread safe. Consider the following execution sequence.

This execution sequence creates two objects for singleton. Therefore this classic implementation is not thread safe.

Method 2: make getInstance() synchronized

// Thread Synchronized Java implementation of 

// singleton design pattern

class Singleton {

 private static Singleton obj;

  private Singleton() {}

    // Only one thread can execute this at a time

    public static synchronized Singleton getInstance() {

        if (obj==null)

            obj = new Singleton();

        return obj;

    }

}

Here using synchronized makes sure that only one thread at a time can execute getInstance(). The main disadvantage of this is method is that using synchronized every time while creating the singleton object is expensive and may decrease the performance of your program. However if performance of getInstance() is not critical for your application this method provides a clean and simple solution.

 

Method 3: Eager Instantiation

// Static initializer based Java implementation of

// singleton design pattern

class Singleton {

    private static Singleton obj = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {

        return obj;

    }

}

Here we have created instance of singleton in static initializer. JVM executes static initializer when the class is loaded and hence this is guaranteed to be thread safe. Use this method only when your singleton class is light and is used throughout the execution of your program.

Method 4 (Best): Use “Double Checked Locking
If you notice carefully once an object is created synchronization is no longer useful because now obj will not be null and any sequence of operations will lead to consistent results.
So we will only acquire lock on the getInstance() once, when the obj is null. This way we only synchronize the first way through, just what we want.

// Double Checked Locking based Java implementation of

// singleton design pattern

class Singleton {

    private volatile static Singleton obj;

    private Singleton() {}

    public static Singleton getInstance() {

        if (obj == null) {

            // To make thread safe

            synchronized (Singleton.class) {

// check again as multiple threads

                    // can reach above step

                if (obj==null)

                    obj = new Singleton();

            }

        }

        return obj;

    }

}

We have declared the obj volatile which ensures that multiple threads offer the obj variable correctly when it is being initialized to Singleton instance. This method drastically reduces the overhead of calling the synchronized method every time.

11.    What is load factor, Threshold, initial/default capacity of Collection Elements? 

ArrayList, Vector, HashSet, Hashtable, and HashMap.

Collection Java 8 Before Java 8
Initial capacity Load factor Initial capacity Load factor
ArrayList 0 (lazily initialized to 10) 10
Vector 10 10
HashSet 16 0.75 16 0.75
HashMap 16 0.75 16 0.75
Hashtable 16 0.75 11 0.75


Rehashing is done because whenever key value pairs are inserted into the map, the load factor increases, which implies that the time complexity also increases as explained above. This might not give the required time complexity of O(1).

Hence, rehash must be done, increasing the size of the bucketArray so as to reduce the load factor and the time complexity.

12. What is covariant return type in Java?

Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a subtype of the parent’s return type. The overriding method becomes variant with respect to return type.

13. What are Bean scopes in spring?

In the spring bean configurations, bean attribute called 'scope' defines what kind of object has to created and returned. There are 5 types of bean scopes available, they are:

1) singleton: Returns a single bean instance per Spring IoC container.

2) prototype: Returns a new bean instance each time when requested.

3) request: Returns a single instance for every HTTP request call.

4) session: Returns a single instance for every HTTP session.

5) global session: global session scope is equal as session scope on portlet-based web applications.

If no bean scope is specified in bean configuration file, then it will be by default 'singleton'. 

14. The contract between equals() and hashCode()?
public boolean equals(Object obj)

public int hashCode()

The problem is caused by the un-overridden method "hashCode()".

 The contract between equals() and hashCode() is:

1) If two objects are equal, then they must have the same hash code.
2) If two objects have the same hash code, they may or may not be equal.

 The idea behind a Map is to be able to find an object faster than a linear search. Using hashed keys to locate objects is a two-step process.

Internally, the HashMap is implemented as an array of Entry objects. Each Entry has a pair and a pointer pointing to the next Entry. The hash code of the key object is the index for addressing the array. This locates the linked list of Entries in that cell of the array. The linked list in the cell is then searched linearly by using equals() to determine if two objects are equal.

The default implementation of hashCode() in Object class returns distinct integers for different objects. Therefore, the second apple has a different hash code.

The HashMap is organized like a sequence of buckets. The key objects are put into different buckets. It takes time of O(1) to get to the right bucket because it is an array access with the index. Therefore, it's a good practice to evenly distribute the objects into those buckets, i.e., having a hashCode() method that produces evenly distributed hash code. (Not the main point here though)

The solution is to add the hashCode method to the Apple class. Here I just use the color string's length for demonstration.

public int hashCode(){return this.color.hashCode();}

15. How to create Immutable class in Java?

The class must be declared as final so that child classes can’t be created.

Data members in the class must be declared private so that direct access is not allowed.

Data members in the class must be declared as final so that we can’t change the value of it after object creation.

A parameterized constructor should initialize all the fields performing a deep copy so that data members can’t be modified with an object reference.

Deep Copy of objects should be performed in the getter methods to return a copy rather than returning the actual object reference)

final class Record {

  private final long id;

  private final String name;

  private final List tokens;

  public Record(long id, String name, List tokens) {

    this.id = id;

    this.name = name;

    this.tokens = tokens;

  }

  public long getId() {

    return id;

  }

  public String getName() {

    return name;

  }

  public List getTokens() {

    return new ArrayList<>(tokens);

  }

  @Override

  public String toString() {

    return "Record{" +

        "id=" + id +

        ", name='" + name + '\'' +

        ", tokens=" + tokens +

        '}';

  }

}

16. How does HashSet Work?

HashSet internally uses HashMap to store it’s elements. Whenever you create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements you enter in the HashSet. The elements you add into HashSet are stored as keys of this HashMap object. The value associated with those keys will be a constant.
     
    whenever you insert an element into HashSet using add() method, it actually creates an entry in the internally backing HashMap object with element you have specified as it’s key and constant called “PRESENT” as it’s value. This “PRESENT” is defined in the HashSet class as below.

      In the  same manner, all methods of HashSet class process internally backing HashMap object to get the desired result. If you know how HashMap works, it will be easy for you to understand how HashSet works. You go through the source code of HashSet class once, you will get a clear picture about how HashSet works internally in Java.

17. What is the difference between Log4j 1 and log4j 2?

    Log4j only supported configuration files in properties and XML formats, while Log4j2 supports configuration through XML, JSON, YAML, and configuration files/programmatic actions

18. Optimistic Locking and Pessimistic locking in Hibernate?

Optimistic locking , where a record is locked only when changes are committed to the database. Pessimistic locking , where a record is locked while it is edited.

19. How can we create a Cache and cache in Spring Boot?

@Cacheable

The simplest way to enable caching behavior for a method is to mark it with @Cacheable and parameterize it with the name of the cache where the results would be stored. 

@Cacheable(“name”)

public String getName(Customer customer) {…}

20. Second level cache in Hibernate?

A Hibernate second-level cache is one of the data caching components available in the Hibernate object-relational mapping (ORM) library. Hibernate is a popular ORM library for the Java language, and it lets you store your Java object data in a relational database management system (RDBMS).

21. Topic versus Queue?

The difference between a Topic and a Queue is that all subscribers to a Topic receive the same message when the message is published and only one subscriber to a Queue receives a message when the message is sent.

22. What happens when JMS server crash what happens to the queue Web logic server?

With the automatic JMS client reconnect feature, if a server or network failure occurs, some JMS client objects will transparently failover to use a another server instance, as long as one is available. For example, if a fatal server failure occurs, JMS clients automatically attempt to reconnect to the server when it becomes available.

23. Any other methods required in comparable implementation.

The Comparable interface contains the method compareTo to decide the order of the elements. Override the compareTo method in the Pair class.

24. Read property from property file in a class.

The Properties is a subclass of Hashtable class and it represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. 

The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties.load() method of Properties class is convenient to load .properties file in the form of key-value pairs.

Syntax

public class Properties extends Hashtable

credentials.properties file

Example

import java.io.*;
import java.util.*;

    public class ReadPropertiesFileTest {

       public static void main(String args[]) throws IOException {

          Properties prop = readPropertiesFile("credentials.properties");

          System.out.println("username: "+ prop.getProperty("username"));

          System.out.println("password: "+ prop.getProperty("password"));

       }

       public static Properties readPropertiesFile(String fileName) throws IOException {

          FileInputStream fis = null;

          Properties prop = null;

          try {

             fis = new FileInputStream(fileName);

             prop = new Properties();

             prop.load(fis);

          } catch(FileNotFoundException fnfe) {

             fnfe.printStackTrace();

          } catch(IOException ioe) {

             ioe.printStackTrace();

          } finally {

             fis.close();

          }

          return prop;

       }
}
	Output :

	username: admin
	password: admin@123

25. Write a program to print something but should not execute PSVM?

As we know that the static block executes before the main method, hence we can place the statement that we want to execute in the static block, But in case of JDK7, and the above versions of the JDK, the code would not execute as compiler firstly looks for the main method before any other thing. Also, it depends on the IDE being used to run the program, ie the program might get executed successfully on some IDE, and might not on some IDE’s. Also, we can abnormally exit our program in the static block so that the JVM will not check the main method, but as discussed it depends on IDE, whether the program will run or not.

Example: Below is the code implementation of the above approach.

  // Java Program printing the statement without using main
  // method.

class PrintWithoutMain {

    // static block

    static {
        // prints "Hello World!!" to the console
        System.out.println("Hello World!!");
        // exit from the program
        System.exit(1);
    }
}
    Output
    Hello World!!

The above code does not compile before and on JDK7. Also, one might get the error like below if run the above code on some IDE like Intellij or Netbeans or console.

26. What annotations we have in Entity classes?

     @Entity
  @Table(name = "STUDENT")
  public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "STUDENT_NAME", nullable = false, unique = false)
    private String name;
    @Transient
    private Integer age;
    @Temporal(TemporalType.DATE)
    private Date birthDate;
    @Enumerated(EnumType.STRING)
    private Gender gender;
    // other fields, getters and setters
  }
  

27. What Class not found exception n Java?

ClassNotFoundException occurs when you try to load a class at runtime using Class. forName() or loadClass() methods and requested classes are not found in classpath. Most of the time this exception will occur when you try to run an application without updating the classpath with JAR files.

28. How we do validation in spring?

The Spring MVC framework provides us with standard predefined validators to validate user input data in a simple and straightforward way. The Bean Validation API is the popular approach for data validations in Spring applications. Here we will be using the hibernate implementation of the Bean Validation API known as Hibernate Validator. 

Validation annotations

Here are some of the most commonly used validation annotations.


1. @Min(value=) – Checks whether the annotated value is greater than 
or equal to the specified minimum value.
2. @Max(value=) – Checks whether the annotated value is smaller than 
or equal to the specified maximum value. ‘

	@Min(value = 18, message = "Age must be greater than 18")
	@Max(value = 25, message = "Age must be smaller than 25")
	private int age;

3. @NotNull – Checks that the annotated value is not null.

4. @NotBlank – Checks that the annotated character sequence/string is 
not null and the trimmed length is greater than 0.

5. @NotEmpty – Checks that the annotated element 
is not null and not empty.

// @NotNull: The CharSequence, Collection, Map or Array object is 
not null, but can be empty.

// @NotEmpty: The CharSequence, Collection, Map or Array object is 
not null and size > 0.

// @NotBlank: The string is not null and the trimmed length is 
greater than zero.

@NotEmpty(message = "First name cannot be null and 
must have size greater than 0")
private String firstName;

@NotNull(message = "Second name must not be null, 
empty value/space can be considered")
private String lastName;

@NotBlank(message = "Username must not be null and 
must contain 1 or more characters")
private String userName;

6. @Email – Checks whether the specified character 
sequence/string is a valid email address.

@Email(message = "Email should be valid")
private String email;

7. @Pattern(regex=, flags=) – Checks that the annotated string matches the 
regular expression considering the given flag matches.

// The regex specifies that the password can contain characters from 
a to z, A to Z and 0-9 only,

// also it must be in between 6 to 10 characters long.

@Pattern(regexp = "^[a-zA-Z0-9]{6,10}$")
private String password;

8. @AssertFalse – Checks that the annotated element is false.

9. @AssertTrue – Checks that the annotated element is true.

@AssertTrue 
private boolean isWorking;

@AssertFalse
private boolean isStudent;

10. @NegativeOrZero – Checks if the given element is 
smaller than or equal to 0.

11. @Null – Checks that the annotated value is null.

12. @Negative – Checks if the element is strictly 
smaller than 0.

13. @Positive – Checks if the element is strictly 
greater than 0.

14. @PositiveOrZero – Checks if the given element is 
greater than or equal to 0.

@Positive
private int operand1;

@Negative
private int operand2;

@PositiveOrZero
private int operand3

@NegativeOrZero
private int operand4;

@Null
private int nullVal;

15. @Size – Checks if the annotated element’s size is 
between min value 
and max value provided (inclusive).

@Size(min = 10, max = 200, message = "About Me must be 
between 10 and 200 characters")
private String aboutMe;

Example 1: User class // Java Program to Illustrate Calculator class

package com.example.springmvc;

// Importing required classes

import javax.validation.constraints.*;
import lombok.Data;

// Annotation
@Data
// Class
public class User {

    @NotEmpty(
        message
        = "First name cannot be null and must have size 
        greater than 0")
    private String firstName;

    @NotNull(
        message
        = "Second name must not be null, empty value/space 
        can be considered")
    private String lastName;

    @NotBlank(
        message
        = "Username must not be null and must 
        contain 1 or more characters")
    private String userName;

    @AssertTrue private boolean working;

    @Min(value = 18,
         message = "Age must be greater than 18")

    @Max(value = 25,
         message = "Age must be smaller than 25")
    private int age;

    @Size(
        min = 10, max = 200,
        message
        = "About Me must be between 10 and 200 characters")
    private String aboutMe;

    @Email(message = "Email should be valid")
    private String email;

    @Pattern(regexp = "^[a-zA-Z0-9]{6,10}$")
    private String password;

    @AssertTrue private boolean isWorking;

    @AssertFalse private boolean isStudent;

}

29. Two classes implement same Interface and how do we create reference of 1 class in Spring(not using new keyword)

You don't call a method directly from an interface, you call it on a reference that points to an instance of a class. Whichever class that is determines which method gets called.

30. How do you do your db connections in property files?

  Connect to your database using application.properties.
   spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
spring.datasource.username=todouser
spring.datasource.password=YOUR_PASSWORD

31. Explain SOLID principles?

Single Responsibility Principle (SRP) - A class should have only one reason to change

Open/Closed Principle - Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

Liskov’s Substitution Principle (LSP) - Derived or child classes must be substitutable for their base or parent classes

Interface Segregation Principle (ISP) - Do not force any client to implement an interface which is irrelevant to them

Dependency Inversion Principle (DIP) -

  • High-level modules/classes should not depend on low-level modules/classes. Both should depend upon abstractions.
  • Abstractions should not depend upon details. Details should depend upon abstractions.

32. Co-relation id in micro services.

Correlation ids are unique identifiers that help you trace requests across multiple services in a distributed system. They are essential for debugging, logging, and monitoring the performance and behavior of your microservices.

33. How do we monitor micro services?

There are three monitoring tools are as follows:

  • Hystrix dashboard
  • Eureka admin dashboard
  • Spring boot admin dashboard

34. How objects converted to json in restful web services

You can use GSon to convert json object to java object


Gson gson = new Gson();
//to get json object use toJson
String json = gson.toJson(obj);
//to get java object use fromJson
MyClass obj = gson.fromJson(jsonObj, MyClass.class);

jackson is also pretty fast and easy to use

35. What is Volatile and where it is used?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.

36. Where you do database configuration in Spring boot?

    Connect to your database using application.properties.
  spring.jpa.hibernate.ddl-auto=none
  spring.datasource.url=jdbc:mysql://localhost:3306/todo_example
  spring.datasource.username=todouser
  spring.datasource.password=YOUR_PASSWORD

37. Why set does not allow duplicates – reason?

Why set does not allowed duplicates, How it will work internally. The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged. This does not lead to compile or runtime errors: duplicates are silently ignored.

38. How do we Configure classes in Spring boot?

Spring Boot favors Java-based configuration. Although it is possible to use SpringApplication with XML sources, we generally recommend that your primary source be a single @Configuration class. Usually the class that defines the main method is a good candidate as the primary @Configuration 

39. what is the difference between component, bean, Services, Repository?

@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.

The @Bean annotation is a method-level annotation, whereas @Component is a class-level annotation. The @Component annotation doesn't need to be used with the @Configuration annotation, whereas the @Bean generic annotation has to be used within a class annotated with @Configuration .

40. How you configured jdbc template in Springboot

Create a SpringBoot maven based project and add spring-boot-starter-jdbc module.

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

The jdbcTemplate automatically reads the spring.datasource properties from my application.properties file

41. What changes required to deploy spring boot as war file in Server?

We need to deploy WAR file so change the package type to WAR in pom.xml file.

<packaging>war</packaging> 

42. Iterate over hash set?

There are three simple ways to iterate over a HashSet, which is the following :

  1. Using Iterator
  2. Without using Iterator (using for loop)
  3. Using for-each loop 

43. JPA how you write a query in JPA?

  package com.javaforsomeone.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.javaforsomeone.entity.Employee;

@Repository
public interface EmployeeRepository extends CrudRepository  {

   public List findByName(String name); 

   public List findByAge(int age);

   public Employee findByEmail(String email);

   @Query(value = "SELECT e FROM Employee e ORDER BY name")
   public List findAllSortedByName();
}

44. what is the difference between RestController and controller?

@RestController is nothing but the shortcut to use both @Controller and @ResponseBody annotation together. In other words, @Controller is used to controller which can accept and return HTML while @RestController annotation can be used to return JSON response.

45. what are default methods in interface added in Java 8?

The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods.

46. When String created using new, "", where it will be present in heap or string pool?

String creation using new()

String creation using String literal

If we create a String using new(), then a new object is created in the heap memory even if that value is already present in the heap memory.

If we create a String using String literal and its value already exists in the string pool, then that String variable also points to that same value in the String pool without the creation of a new String with that value.

It takes more time for the execution and thus has lower performance than using String literal.

It takes less time for the execution and thus has better performance than using new().

Example:

String n1= new String(“Java”);

String n2= new String(“Java”);

String n3= new String(“Create”);

Example:

String s1=”Java”;

String s2=”Java”;

String s3=”Create”;

47. what new features are there in java 8?

  • Some of the important Java 8 features are;
  • forEach() method in Iterable interface
  • default and static methods in Interfaces
  • Functional Interfaces and Lambda Expressions
  • Java Stream API for Bulk Data Operations on Collections
  • Java Time API
  • Java Stream API1
  • Concurrency API improvements
  • Java IO improvements

48. Does toUpper. toLower creates new string object or not?

Java automatically interns String literals. when you use toUpperCase() it creates a new instance of the string, using new String(), that's why both the objects are different.

49. Serializable interface is a marker interface

The Serializable interface is present in java.io package. It is a marker interface. A Marker Interface does not have any methods and fields. Thus classes implementing it do not have to implement any methods. Classes implement it if they want their instances to be Serialized or Deserialized. Serialization is a mechanism of converting the state of an object into a byte stream. Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream. Thus it can be used to make an eligible for saving its state into a file. 

50. What is Static synchronization & non static synchronization?

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object.

If you make any static method as synchronized, the lock will be on the class not on object.

Why we use Static Synchronized Block/Method?

Suppose there are two objects of a shared class(e.g. Account) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. I want no interference between t1 and t3 or t2 and t4. Static synchronization solves this problem.

The JVM creates a Class object when the class is loaded (When it is used for the first time). Once a class is loaded into a JVM, the same class will not be loaded again. The JVM creates one instance of Class for each class that is loaded, The Class instances are Objects and can be synchronized via static synchronized methods.

For example


class MyClass  {
  ...
  public synchronized static someMethod() {
    ...
  }
  ...
}
It is the equivalent to the following static synchronized block:

synchronized ( MyClass.class ) {
...
}
Example of static synchronization In this example we are applying synchronized keyword on the static method to perform static synchronization.

class Account{
 synchronized static void showAccount(String accountName){
     System.out.println("My account name is "+accountName+" 
     Holder Name is "+Thread.currentThread().getName());
     try{
       Thread.sleep(500);
     }catch(Exception e){}
   }
}

class MyThread1 extends Thread{
    public void run(){
       Account.showAccount("Javaforsomeone.com");
  }
}

class MyThread2 extends Thread{
    public void run(){
       Account.showAccount("Linkedin.com");
    }
}

class MyThread3 extends Thread{
    public void run(){
       Account.showAccount("Facebook.com");
    }
}

class MyThread4 extends Thread{
    public void run(){
       Account.showAccount("Twitter.com");
    }
}

class StaticSyncDemo{

    public static void main(String t[]){
       MyThread1 t1 = new MyThread1();
       MyThread2 t2 = new MyThread2();
       MyThread3 t3 = new MyThread3();
       MyThread4 t4 = new MyThread4();
       t1.setName("DAV JavaServices");
       t2.setName("Java For Some");
       t3.setName("Java For One");
       t4.setName("admin@javaforsomeone.com");       
       t1.start();
       t2.start();
       t3.start();
       t4.start();
    }
}