Sunday, October 13, 2019

TO THE NEW Interview Questions | October 2019

1. Check if two strings are anagram of each other.
2. Reverse a doubly circular linked list.
3. Implement Queue using linked list.

Policy Bazaar Interview Experience | Oct 2019

I visited policy bazaar on 12/10/2019, for opportunity in Java Development. My experience is 5 years and i am sharing my complete interview experience below.

The interview process consisted of :

1. Telephonic Interview :

Tell me about your work.
Why String is special in JAVA?
What are immutable classes and how to make a class immutable.
Why other classes are not Immutable?
Does static break encapsulation in Java?
Where are the variables of interface getting stored.
what is the difference between : String s="sid" and String s=new ("Sid");
What and where is string constant pool? where are int stored in memory.
How is + overrided for string in java? ex : StringBuffer s="hi".append(s1).append(s2); and
String x=s+s1+s2? how many objects are being created in both cases.
Level Order traversal?
Improvements in hashmap in java 8?
treeify time complexity.
What is better HashSet or HashMap for getting distinct list of items? Consider Hashset internally implements HashMap.
How does Spring work internally?
Memory management in Java 8.
Give an example of Memory Leak and Out Of memory error.

2. Written round at their Gurgaon Office

https://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/

https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/

3. Technical Round No 1 at their Gurgaon Office

https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/

Whats is OOPS.
Is Java a functional lang or structural lang.
What is functional programming.
What is lambda.
What is encapsulation & abstraction.
Why we do overriding and overloading? Give examples of your project.
More Core java Questions.
When is Arraylist useful and when is Linkedlist useful.
SOLID Principles.
Open/Closed Principle
static syncronized & synchronized difference.

3. Technical Round No 2 at their Gurgaon Office

Level Order Traversal.
Spiral Level Order Traversal.
LRU Cache implementation.
Producer Consumer Problem.
Multithreading  questions.
wait() / sleep() difference.
how do you implement caching in your project.
Executor Framework.
How to make a thread.
Design Pattern You have worked upon.
why String is so special in java.
Where is String constant pool in memory?
Difference b/w encapsulation and abstraction and polymorphism.
Can we upload war/ejb in AWS lambda? if not why?
How does UI code can be uploaded in AWS Lambda.

4. HR discussion

Wednesday, October 9, 2019

JAVA Memory Model Quick Reference Guide -JAVA 8 Updates

JDK 7 still has PermGen but the interned strings are moved to JAVA heap.

JDK 8 :

Permgen has been removed completely.

Only the class metadata is being stored in Metaspace m along with JVM internal code, rest of the data is in Heap.

Tuesday, October 8, 2019

Object Oriented Concepts

Data Hiding

The data should not go out directly i.e outside person is not allowed to access the data this is nothing but “Data Hiding”.
The main advantage of data hiding is we can achieve security.
By using private modifier we can achieve this.

Abstraction

Hiding implementation details is nothing but abstraction

Note:- 1) If we don’t know about implementation just we have to represent the specification then we should
go for interface
2) If we don’t know about complete implementation just we have partial implementation then we
should go for abstract.
3) If we know complete implementation and if we r ready to provide service then we should go for
concrete class

Encapsulation

If a class follows data hiding and abstraction such type of class is said to be ‘Encapsulated’ class.
Encapsulation = Data Hiding + Abstraction

The data members we have to declared as private. So that outside person is not allowed to access to directly
we have to provide Access to our data by defining setter and getter methods. i.e hiding data behind methods
is the central concept of encapsulation.


IS – A RelationShip

 Also known as ‘inheritance’.
 By using extends keyword we can implement inheritance.
 The main advantage is reusability.
Note:- parent class reference can be used to hold child class object but by using that reference we r not
allowed to call child class specific methods.

HAS – A RelationShip

 Also known as Composition or Aggregation .
 There is no specific keyword, but most of the cases we can implemented by using new keyword.
 Main advantage is reusability.


