Test your core java knowledge – part 2

1.How HashMap works?
2.When to override hashcode() and equals().
3.How to make an object immutable?
4.Difference between creating String new() and literal
5.Difference between abstract class and interface.
6.Difference between abstraction and encapsulation.
7.why wait() notify and notifyall() are in object class?
8.transient and volatile keywords.
9.Difference between iterator and lisiterator.(Class and interface hierarchy)
10.Deep copy and shallow copy.
11.sleep() and wait() difference.
12.access modifiers.
13.Garbage collection. how to call it? does it always work?
14.Collection Hierarchy and exception class hierarchy.
15.Why collection doesnt extend serializable and cloneable?(What are marker interfaces?)
16.Why map doesnt extend collection interface?
17.Difference between collections questions.
18.How hashset works?
19.how many Null element added in hashset and treeset.
20.Difference between implements runnable and extend thread.
21.join() and yield()
22.Writing a deadlock and resolving.
23.producer and consumer problem.
24.overriding of methods like main(),static, abstract. Overriding and overloading rules.
25.how string pool works?memory management.intern().
26.widening and narrowing in inheritance and exception classes.
27.can we override wait() or notify() methods?
28.Heapoutofmemory : reasons, fixings, best practices
29. Singleton class. singleton in multithreaded
30.executors thread pool concepts.
31.Dynamic dispatch(static binding and dynamic binding)

32.Java passby value or reference – for java script?
0.1+0.2=? Why BigDecimal, Float etc IEEE7
33.”Semapore vs Lock, which controls the thread? OS?
34.What type of mechanism followed Preemptieve. How the contect swithing happens?”
35.Spring MVC – how do you control DOS attack? Header
36.jquery – how to apply style for all paragraphs
37.single java script minimized or multiple?
38.wht stack flow error?
39.What Ioc? Why Proxy used?


Refresh your core Java knowledge

  1. Explain about strategy pattern with code.
  2. write interface for strategy

2.implement strategy for two different strategies

3.write a context class to use strategy

  1. pass strategy into context class and call it
  2. Concurrent HashMap vs synchronized

Concurrent HashMap

1.You should use ConcurrentHashMap when you need very high concurrency in your project.

2.It is thread safe without synchronizing the whole map.

3.Reads can happen very fast while write is done with a lock.

4.There is no locking at the object level.

5.The locking is at a much finer granularity at a hashmap bucket level.

6.ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.

7.ConcurrentHashMap uses multitude of locks.

Synchronized HashMap

1.Synchronization at Object level.

2.Every read/write operation needs to acquire lock.

3.Locking the entire collection is a performance overhead.

4.This essentially gives access to only one thread to the entire map & blocks all the other threads.

5.It may cause contention.

6.SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.

  1. what does mean by Threadsafe.

Ensures that particular task object would complete without interruption by other Thread. It helps to complete the Task.

  1. How do you start a Thread?

by start method(), run method()

  1. How do you handle concurrency?





1.Executor framework

2.Synchronizer framework

3.Concurrent collections


5.Atomic variables




2.Thread Factory





7.Concurrent Collections

8.Atomic Variables


  1. Threadsafty

“A class is threadsafe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or

interleaving of the execution of those threads by the runtime environment,and with noadditional synchronization or

other coordination on the part of the calling code.”

  1. Explain Singleton Pattern.

“allows only a single object to ever be created

Private constructor

1.double checking synchronized way: Lazy Loading

  1. statis final – Eager Loading
  2. enum

Realtime Example

Java.lang.Runtime with getRuntime() method

Java.awt.Toolkit with getDefaultToolkit()

Java.awt.Desktop with getDesktop()

How to break singleton pattern?

  1. use different class loader
  2. use clone interface
  3. serialization – use readResolve to avoid

4.concurrent thread – use double locking  ”




  1. Explain about collection in Java. How do you handle dublicates?

Set – TreeSet – No dublicate

List- ArrayList, LinkedList – Ordered way

Map – HashMap, TreeMap, HashTable, Dictionary, ZKey value pair

Collection Interface

Collection c = new ArrayList() is better than List interface


HashMap – fast algorithem to retieve, no order

TreeMap – Keys sorted by ascending comparision order

LinkedHashMap- keeps the key in insertion order

