Nitin Agrawal
Contact -
  • Home
  • Interviews
    • InterviewFacts
    • Resume Thoughts
    • Companies >
      • InvestmentBanks >
        • ECS
        • Bank Of America
        • WesternUnion
        • WellsFargo
      • ProductBasedCompanies >
        • CA Technologies
        • Model N India
        • Verizon Media
        • Oracle & GoJek
        • IVY Computec
        • Samsung
        • ClearWaterAnalytics
        • ADP
        • ServiceNow
        • Pubmatic
        • Expedia
        • Amphora
        • CDK Global
        • Delphix
        • Fractal Enterprises LLP
        • CDK Global
        • Tide-Banking
        • Epic
        • Sincro-Pune
      • ServiceBasedCompanies >
        • Altimetrik
        • ASG World Wide Pvt Ltd
        • Paraxel International & Pramati Technologies Pvt Ltd
        • MitraTech
        • Intelizest Coding Round
        • ZeMoSo
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems
      • AnagramsSet
    • Core Java >
      • Codility
      • Java14 >
        • Code Snippets
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
      • Important Points
      • Immutability
      • Dictionary
      • Sample Code Part 1 >
        • PatternLength
        • Serialization >
          • Kryo2
          • JAXB/XSD
          • XStream
        • MongoDB
        • New methods in Collections
        • MethodReferences
        • Complex Objects Comparator >
          • Performance
        • NIO >
          • NIO 2nd Sample
        • Date Converter
        • Minimum cost path
        • Find File
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • Decorator
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • RequestChaining
        • Singleton >
          • Singletons
  • Frameworks
    • AngularJS
    • Apache Velocity
    • Spring >
      • Spring Boot >
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Design Patterns
    • AWS >
      • Honeycode
  • Databases
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search >
      • StudySources
  • Random issues
    • TOAD issue
    • Architect's suggestions
  • Your Views
You can check the code snippets, asked as part of interview processes on -
https://github.com/nitinbly84/CodeSnippets.git


Here on this page I will be posting the coding questions asked during the interviews. Other such useful questions can be seen on other pages on this site.
The solutions I have posted, are as per my understanding & those may be incorrect or can be optimized further. It will be helpful if I can get suggestions on that & get more questions.
It will be great if you can share the interview questions here, along with the answers which were accepted. Else I will try to put the answer of those here.

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

Sometimes, you may be given below kind of code during the interviews & tell the result -

public class PracA {
 
 PracA() {
  System.out.println("PracA");
  new PracB();
 }
 public static void main(String[] args) {
  PracB pb = new PracB();
 }
}
class PracB extends PracA {
 PracB() {
  super();
 }
}

​Result will be StackOverflowError, & reason is new PracB() statement which is causing the loop here. If you remove this statement then program is fine.

​Also see both the classes are in the same .java file, so only one class can be public. Interviewer can say what if both classes are public, then result will be compilation error.
===============================================================================================

Sometimes, you may be given below kind of code during the interviews to tell the result -
public class PracA {
 
 public static void main(String[] args) {
  Integer i = null;
  int j = Integer.parseInt(null); // Gives java.lang.NumberFormatException: null
  int k = i; // Gives java.lang.NullPointerException
 }
}

​Results : Results are mentioned in the comments in the code above. So while coding in real life also we need to take care for such NullPointer issues.
===============================================================================================

One more question I have seen that people ask that your method accepts some object value & you are taking some actions on that value as per your ​requirement, but how will you avoid any 'NullPointerException' issue efficiently. So below are my some suggestions to avoid any such issues in your ​method or other's method. As you can't assume that other's method is checking for Null value.
​a) In your method before starting any operation on the received values, check if those values are valid & not null, otherwise
​    throw some exception to pass the required message to the caller.
​b) If you are looking some fancy here, then you can look for some annotations which may be provided by 3rd parties to check
​    for null values. Or you can even use - Objects.requireNonNull(val); as a first statement in your method body like shown
​    below -
         public static Integer check(Integer val) {
               Objects.requireNonNull(val);
               return val;
          }
​c) And also while returning any object, don't return null, better try to return an empty object, which can avoid the
​    NullPointerException by the other calling
​    methods. If you are returning some collection object like List then you can use Collections.EMPTY_LIST; instead of return
​    null.

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

Question : How will you create your Singleton class so that one shouldn't be able to create another instances of it using 
​                   reflection even.
​Solution : If you are using jdk5 or above then use Enum directly else override readResolve() & writeReplace() in your
​                  singleton class. Look on the Google to get implementation details of this. Rest look here.

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