Method Overloading Interview Questions

Method overloading can be done by changing:

The number of parameters in two methods.
The data types of the parameters of methods.
The Order of the parameters of methods.
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile time error.
If both methods have same parameter types, but different return type, then it is not possible.


Can we overload static methods?
The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters. For example, consider the following Java program.

Method overloading and null error in Java

public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }

    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();

        // This line causes error
        mv.fun(null);
    }
}
Output :

22: error: reference to fun is ambiguous
        mv.fun(null);
          ^
  both method fun(Integer) in Test and method fun(String) in Test match
1 erro


The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null.
This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding.


public class Test
{
    // Overloaded methods
    public void fun(Integer i)
    {
        System.out.println("fun(Integer ) ");
    }
    public void fun(String name)
    {
        System.out.println("fun(String ) ");
    }

    // Driver code
    public static void main(String [] args)
    {
        Test mv = new Test();
       
        Integer arg = null;

        // No compiler error
        mv.fun(arg);
    }
}
Output :

fun(Integer )
In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that.

Note: This problem wouldn’t persist when the overriden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it.


In the case of overloading if there is no method with the required argument then the compiler won’t raise immediately compile time error. First it will promote arguments to next level and checks is there any matched method with promoted arguments, if there is no such method compiler will promote the argument to the next level and checks for the matched method. After all possible promotions still the compiler unable to find the matched method then it raises compile time error.
The following is the list of all possible Automatic promotion.









In the case of overloading the more specific version will get the chance first.

package com.agreeya.utils;

public class OOConcept {

public void m1(String s) {
System.out.println("String Version");
}

public void m1(Object o) {
System.out.println("Object Version");
}

public static void main(String arg[]) {
OOConcept t = new OOConcept();
t.m1("raju");
t.m1(new Object());
t.m1(null);
}

}

String Version
Object Version
String Version




package com.agreeya.utils;

public class OOConcept {

public void m1(String s) {
System.out.println("String Version");
}

public void m1(StringBuffer sb) {
System.out.println("StringVersion");
}

public static void main(String arg[]) {
OOConcept t = new OOConcept();
t.m1("raju");  - > String Version // when the next line is commented
t.m1(null);  -> Compilation Error
}

}


Note:- we can define a single method which can be applicable for any type of primitive argument, as
follows
m1(double d)
By automatic promotion instead of double we can give char, byte, short, int, long, float, double.
Based on the same approach square root method in math class is declared.
public static double sqrt(double d)
If we want to declare a method which can be applicable for byte, short, char, int, long we should declare as
follows.
m1(long)



public void m1(int i, float f)
{
System.out.println("int, float");
}
public void m1(float f, int i)
{
System.out.println("float, int");
}
public static void main(String arg[])
{
Test t = new Test();
t.m1(10.5f, 10);
t.m1(10, 10.5f);
t.m1(10, 10); // C.E : reference to m1() is ambiguous
t.m1(10.5f, 10.5f);// C.E : can’t find symbol method m1(float,float)
}



class Animal
{
}
class Monkey extends Animal
{
}
class Test
{
public void m1(Animal a)
{
System.out.println("Animal Version");
}
public void m1(Monkey m)
{
System.out.println("Monkey Version");
}
public static void main(String arg[])
{
Test t = new Test();
Case1: Animal a = new Animal();
t.m1(a); //Animal Version
Case2: Monkey m = new Monkey();
t.m1(m); //Monkey Version
Case3: Animal a1 = new Monkey();
t.m1(a1); //Animal Version
}
}
Overloading method resolution will always take care by compiler based on the reference type but not based on runtime object.


Note: In case of wrapper classes, wither it should be exact match or the parent class should match. It means Short is not compatible with Interger, but both are compatible with Number class and Object Class.


1. Primitive Widening > Boxing > Varargs.
2. Widening and Boxing (WB) not allowed.
3. Boxing and Widening (BW) allowed.
4. While overloading, Widening + vararg and Boxing + vararg can only be used in a mutually exclusive manner i.e. not together.
5. Widening between wrapper classes not allowed