ArrayList – excels randon access, slower insert or removing elements

LinkedList – good at insertion and deletions from the middle of a List


The concept of an Iterator (another design pattern) can be used to achieve this abstraction. An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence. works only on forward direction

ListIterator – works on both direction

LinkedList supports both queue and stack

  1. why concurrency?

Improve resource utilization/ Time Efficiency

Parallel Task

Handle Blocking I/O easily

  1. hierachcal DB handle in core hava – write a program to handle in Memory
  2. flight schedule – Write Java program
  3. static vs instance

static – class level

–  static method cannot be overridden

– executes only once

intance – object level

Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it.

Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

  1. annotation – how it works?

Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.

  1. add @Marker in interface where you wanted to make it as annotation 2. Add annototed interface at required places

Retention Policy to decide compile or runtime 3. write annotation processor ( uses reflection)

4.Build Jar

  1. What is mean by String is immutable?

StringPool- Special Storage area in heap, if the string created and if it already has variable, it will be returned.

Allow string to cache its hashcode – This helps in hashmap for storage object, string play as better key.

Security – many db, networking connections uses string as name. Changing would lead to security issues.The same case for Reflection.

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues

Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).



  1. How can you make class as immutable?



  1. Why String is immutable?
  2. how to pass object from m/c to m/c? RMI, serialization
  3. Can we override static method?

No. we cannot.No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding.


Read more: http://java67.blogspot.com/2012/08/can-we-override-static-method-in-java.html#ixzz3kxdkRXwI

  1. factory vs builder

both are creational pattern

Factory – provide single or family of related objects

builder – crafts complex different types of objects step by step, construction process helps to create different forms of objects.

  1. depth questions on multithreading code
  2. counter in core java
  3. Class Path issue –

Parent First, Parent Last, Depends on App Server

how do you solve class path issue?



  1. Explain about JVM and GC


Abstract computing m/c to run java program

HotSpot – ClassLoader with JRE

– Just In Compilation –  dynamic translation, is

compilation done during execution of a program – at run time –

rather than prior to execution.

– Adaptieve Optimization – Dynamic compilation

Class Loader

JVM Memory

Method Area(Shared among all threads(global), shared

class structures like field,method data,code for methods and


Permannent Generation

Runtime Constant Pool

Field & Method Area



Heap(Shared among all threads(global), stores all

created objects and arrays)

Younger Generation


Eden – New/short-term objects are instantiated

in the eden space

From Survivor 0 -Survived/mid-term objects are

copied from the eden space to the survivor space.

From Survivor 1

Old Generation – Tenured/long-term objects are

copied from the survivor to the old generation space.



JVM Language Stacks

PC Registers

Native Method Stacks


Execution Enginge

Native Method Interface

Native Method Libraries

Code Cache

Thread 1..N( Private stack(local), Holds reference

to object in heap, stores local variables of primitive types)



Native Stack




***“In each thread stack the program is executed

referring to the Java logic in the method area and the object

data in the heap space”.****


How GC works?




– collection is performed frequently

– collection is focused more on speed efficiency.


— collection is performed less or in-frequently

– collection is focused more on time efficiency.

– very large


Most objects live for a short period.

Only few old objects have references to young objects.


GC algorithems

  1. Serial – works by holding all application thread(freeze all


– designed for single threaded environtmnet

– doesn’t suitable for server, and suitable for

commandline programs

  1. Parallel – default GC

– halts application thread, but uses multiple thread

  1. CMS
  2. mark live objects by start with root(thread stack, global

references and static variables)

2.In the sweep phase of the Mark-and-Sweep algorithm all

unreachable objects are declared as free memory.


  1. Uses more memory compared with Parallel.Better GC incase

of more CPU.

  1. CMC – avoids fragmentation by moving objects
  2. G1 – used for large heap memory areas

separate Heaps into region


  1. What are new feature and JDK 7 and are you aware about JDK 8 enhancements?

Java 5 Tiger

Generics – Provids compile type safety for collections



Enumerations – Typesafe


Enhanced for loops

improved memory model

concurrent utils

Java 6 Mustang

JavaScript integration in platform

Java compiler API

Java 7 Dolphin

Strings in switch

automatic resource managemnet in try-statement

Java 8


date and time api

parallel operations

pipeline and streams

  1. “Have to build your own implementation of thread pool?

ExecutorService executor = Executors.newThreadPool(5);

Runnable worker = new WorkerThread(i);


  1. Did you sometime try to build your own web server in Java?”
  2. Give few examples where you wrote Abstract Base classes?

Abstact vs Interface

Abstract – provide IS A, this can be used when sub classes need

default functionality .If the base class is changed often abstarct class is the best approach.

Framework is the best place where we can use it for Abstarct class.

Interface – 1.Can do like this- used for common functionality need to be shared with unrelated classes. but different implementation.

Contains variable static final. Design By Contract.

Supports Runtime polymorphism.

Avoid hierarchical type framework frequent changes in interface break the implementation.Everything should be done at first

Composition vs Inheritence

Inheritance – compile time – IS A

Composition – Runtime

runtime – HAS A

  1. write own arraylist

two approaches. Simple class having most of them static methods and second java inheritance and polymorphism based.

  1. Draw process flow of JVM and explain each component?
  2. Draw and explain each functions of GC
  3. Explain thread locking

Intrinisic Lock: Every object in Java has Monitor, when synchronized key word applied, it locks the object. For static method, it applies on Class


Drawbacks of Intrinisic Locks:

  1. not possible to interrupt a thread waiting to acquire a lock(lock interruptly)
  2. not possible to attempt to acquire a lock without being willing to wait for it forever(try lock)

3.Cannot implement non-block-structured locking disciplines.

  1. DeadLock situations can occur.


Reentrant Lock – allows the thread to re-aquire the same lock multiple times.1)Polled and Timed Lock aquisitions, 2)Interruptable Lock aquisitions, 3)Non-block structure locking, 4)Fairness.



  1. What are the main steps you do when using JAXB?