Question : How will you prevent the changing of the private members of your class via reflection API.
​Solution : One simple way to make all such private members as final also & if making 'final' every such member is not
​                  feasible then provide one private method to check such changes & do reset them before working on them. Call this
​                  method in every of your method first. Example shown below & 'Others' is the class which we want to safeguard
​                  with such changes & for further security if feasible you can make your class as final, to avoid any overriding further-


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
 * This class is a sample to show how to prevent any issue due to reflection by other classes.
 * One can see if some variable value is not supposed to be changed by any way then declare that
 * field has private final else if that field is supposed to be changed by owner class only, then
 * check if its value was changed by other class may be via reflection API.
 * @author nitin
 *
 */
public class Reflections {
 public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
  Others o = new Others();
  Field[] fields = Others.class.getDeclaredFields();
  fields[0].setAccessible(true);
  fields[1].setAccessible(true);
  // Below trying to change the value of private final member.
  // Though it will not give any issue but this new value will not
  // be used.
  for(Field f : fields) {
   int mod = f.getModifiers();
   Field modifier = f.getClass().getDeclaredField("modifiers");
   modifier.setAccessible(true);
   modifier.setInt(f, mod - Modifier.FINAL);
  }
  fields[0].setInt(o, 2);
  fields[1].set(o, "Nitin");
  // As value of 'a' was changed to 2, so value must have been 6 but it is 9 still.
  // Because that member was final.
  System.out.println(o.getValue());
  // If check the field value then it shows as '2' here but it is not used when referred from the object of
  // Others.
  System.out.println(fields[0].get(o));
  // value is still '3' here.
  System.out.println(o.getA());
  // Value is reset due to use of checker()
  System.out.println(o.getJ());
 }
}
class Others {
 private final int a = 3;
 private String j;
 public int getValue() {
  //  checker();
  int b = a;
  int i = b*3;
  return i;
 }
 // If working on any private member variable in the method, then always checking if its value has changed
 // if yes then reset the value.
 public String getJ() {
  checker();
  j = "Hello";
  return j;
 }
 
 public int getA() {
  return a;
 }
 // This method will be used to check the private members' values & if there is any change then will reset those values.
 private void checker() {
  if(j != null) {
   System.out.println("Illegal value of j....reseting now....");
   j = null;
  }
 }
}


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

Question : Below is the code, tell the issues in this -
class Base {
 
 static String getDetails() {
    return "Hello";
 }

String findCountry() {
​return "India";
​}

static void status() {
​sop("True");
}

int add() {
  return 7;
 }
 
 int sub() {
  return 3;
 }
}
class Decorator extends Base {
  
 public static String getDetails() {
    return "Hi";
 }

static String findCountry() {
​return "India";
​}

​public void status() {
​sop("False");
}
protected int add() {
  return 3;
 }
 
 private int sub() {
  return 1;
 }
}

Solution : getDetails() will be fine as in both classes it is associate with classes & will not participate in OOP concepts, so no
​                  issues with this.
 ​                findCountry(), this will give the compile time error, because, findCountry() from 'Base' class will be part of 
​                 'Decorator' class & findCountry() 
​                 is also present in 'Decorator' class as static method & it can't override the instance method. So it is an issue.
​                 status(), this will give the compile time error, because this method is present as static to 'Base' class & is visible to
​                 'Decorator' class, so compiler will complain as instance method can't override the static method. So it is an issue.
​                 add() will be fine as it is just widening the access specifier & subclass can do that, so no issues here.
​                 sub(), this will give the compile time error as you can't reduce the visibility in the subclass of any overridden
​                 method. So it is an issue here.


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

Question : During the interview with Tech Mahindra, I was asked below question & I was supposed to provide the solution as
​                  per the senior Java resource or Team Leader -
​                  Write a method to convert the given string as per the below condition & invalid character will also be provided -
​                  In the resulted string, all the valid characters must be in the start & all the invalid characters must be in the end.
​                  Ex : input String : a*b*c
​                         Invalid character : *
​                        Output should be : abc***
                  So I gave below solution -
Solution : 

public class Conversion {
 
 public static void main(String[] args) {
  System.out.println(convert("a*b*c*", '*'));
  System.out.println(convert("abc***", '*'));
  System.out.println(convert("a**bc*", '*'));
  System.out.println(convert("abc", '*'));
 }
 
 public static String convert(String input, char invalid) {
  if(input == null || input.isEmpty())
   return input;
  
  int len = input.length();
  char[] array = new char[len];
  int start = 0;
  int end = len - 1;
  for(char ch : input.toCharArray()) {
   if(ch != invalid) {
    array[start] = ch;
    start++;
   } else {
    array[end] = ch;
    end--;
   }
  }
  return new String(array);
 }
}


​Following questions were - What cases will you test for this code? How will you add a solution for a separate but related problem ​like output should be "***abc"?
​So I said, I will treat each new requirement as the new feature & will create a separate class for that. And will create another class on delegator pattern. to call the required class for the required feature. But instead of that pattern name, he was looking for 'Strategy' design pattern.

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