Method Overloading with Autoboxing and Widening in Java


Method Overloading with Autoboxing

// Java program to illustrate 
// Autoboxing 
// while resolving data type as: 
// a)reference b)primitive 
import java.io.*; 

public class Conversion 
// 1.overloaded method with primitive formal argument 
public void method(int i) 
System.out.println("Primitive type int formal argument :" + i); 
// overloaded method with reference formal argument 
public void method(Integer i) 
System.out.println("Reference type Integer formal argument :" + i); 
// 2. overloaded method primitive formal argument 
// and to be invoked for wrapper Object as overloaded method 
// with wrapper object of same(Long) type as an argument is not 
// available. 
public void method(long i) 
System.out.println("Primitive type long formal argument :" + i); 

class GFG 
public static void main (String[] args) 
Conversion c = new Conversion(); 
// invoking the method with different signature. 
c.method(10); 
c.method(new Integer(15)); 
c.method(new Long(100)); 
// Using short will give, argument mismatch; 
// possible lossy conversion from int to short 
// c.method(new Short(15)); 

Output:

Primitive type int formal argument :10
Reference type Integer formal argument :15
Primitive type long formal argument :100

Method Overloading with Widening

// Java program to illustrate method 
// overloading 
// in case of widening 
import java.io.*; 

public class Conversion 
// overloaded method 
public void method(int i) 
System.out.println("Primitive type int formal argument :" + i); 
// overloaded method primitive formal argument 
// and to be invoked for wrapper Object as 

public void method(float i) 
System.out.println("Primitive type float formal argument :" + i); 

class GFG 
public static void main (String[] args) 
Conversion c = new Conversion(); 
// invoking the method with signature 
// has widened data type 
c.method(10); 
c.method(new Long(100)); 


Output:

Primitive type int formal argument :10
Primitive type float formal argument :100.0


Method Overloading with Widening and Boxing Together

Widening of primitive type has taken priority over boxing and var-args. But widening and boxing of primitive type can not work together.

// Java program to illustrate method 
// overloading for widening 
// and autoboxing together 
import java.io.*; 

public class Conversion 
// overloaded method with reference type formal argument 
public void method(Integer a) 
System.out.println("Primitive type byte formal argument :" + a); 

class GFG 
public static void main (String[] args) 
Conversion c = new Conversion(); 
// invoking the method 
byte val = 5; 
c.method(val); 


Output:

25: error: incompatible types: byte cannot be converted to Integer
        c.method(val);
                 ^
 Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

But boxing followed by widening is acceptable if this is passed to a reference of type Object. See the following example for this.

// Java program to illustrate 
// autoboxing followed by 
// widening in reference type 
// variables 
import java.io.*; 

public class Conversion 
// overloaded method with reference type 
// formal argument 
public void method(Object b) 
// Object b is typecasted to Byte and then printed 
Byte bt = (Byte) b; 
System.out.println("reference type formal argument :" + bt); 

class GFG 
public static void main (String[] args) 
Conversion c = new Conversion(); 
byte val = 5; 
// b is first widened to Byte 
// and then Byte is passed to Object. 
c.method(val); 


Primitive type byte formal argument :5


Method Overloading with Var-args argument

Widening of primitive type gets more priority over var-args.

// Java program to illustrate 
// method overloading for var-args 
// and widening concept together 
import java.io.*; 

public class Conversion 
// overloaded method primitive(byte) var-args formal argument 
public void method(byte... a) 
System.out.println("Primitive type byte formal argument :" + a); 
// overloaded method primitive(int) formal arguments 
public void method(long a, long b) 
System.out.println("Widening type long formal argument :" + a); 

class GFG 
public static void main (String[] args) 
Conversion c = new Conversion(); 
// invokes the method having widening 
// primitive type parameters. 
byte val = 5; 
c.method(val,val); 


Output:

Widening type long formal argument :5




Sunday, October 6, 2019

JAVA Memory Model Quick Reference Guide

Following are points you need to consider about memory allocation in java.

Note: Object and Object references are different things.

1)There is new keyword in java used very often to create new object. But what new does is allocate memory for the object of class you are making and returns a reference.

That means whenever you create an object as static or local, it gets stored in HEAP.

2) All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.

3) Classes loaded by classloader and static variables and static object references are stored in a special location in heap which permanent generation.

4) Local primitive variables, local object references and method parameters are stored in Stack.

5) Local Functions (methods) are stored in stack but Static functions(methods) goes in permanent storage.

6) All the information related to a class like name of the class, Object arrays asscociated with the class, internal objects used by JVM (like java/lang/Object) and optimization information goes into the Permanent Generation area.

7) To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems


NOTE :Permanent Generation area has been removed in JAVA 8. All the things which were getting stored in permgen are now moved to Metaspace memory area, which is part of native memory.

Java (JVM) Memory Model – Memory Management in Java

Java Memory Model, JVM Memory Model, Memory Management in Java, Java Memory Management

As you can see in the above image, JVM memory is divided into separate parts. At broad level, JVM Heap memory is physically divided into two parts – Young Generation and Old Generation.

Memory Management in Java – Young Generation
The young generation is the place where all the new objects are created. When the young generation is filled, garbage collection is performed. This garbage collection is called Minor GC. Young Generation is divided into three parts – Eden Memory and two Survivor Memory spaces.

Important Points about Young Generation Spaces:


Most of the newly created objects are located in the Eden memory space.
When Eden space is filled with objects, Minor GC is performed and all the survivor objects are moved to one of the survivor spaces.
Minor GC also checks the survivor objects and move them to the other survivor space. So at a time, one of the survivor space is always empty.
Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually, it’s done by setting a threshold for the age of the young generation objects before they become eligible to promote to Old generation.


Memory Management in Java – Old Generation
Old Generation memory contains the objects that are long-lived and survived after many rounds of Minor GC. Usually, garbage collection is performed in Old Generation memory when it’s full. Old Generation Garbage Collection is called Major GC and usually takes a longer time.

Stop the World Event
All the Garbage Collections are “Stop the World” events because all application threads are stopped until the operation completes.

Since Young generation keeps short-lived objects, Minor GC is very fast and the application doesn’t get affected by this.

However, Major GC takes a long time because it checks all the live objects. Major GC should be minimized because it will make your application unresponsive for the garbage collection duration. So if you have a responsive application and there are a lot of Major Garbage Collection happening, you will notice timeout errors.

The duration taken by garbage collector depends on the strategy used for garbage collection. That’s why it’s necessary to monitor and tune the garbage collector to avoid timeouts in the highly responsive applications.

Memory Management in Java – Java Garbage Collection
Java Garbage Collection is the process to identify and remove the unused objects from the memory and free space to be allocated to objects created in future processing. One of the best features of Java programming language is the automatic garbage collection, unlike other programming languages such as C where memory allocation and deallocation is a manual process.

Garbage Collector is the program running in the background that looks into all the objects in the memory and find out objects that are not referenced by any part of the program. All these unreferenced objects are deleted and space is reclaimed for allocation to other objects.

One of the basic ways of garbage collection involves three steps:

Marking: This is the first step where garbage collector identifies which objects are in use and which ones are not in use.
Normal Deletion: Garbage Collector removes the unused objects and reclaim the free space to be allocated to other objects.
Deletion with Compacting: For better performance, after deleting unused objects, all the survived objects can be moved to be together. This will increase the performance of allocation of memory to newer objects.
There are two problems with a simple mark and delete approach.


First one is that it’s not efficient because most of the newly created objects will become unused
Secondly objects that are in-use for multiple garbage collection cycle are most likely to be in-use for future cycles too.
The above shortcomings with the simple approach is the reason that Java Garbage Collection is Generational and we have Young Generation and Old Generation spaces in the heap memory. I have already explained above how objects are scanned and moved from one generational space to another based on the Minor GC and Major GC.