Marshalling – POJO to XML

UnMarshalling- XML to POJO


  1. What is WeakHashmap and why do we use it?

A weak reference, simply put, is a reference that isn’t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself.

Reference Queue – Keep track of Weak References.

Soft References – Same as weak, but it will stay in memory for sometime.

Phantom References – A phantom reference is one of the strengths or levels of ‘non strong’ reference defined in the Java programming language; the others being weak and soft.[1] Phantom reference are the weakest level of reference in Java; in order from strongest to weakest, they are: strong, soft, weak, phantom.

An object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.s



  1. How do you decide Thread Pool Size?
  2. Number of processors
  3. Extra overhead for thread swicth

Formula 1 for simpler Tasks

Thread Pool Size = Number of processors +1

int poolSize  = Runtime.getRuntime().availableProcessors() + 1;

Formula 2: Consider I/O or other blocking operations

N = Number of processor available in system.

U = Target utilization of CUP; 0 >= U <= 1.

W/C = Ration of wait and computation time.

Number of threads for thread pool can evaluate by this formula:

Number of Threads = N * U * (1 + W/C)

Formula 3: Amadhals Law


P – proportion of task excuted on parallel.N – number of processors



  1. “Threaddumb structure
  2. Why we need threaddump?”

healthy vs non-healthy(stuck)

JVM Threads

Application Thread

Thread Status

Thread Life status


Why Threaddumb analysis?

appln and java concurrency problems

root cause of performamce problems

respose time contributors / performamce bottlenecks

impact of JVM pause on appln threads

  1. Diff b/w User Thread and Daemon Thread

Daemon thread exit when main thread exits.

User Thread continues after Main thread exits



  1. Explicit vs Intrinisc Lock


  1. What is volatile?

Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

  1. Mutax vs Synchronizer block

it is called Mutex if only one person allow to watch the play

it is called Semaphore if N number of people allow to watch the play.If anybody leave the Theater during the play then other person can be allowed to watch play.

it is called CountDownLatch if no one allowed to enter until every person vacate the theater.Here each person has freewill to leave the theater. One or More Threads wait for other set of Threads to complete set of tasks.`

it is called Cyclicbarrier if theater will not start until every person enter in theater. Here showman can not start the show until all the person enter and grab the seat . Once the play finish same barrier will apply for next show

One or More thread in a group to complete certain set of tasks before start the next tasks.


Here , person is Thread , Play is resource.