Question : You are given a String of characters like 'abcdacdera', find the count of each character occurrence in this String.
​                  Further complexity can be added to display this output in the decreasing order of count of each character.
Solution : This question is getting very common to understand the approach of the candidate to solve the issues.
​                 Interviewer may not be expecting a working code but would like to know about your approach & what options you
​                 try to find the solution. This question has been asked in Synechron, Infosys & CA Technologies interviews.
​                 Below I have given a solution for this for both the above requirements & accordingly you can remove the part of the
                 code or can keep it. Please check the comments in the code below -

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
 * To get the count of each character in the provided String.
 * And print the count of each character in decreasing order of
 * values of the count. If count is same then upper case character
 * will be shown first or the character whose ASCII value is lesser.
 * @author nitin
 *
 */
public class CharacterCount {
 public static void main(String[] args) {
  //  String str = "abcBbdghBadbcABBBAAA";
  //  String str = "";
  //  String str = null;
  String str = "ABCDACV{}{abbbbc{}{{{{{{}DDDD---------";
  //  String str = "abcacbcaa";
  List<Chars> chars = counts(str);
  if(chars.isEmpty())
   System.out.println("Empty list with no data");
  else
   System.out.println("Using Map & Comparator ordered by count of each character & if count"
     + " \n of characters is same then those will be in increasing order of "
     + "\n their ASCII values....");
  for(Chars ch : chars) {
   System.out.println(ch.data  + "  " + ch.count);
  }
 }
 public static List<Chars> counts(String str) {
  if(str == null)
   return Collections.EMPTY_LIST;
  char[] characters = str.toCharArray();
  
  CustomComparator cc = new CustomComparator();
  
  HashMap<Character, Chars> hm = new HashMap<>();
  // If don't want to use the map like above, then can use map as shown below.
  // It will also shorten the code & will make it simple.
  HashMap<Character, Integer> charCount = new HashMap<>();
  
  // If using jdk8 & want to use its features only then below HashMap.
  HashMap<Character, Integer> charCount8 = new HashMap<>();
  
  Set<Chars> collection = new TreeSet<>();
  //  This for loop block will take the count of each character in the String
  //  and will store this data in the hashmap. If you just need the counts &
  //  don't need to take any other action then can avoid creating a separate class
  //  like created as 'Chars' & instead of its objects just store the count directly
  //  as Integer & keep updating that value if the key is encountered again.
  for(char ch : characters) {
   Chars chr = hm.get(ch);
   if(chr == null) {
    chr = new Chars();
    chr.data = ch;
    chr.count = 1;
    hm.put(ch, chr);
   } else {
    chr.count = chr.count + 1;
   }
   Chars chars = new Chars();
   chars.data = ch;
   collection.remove(chars);
   if(charCount.containsKey(ch))
    chars.count = charCount.get(ch) + 1;
   else
    chars.count = 1;
   charCount.put(ch, chars.count);
   collection.add(chars);
   
   charCount8.compute(ch, (c, i) -> (i == null) ? 1 : i+1);
  }
  //  Below is fetching the keys i.e. objects of 'Chars' class & storing
  //  these objects in a list which is sorted as per the Comparable interface
  //  implementation.
  Collection<Chars> cl = hm.values();
  List<Chars> ls = new ArrayList<>();
  ls.addAll(cl);
  Collections.sort((List<Chars>)ls, cc);
  
  System.out.println("Showing the count of characters using jdk8.....");
  charCount8.forEach((c, i) -> System.out.println(c + "  " + i));
  System.out.println("--------------------------");
  
  System.out.println("Using TreeSet ordered by characters.........");
  for(Chars chr : collection) {
   System.out.println(chr.data + "  " + chr.count);
  }
  System.out.println("-------------------------");
  
  // Returning the sorted list.
  return ls;
 }
}
/**
 * Below class is used to store the characters in the string & Comparable
 * implementation is provided to sort its objects accordingly.
 * Here its objects will be sorted in reverse/decreasing order as per the
 * values of 'count'.
 * @author nitin
 *
 */
class Chars implements Comparable<Chars> {
 char data;
 int count;
 @Override
 public int hashCode() {
  return data;
 }
 @Override
 public boolean equals(Object ch) {
  return ((Chars) ch).data == this.data;
 }
 // If TreeSet not using then can use below block & remove next compareTo() block.
 // Also no need to use the comparator then.
 /*@Override
 public int compareTo(Chars o) {
  if(o.count < this.count)
   return -1;
  else if(o.count > this.count)
   return 1;
  else {
   if(o.data < this.data)
    return 1;
   else if(o.data > this.data)
    return -1;
  }
  return 0;
 }*/
 // Below method will cause the ordering on the basis of 'key'
 // i.e. character. And if ordering needs to be done on the basis
 // of counts, then try the above method & HashMap.
 @Override
 public int compareTo(Chars o) {
  if(o.data < this.data) {
   return 1;
  }
  else if(o.data > this.data) {
   return -1;
  }
  return 0;
 }
}
/**
 * Custom comparator class to sort the objects on the basis of count
 * and the objects will have decreasing order.
 * @author nitin
 *
 */