Memory Management in Java – Java Garbage Collection Types
There are five types of garbage collection types that we can use in our applications. We just need to use the JVM switch to enable the garbage collection strategy for the application. Let’s look at each of them one by one.

Serial GC (-XX:+UseSerialGC): Serial GC uses the simple mark-sweep-compact approach for young and old generations garbage collection i.e Minor and Major GC.
Serial GC is useful in client machines such as our simple stand-alone applications and machines with smaller CPU. It is good for small applications with low memory footprint.

Parallel GC (-XX:+UseParallelGC): Parallel GC is same as Serial GC except that is spawns N threads for young generation garbage collection where N is the number of CPU cores in the system. We can control the number of threads using -XX:ParallelGCThreads=n JVM option.
Parallel Garbage Collector is also called throughput collector because it uses multiple CPUs to speed up the GC performance. Parallel GC uses a single thread for Old Generation garbage collection.

Parallel Old GC (-XX:+UseParallelOldGC): This is same as Parallel GC except that it uses multiple threads for both Young Generation and Old Generation garbage collection.
Concurrent Mark Sweep (CMS) Collector (-XX:+UseConcMarkSweepGC): CMS Collector is also referred as concurrent low pause collector. It does the garbage collection for the Old generation. CMS collector tries to minimize the pauses due to garbage collection by doing most of the garbage collection work concurrently with the application threads.
CMS collector on the young generation uses the same algorithm as that of the parallel collector. This garbage collector is suitable for responsive applications where we can’t afford longer pause times. We can limit the number of threads in CMS collector using -XX:ParallelCMSThreads=n JVM option.

G1 Garbage Collector (-XX:+UseG1GC): The Garbage First or G1 garbage collector is available from Java 7 and its long term goal is to replace the CMS collector. The G1 collector is a parallel, concurrent, and incrementally compacting low-pause garbage collector.
Garbage First Collector doesn’t work like other collectors and there is no concept of Young and Old generation space. It divides the heap space into multiple equal-sized heap regions. When a garbage collection is invoked, it first collects the region with lesser live data, hence “Garbage First”. You can find more details about it at Garbage-First Collector Oracle Documentation.

Memory Management in Java – Java Garbage Collection Monitoring
We can use the Java command line as well as UI tools for monitoring garbage collection activities of an application. For my example, I am using one of the demo application provided by Java SE downloads.

If you want to use the same application, go to Java SE Downloads page and download JDK 7 and JavaFX Demos and Samples. The sample application I am using is Java2Demo.jar and it’s present in jdk1.7.0_55/demo/jfc/Java2D directory. However this is an optional step and you can run the GC monitoring commands for any java application.

Command used by me to start the demo application is:


pankaj@Pankaj:~/Downloads/jdk1.7.0_55/demo/jfc/Java2D$ java -Xmx120m -Xms30m -Xmn10m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseSerialGC -jar Java2Demo.jar
jstat
We can use jstat command line tool to monitor the JVM memory and garbage collection activities. It ships with standard JDK, so you don’t need to do anything else to get it.

For executing jstat you need to know the process id of the application, you can get it easily using ps -eaf | grep java command.


pankaj@Pankaj:~$ ps -eaf | grep Java2Demo.jar
  501 9582  11579   0  9:48PM ttys000    0:21.66 /usr/bin/java -Xmx120m -Xms30m -Xmn10m -XX:PermSize=20m -XX:MaxPermSize=20m -XX:+UseG1GC -jar Java2Demo.jar
  501 14073 14045   0  9:48PM ttys002    0:00.00 grep Java2Demo.jar
So the process id for my java application is 9582. Now we can run jstat command as shown below.


pankaj@Pankaj:~$ jstat -gc 9582 1000
 S0C    S1C    S0U    S1U      EC       EU        OC         OU       PC     PU    YGC     YGCT    FGC    FGCT     GCT