class CustomComparator implements Comparator<Chars> {
 @Override
 public int compare(Chars o1, Chars o2) {
  if(o1.count < o2.count)
   return 1;
  else if(o1.count > o2.count)
   return -1;
  else {
   if(o1.data < o2.data)
    return -1;
   else if(o1.data > o2.data)
    return 1;
  }
  return 0;
 }
}


Output of above code :
Showing the count of characters using jdk8.....
a  1
A  2
b  4
B  1
c  1
C  2
D  5
V  1
{  9
-  9
}  3
--------------------------
Using TreeSet ordered by characters.........
-  9
A  2
B  1
C  2
D  5
V  1
a  1
b  4
c  1
{  9
}  3
-------------------------
Using Map & Comparator ordered by count of each character & if count
 of characters is same then those will be in increasing order of
 their ASCII values....
-  9
{  9
D  5
b  4
}  3
A  2
C  2
B  1
V  1
a  1
c  1


Also please look here. And also try the above code with different samples & please let me know here, in case you get issue for any such case.
===============================================================================================
Question : 
You are given a collection of points with their coordinates in 2 dimensional space. Now you need to find the
                   minimum are of the square to enclose all the points such that either these points are on the edge or within the
                   square. There can be multiple such cases where you need to find the minimum area for the given points. You will
                   be given this input via command line such that first line will be number of test cases, second line will be number of
                   points in the current test case & after that will be the points coordinates in that case. And you need to print the
                   area for each test case.
                   Below is one way I thought of & it is not yet tested properly but it can give you one approach & in case of any
                   issue here then please let me know the failing test case/s & suggest the solution.
                   Note :- Currently in below code usage of ArrayList, sorting of ArrayList & HashMap is useless & can be removed
                               but it is there still to have some pointers in case requirement is tweaked a bit.
Solution : 

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;

public class HR2 {
 static Scanner s = new Scanner(System.in);
 public static void main(String[] args) {
  System.out.print("Number of Test Cases : ");
  int count = Integer.parseInt(s.nextLine());
  ArrayList<String> ans = new ArrayList<>();

  while(count > 0) {
   System.out.print("Number of Inputs : ");
   int inputs = Integer.parseInt(s.nextLine());
   ArrayList<String> co = new ArrayList<>();
   while(inputs > 0) {
    String t = s.nextLine();
    co.add(t);
    inputs--;
   }
   System.out.println(findPoints(co));
   count--;
  }
  s.close();
  ans.forEach(System.out::println);
 }

 private static String findPoints(ArrayList<String> co) {
  int xMin = Integer.MAX_VALUE;
  int yMin = Integer.MAX_VALUE;
  int xMax = Integer.MIN_VALUE;
  int yMax = Integer.MIN_VALUE;
  HashMap<Integer, Integer> point1 = new HashMap<>();
  HashMap<Integer, Integer> point2 = new HashMap<>();
  HashMap<Integer, Integer> point3 = new HashMap<>();
  HashMap<Integer, Integer> point4 = new HashMap<>();
  ArrayList<Integer> xs = new ArrayList<>();
  ArrayList<Integer> ys = new ArrayList<>();

  int len = co.size();
  for(int i = 0; i < len; i++) {
   String cur = co.get(i);
   String[] splits = cur.split(" ");
   int xCor = Integer.parseInt(splits[0]);
   int yCor = Integer.parseInt(splits[1]);
   xs.add(xCor);
   ys.add(yCor);
   if(xMin >= xCor) {
    xMin = xCor;
    point1.clear();
    point1.put(xMin, yCor);
   }
   if(xMax <= xCor) {
    xMax = xCor;
    point2.clear();
    point2.put(xMax, yCor);
   }
   if(yMin >= yCor) {
    yMin = yCor;
    point3.clear();
    point3.put(yMin, xCor);
   }
   if(yMax <= yCor) {
    yMax = yCor;
    point4.clear();
    point4.put(yMax, xCor);
   }
  }

  Collections.sort(xs);
  Collections.sort(ys);

  BigInteger length = new BigInteger(xMax-xMin+"");
  BigInteger breadth = new BigInteger(yMax-yMin+"");

  return length.multiply(breadth).toString();
 }

}

Powered by Create your own unique website with customizable templates.