1024.0 1024.0  0.0    0.0    8192.0   7933.3   42108.0    23401.3   20480.0 19990.9    157    0.274  40      1.381    1.654
1024.0 1024.0  0.0    0.0    8192.0   8026.5   42108.0    23401.3   20480.0 19990.9    157    0.274  40      1.381    1.654
1024.0 1024.0  0.0    0.0    8192.0   8030.0   42108.0    23401.3   20480.0 19990.9    157    0.274  40      1.381    1.654
1024.0 1024.0  0.0    0.0    8192.0   8122.2   42108.0    23401.3   20480.0 19990.9    157    0.274  40      1.381    1.654
1024.0 1024.0  0.0    0.0    8192.0   8171.2   42108.0    23401.3   20480.0 19990.9    157    0.274  40      1.381    1.654
1024.0 1024.0  48.7   0.0    8192.0   106.7    42108.0    23401.3   20480.0 19990.9    158    0.275  40      1.381    1.656
1024.0 1024.0  48.7   0.0    8192.0   145.8    42108.0    23401.3   20480.0 19990.9    158    0.275  40      1.381    1.656
The last argument for jstat is the time interval between each output, so it will print memory and garbage collection data every 1 second.

Let’s go through each of the columns one by one.

S0C and S1C: This column shows the current size of the Survivor0 and Survivor1 areas in KB.
S0U and S1U: This column shows the current usage of the Survivor0 and Survivor1 areas in KB. Notice that one of the survivor areas are empty all the time.
EC and EU: These columns show the current size and usage of Eden space in KB. Note that EU size is increasing and as soon as it crosses the EC, Minor GC is called and EU size is decreased.
OC and OU: These columns show the current size and current usage of Old generation in KB.
PC and PU: These columns show the current size and current usage of Perm Gen in KB.
YGC and YGCT: YGC column displays the number of GC event occurred in young generation. YGCT column displays the accumulated time for GC operations for Young generation. Notice that both of them are increased in the same row where EU value is dropped because of minor GC.
FGC and FGCT: FGC column displays the number of Full GC event occurred. FGCT column displays the accumulated time for Full GC operations. Notice that Full GC time is too high when compared to young generation GC timings.
GCT: This column displays the total accumulated time for GC operations. Notice that it’s sum of YGCT and FGCT column values.
The advantage of jstat is that it can be executed in remote servers too where we don’t have GUI. Notice that the sum of S0C, S1C and EC is 10m as specified through -Xmn10m JVM option.

Java VisualVM with Visual GC
If you want to see memory and GC operations in GUI, then you can use jvisualvm tool. Java VisualVM is also part of JDK, so you don’t need to download it separately.

Just run jvisualvm command in the terminal to launch the Java VisualVM application. Once launched, you need to install Visual GC plugin from Tools -< Plugins option, as shown in below image.

VisualVM-Visual-GC-Plugin

After installing Visual GC, just open the application from the left side column and head over to Visual GC section. You will get an image of JVM memory and garbage collection details as shown in below image.

Serial-GC-VisualGC

Java Garbage Collection Tuning
Java Garbage Collection Tuning should be the last option you should use for increasing the throughput of your application and only when you see a drop in performance because of longer GC timings causing application timeout.

If you see java.lang.OutOfMemoryError: PermGen space errors in logs, then try to monitor and increase the Perm Gen memory space using -XX:PermGen and -XX:MaxPermGen JVM options. You might also try using -XX:+CMSClassUnloadingEnabled and check how it’s performing with CMS Garbage collector.

If you see a lot of Full GC operations, then you should try increasing Old generation memory space.

Overall garbage collection tuning takes a lot of effort and time and there is no hard and fast rule for that. You would need to try different options and compare them to find out the best one suitable for your application.

That’s all for Java Memory Model, Memory Management in Java and Garbage Collection, I hope it helps you in understanding JVM memory and garbage collection process.