Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Friday 30 August 2013

Top Most Interview Questions when 5 or 6 years of Java/J2EE experience


Generally there were some basic questions:
1. java Objective SCJP level
2. J2EE objective
3. JMS Objective
4. IBM MQ Objective
5. Complicated Multithreading
6. Serialization, File I/O
Below are some extract of questions which I faced while giving Interview of Sapient, Nomura, Gemstone, Mobility, ION, HP, RBS, TIBCO, BOA, CSC. 

Generally I have seen if the interview is for an Investment Bank or any product based organization, then core concepts are very important. And since 2008and just adding this line in 2013 I would say most important concept stills remains Multi threading. And so Executer framework remains hot.

CSC, Chennai
1. 50 numbers ( 1 to 50 ) are distributed in random order in an array of size 50. One number is missing. How to find.
2. Inner Classes, Anonymous Classes.
3. Find manager name who has max. number of employees working under him, when table has employeedID, Name, and ManagerID as columns. and Manager can also be employee.
4. Serialization.
5. How to design a web application, medium size.
6. Write logic to print alternate elements in a ArrayList, even some are removed.
7. How to implement a Hospital scenario, where doctor is examining patients, and emergency cases, and informing doctor of emergency cases, scheduling, etc.
 8. How to select unique elements from a table.
9. Calculate number of legs, and give formula:
7 persons, each person having 7 bags, each bag having 7 dogs, and each dog having 7 puppies.
Bank Of America, Mumbai
1. How is semaphore implemented.
2. How to ensure only one instance in Singleton class.
3. How synchronization works, inside JVM.
4. Master JVM is holding objects. Slave JVM's are reading and writing the object.
What problems can come and what is solution.
5. How Garbage Collection works in JVM.
6. When are class garbage collected, when are classes unloaded.
7. How to ensure that instance is never garbage collected.
8. Different protocols for Web Services.
9. Managing Session in Web Services
10. RMI, how EJB works
11. passing objects between two JVM's.
12. role of WSDL, stubs, etc. in Web Services.
13. Garbage Collection Tuning parameters.
14. LAZY Loading in ORM.
15. Why there is Stack and heap in JVM. Why this structure.
16. how much memory a program consumes, when no objects created inside program.
1. JCA - Tntro
2. JPA - Intro
3. EAGER/ LAZY loading
4. JPA relations
5. IBM MQ Objective
6. JMS session, Thread Safety In JMS
7. JMS providers
8. JMS implementation
9. AQ Provider and implementation using JNDI
10. Garbage Collection algorithms.
11. SOAP
12. JTA.
RBS, Gurgaon
1. Hashing Algorithm.
2. Search Algorithm
3. MVC design Pattern.
4. Multi threading Objectives.
5. Design Application which handles a particular operation for millions of trades, operation like trade validation. Application communicates external application for data.
6. Several Designing Questions.
7. Scala, Open Source high performing JMS implementations, Dynamic languages
8. Cache Implementation.
9. How Oracle Coherence works.
Gemstone, Pune
1. Why Use EJB 3.0
2. Why use JPA
3. Why use JPA with ORM, Standard ORM products
4. Writing Complex Query while using JPA and ORM
5. JTA, how it works
6. JTA, how to use
7. Where to use JDBC and where ORM
8. JSF Architecture, who is model, view and controller
9. Optimistic Lock in JPA - Detailed
10. Multithreaded program to read large file/ code and design
HP Labs, Banglore
1. Latch, Barrier, synchronized, Lock, ThreadPoolExecuter, Garbage Collection Algo.
2. Which forums do you follow,  Cloud Computing, How to improve programming and Coding skills.
3.  Design horse racing application.
4. Struts, how to extend struts. Why to use Struts.
5.  Where to use messaging
1. Core Java SCJP level
2. Current Project Architecture
3. Message Flow in current project.
4. Fault Tolerance in JMS
5. Hashing Algo in Java, HashMap
6. Aggregation, Composition, Encapsulation, Abstraction.
7. How to implement Thread Pool
8. Complete Garbage Colection Algo.
9. DataSource, DB connection pool - how it works.
10. Exception- Logic, how to handle and design Exception, Error.
11. NIO-concept, Socket handling using NIO.
12. Adapter Design pattern
13. Stored Proc, Trigger
14. JDK1.5 Thread pool
15. Serialization, Externalization
16. Immutable, FInal, Usage of Final and Immutable
17. Exception handling in the spawned threads
18. RESTful Web Services, JEEVAN
19. Types of Parsers
1. deep copy and shallow copy
2. hash code
3. graceful shutdown of threads
4. NaN, 0/0
5. wrapper classes.
6. BootStrap Class Loader
7. Oracle OCI.
8. Oracle JDBC drivers
9. Oracle Thin and Thick Clients.
10. Oracle Rak
11. MQ API, MQ classes for Java.
12. MessageId, Priority for MQ message.
13. Garbage Collection
14. Java Green Threads
15. Coorelated Sub Queries.
16. Steps to make connection to MQ using Java.
17. Options to set for browsing message in MQ Queue.
18. Client Mode/Bindings Mode.
19. Log4j
1. How would you implement your own Thread Pool.
2. What is NIO
3. Best way to read data from socket using traditional I/O
4. Beat way to read file.
5. How to read characters from InputStream.
6. How Serialization works
7. Synchronization
8. how to implement counter in servlet.
9. how hashtable is thread safe.
10. CharSet, Enocder, Decoder
11. AtomicInteger, volatile, transient.
12. JTA, XA, how XA works, two phase commit.
13. Role of transaction manager in XA transaction.
14. XADataSource, and closing XADataSource.
15. UserTransaction
16. JCA Architecture
1. How would you implement cache in java.
2. How would you implement auto complete using java, jsp.
3. How would you implement a chache with auto complete feature.
4. How to make class immutable.
5. How to serialize immutable class.
6. How to gaurantee message delivery in JMS, fault tolerance
7. Message recovery techniques and redelivery.
8. DROP table.
9. Oracle Stored Procedure or function
10. Struts architecture
11. JSP Exception Handling
12. java Objective SCJP Level
13. java Design Pattern
14. J2EE objective
15. Implementing references
16. UNIX Commands - grep, softlink, hardlink
17. Serializable, Externalizable, Cloneable
JDk 1.5 Collections classes.
Multintreading Concepts - Barrier, Latch, etc.
JMS functioning
SQl Query using JOINS
Java Design pattern - detail
Overloading, Overriding, Comparator, Comparable, hashCode(), equals(), Serializable, Externalizable, RMI, garbage Collection.
Please read my more posts in the same category - Answers Java/J2EE interview questions

Top Most java interview with Investment bank -4


This is another set of investment bank java interview questions. This interview was not attended by me but I got this these questions from one of my team mate, who passed these interviews to receive the IB job offer. Here the main focus area were again java collections, memory model, java 1.5 concurrency and design pattern.
  Always remember your first impression is the most important and everybody know what is the first question in all interviews. It is 'tell me about yourself' or' tell me about current project'. Be well prepared for this questions which sets the tone for rest of your interview. If you are taking telephonic interview be very clear that your voice should be clear and there should not be any background noise.

1) Tell me about career profile and describe your one of the main project?
   then deep drive into the current project.
  • Why u are using these technology like JMS, Concurrency, Spring in your application?
  •  What feathers of java 1.6 you are using in your current application?
  •  How you r managing concurrency in application? 
  •  How the exceptions are handled in your application?

2) Java collections - When to use ArrayList and Linked list?
Java Collection


3) Application wants to load static data with limited memory foot print and it should be refreshed after regular interval. Implement LRU Cache ?
LRU Cache Implementation

4) What is soft reference, weak reference, phantom reference?
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. It is used in java.util.WeakHashMap.
soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it areWeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.
phantom reference is quite different than either SoftReference or WeakReference. The object is marked for Garbage collection but it is finalised and have not yet reclaimed. The object is called as phantom reachable.  Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead.

5) How is memory management in java? how the heap is divided in different area?
Java Memory Mgmt

6) Where String literals are stored in heap?
Java Memory Mgmt

7) How to handle out of memory error and what tools we can use to figure out memory leaks?

8) What is Synchronization and locks in java 1.5?
Java 1.5 features

9) Explain new feathers in java 1.5 and java 1.6?
Java 1.5 features

There are a few new features in Java 1.6, but not many:
  • @Override annotations on methods specified by an interface
  • NavigableSetNavigableSetDeque
Those are the changes that I can think of.
Wait, there's more:
  • Pluggable Annotation Processing
  • Programmatically access to the compiler through ToolProvider 


10) How to do thread scheduling in java 1.5?
Java Concurrency

11) What are new concurrency classes in java 1.5?
Java Concurrency

12) Explain Singleton design pattern and what is double check locking (DCL)  and how to make singleton classes using volatile?
Design Pattern [Singleton]


13) What is the difference between correlated subqueries and uncorrelated subqueries?
Uncorrelated subquery is that the subquery can be run independently of the outer query. Basically, the subquery has no relationship with the outer query.
example :
select * from employee where id in (select employee_id from department where dept_id=10);
  Here sub query \ inner query is not dependent on outer query.
Correlated subquery has the opposite property – the subquery cannot be run independently of the outer query. 
SELECT *FROM Employee Emp1
WHERE (1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
What you will notice in the correlated subquery above is that the inner subquery uses Emp1.Salary, but the alias Emp1 is created in the outer query. This is why it is called a correlated subquery, because the subquery references a value in it’s WHERE clause (in this case, it uses a column belonging to Emp1) that is used in the outer query. 

14) If Parent class is Serializable, then Child class should be Serializable classs ?
yes, a subclass IS-A superclass, and hence child will also be IS-A Serializable too.
However, if the question is referring to an object actually being serializable, then maybe not, as it is possible for a subclass to provide readObject() and writeObject() methods, that thows a NotSerializableException.


Puzzle :
1) You are in one room at 5'th floor of building and it has 3 bulbs and the switch for these bulbs are in ground floor and you can go down only 1 time and Tell me how you know particular switch for each bulb? ,, tip --use bulb heating**
2) You have 1000 teams and each team plays knock out with each other, how many minimum matches we need to schedule to figure out winner?
3) Write the programme to get square root of 100? do not use java math Square root functions?

Management Round:
1) Tell me about yourself?
2) Why you want to leave current job?
3) Why you want to join this bank? ..[Get the history of bank and current CEO details and latest mergers]
4) Your key strengths and weakness?
5) Tell me how you were managing team?

HR Round:
1) Why would you like to leave current role?
2) What is your long term plan, how you would you like to growth your career?
[Answer of these Mgmt/HR Questions are listed here]Overall process took around 1.5 months from first round to final job offer. one more point there was onsite puzzle solving in first round using eclipse and we need to make Junit test cases to demonstrate the understanding of Test driven development.

More interview questions from investment bank job interviews

Important topic to prepare for Java interview:
1) JAVA 1.5 details

Banking development work requires analytical skills so you can be surprised by puzzles. Sample puzzles at listed in blog Frequently asked java puzzles

Top Most Java Memory Management

We are covering here -'Java garbage collection interview questions' or 'Java memory interview questions' in details. The topic is always asked to senior java developers to verify the java memory model understanding. In bigger project taking care of VM memory becomes very important due to more memory required at peak time processing in application.  

In this topic frequently asked questions are:

  • What is Garbage collection?
  • How to do analysis of java memory issues?
  • Explain Java memory model?
  • What are garbage collectors?
  • How to use java profilers?
  • Have you worked in application performance improvement?
  • What are the memory issues you have faced in your application?

Garbage Collection:


Garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.

Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. However, many systems use a combination of approaches, including other techniques such as stack allocation and region inference.

Resources other than memory, such as network sockets, database handles, user interaction windows, and file and device descriptors, are not typically handled by garbage collection. Methods used to manage such resources, particularly destructors, may suffice to manage memory as well, leaving no need for GC. Some GC systems allow such other resources to be associated with a region of memory that, when collected, causes the other resource to be reclaimed; this is called finalization. Finalization may introduce complications limiting its usability, such as intolerable latency between disuse and reclaim of especially limited resources, or a lack of control over which thread performs the work of reclaiming.

Memory is divided in mainly 3 areas:
  •  Young\Eden Generation : for newly created objects.
  •  Tenured Generation : for old objects which are survived after minor gc.
  •  Perm Space : for class definition, meta data and string pools.



At initialization, a maximum address space is virtually reserved but not allocated to physical memory unless it is needed. The complete address space reserved for object memory can be divided into the young and tenured generations.The young generation consists of eden and two survivor spaces. Most objects are initially allocated in eden. One survivor space is empty at any time, and serves as the destination of any live objects in eden and the other survivor space during the next copying collection. Objects are copied between survivor spaces in this way until they are old enough to be tenured (copied to the tenured generation). A third generation closely related to the tenured generation is the permanent generation which holds data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level.

Java objects are created in Heap and Heap is divided into three parts or generations of garbage collection in Java as mentioned above. New Generation is divided into three parts known as 
  •   Eden space
  •   Survivor 1 
  •   Survivor 2 space. 
When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is special and it is used to stores String pool,  Meta data related to classes and method in JVM.

Out Of Memory / OOM :
   If it happens in your application take it is opportunity to display your technical skills. In technical term it means the JVM does not have space to put objects in tenured space which are survived in minor collection and it stops working or responding due to no memory to do further processing.
 
These are terms used in context of java memory management:

  • Throughput is the percentage of total time not spent in garbage collection, considered over long periods of time. Throughput includes time spent in allocation (but tuning for speed of allocation is generally not needed).
  • Pauses are the times when an application appears unresponsive because garbage collection is occurring.
  • Footprint is the working set of a process, measured in pages and cache lines. On systems with limited physical memory or many processes, footprint may dictate scalability. 
  • Promptness is the time between when an object becomes dead and when the memory becomes available, an important consideration for distributed systems, including remote method invocation (RMI).
  • Heap Dump is a list of objects in the memory of JVM as well as the content of the memory occupied by those objects. It preserves the value of any attributes of the objects, including references to other objects. In other words, a heap dump gives you a complete picture of the memory.There are multiple tools that allow you to dump heap in a Java process:Some tools like VisualVM and memory profilers allow you to initiate a heap dump from the GUI, but you don’t need any fancy tools here—jmap will do just fine. As it provides the most general case, we'll use jmap in the next example.Before you dump heap, be sure to keep the following issues in mind:Note that the -F option, which will dump non-responsive programs, might be useful on UNIX systems, but is not available on Windows. Note also that JDK 6 includes the option +XX:+HeapDumpOnOutOfMemoryError that will dump heap whenever the OutOfMemoryError alert is encountered. This can be a useful option, but keep in mind that it has the potential to consume significant amounts of disk space.


The basic principles of garbage collection are:

  1. Find data objects in a program that cannot be accessed in the future
  2. Reclaim the resources used by those objects



   An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data.The blue area in the diagram below is a typical distribution for the lifetimes of objects. The X axis is object lifetimes measured in bytes allocated. The byte count on the Y axis is the total bytes in objects with the corresponding lifetime. The sharp peak at the left represents objects that can be reclaimed (i.e., have "died") shortly after being allocated. Iterator objects, for example, are often alive for the duration of a single loop.   


Application GC bytes allocation is shown in above picture. Majority of byte survival happens in Minor Collection and majority of objects are cleared in Major collections. Some objects do live longer, and so the distribution stretches out to the the right. For instance, there are typically some objects allocated at initialisation that live until the process exits. Between these two extremes are objects that live for the duration of some intermediate computation, seen here as the lump to the right of the initial peak. Some applications have very different looking distributions, but a surprisingly large number possess this general shape. Efficient collection is made possible by focusing on the fact that a majority of objects "die young".



Collectors

The Java HotSpot VM includes three different collectors, each with different performance characteristics.
  • The serial collector uses a single thread to perform all garbage collection work, which makes it relatively efficient since there is no communication overhead between threads. It is best-suited to single processor machines, since it cannot take advantage of multiprocessor hardware, although it can be useful on multiprocessors for applications with small data sets (up to approximately 100MB). The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC.
  • The parallel collector (also known as the throughput collector) performs minor collections in parallel, which can significantly reduce garbage collection overhead. It is intended for applications with medium- to large-sized data sets that are run on multiprocessor or multi-threaded hardware. The parallel collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseParallelGC.
  • Newparallel compaction is a feature introduced in J2SE 5.0 update 6 and enhanced in Java SE 6 that allows the parallel collector to perform major collections in parallel. Without parallel compaction, major collections are performed using a single thread, which can significantly limit scalability. Parallel compaction is enabled by adding the option -XX:+UseParallelOldGC to the command line.
  • The concurrent collector performs most of its work concurrently (i.e., while the application is still running) to keep garbage collection pauses short. It is designed for applications with medium- to large-sized data sets for which response time is more important than overall throughput, since the techniques used to minimize pauses can reduce application performance. The concurrent collector is enabled with the option -XX:+UseConcMarkSweepGC.

    VM Options for GC details:

    • -verbose:gc — prints basic information about GC to the standard output
    • -XX:+PrintGCTimeStamps — prints the times that GC executes
    • -XX:+PrintGCDetails — prints statistics about different regions of memory in the JVM
    • -Xloggc: — logs the results of GC in the given file.


      These Command line options are available via JMX to monitor VM memory-
      • -Dcom.sun.management.jmxremote — enables JMX monitoring
      • -Dcom.sun.management.jmxremote.port = — controls the port for JMX monitoring
      • com.sun.management.jmxremote.ssl
      • com.sun.management.jmxremote.authenticate
      • If you're using JDK 6, you can use tool called jmap on any platform.

        What is Garbage First Collector?

         Recently in one java interview, I was asked about Garbage First collector and Garbage First collector splits the heap up into fixed-size regions and tracks the live data in those regions. It keeps a set of pointers — the "remembered set" — into and out of the region. When a GC is deemed necessary, it collects the regions with less live data first (hence, "garbage first"). Often, this can mean collecting an entire region in one step: if the number of pointers into a region is zero, then it doesn't need to do a mark or sweep of that region.
            For each region, it tracks various metrics that describe how long it will take to collect them. You can give it a soft real-time constraint about pause times, and it then tries to collect as much garbage as it can in that constrained time.

        Technical description

        The G1 collector achieves high performance and pause time goals through several techniques.
        The heap is partitioned into a set of equal-sized heap regions, each a contiguous range of virtual memory. G1 performs a concurrent global marking phase to determine the liveness of objects throughout the heap. After the mark phase completes, G1 knows which regions are mostly empty. It collects in these regions first, which usually yields a large amount of free space. This is why this method of garbage collection is called Garbage-First. As the name suggests, G1 concentrates its collection and compaction activity on the areas of the heap that are likely to be full of reclaimable objects, that is, garbage. G1 uses a pause prediction model to meet a user-defined pause time target and selects the number of regions to collect based on the specified pause time target.
        The regions identified by G1 as ripe for reclamation are garbage collected using evacuation. G1 copies objects from one or more regions of the heap to a single region on the heap, and in the process both compacts and frees up memory. This evacuation is performed in parallel on multi-processors, to decrease pause times and increase throughput. Thus, with each garbage collection, G1 continuously works to reduce fragmentation, working within the user defined pause times. This is beyond the capability of both the previous methods. CMS (Concurrent Mark Sweep ) garbage collection does not do compaction. ParallelOld garbage collection performs only whole-heap compaction, which results in considerable pause times.
        It is important to note that G1 is not a real-time collector. It meets the set pause time target with high probability but not absolute certainty. Based on data from previous collections, G1 does an estimate of how many regions can be collected within the user specified target time. Thus, the collector has a reasonably accurate model of the cost of collecting the regions, and it uses this model to determine which and how many regions to collect while staying within the pause time target.

        Recommended Use Cases for G1

        The first focus of G1 is to provide a solution for users running applications that require large heaps with limited GC latency. This means heap sizes of around 6GB or larger, and stable and predictable pause time below 0.5 seconds.
        Applications running today with either the CMS or the ParallelOld garbage collector would benefit switching to G1 if the application has one or more of the following traits.
        • More than 50% of the Java heap is occupied with live data.
        • The rate of object allocation rate or promotion varies significantly.
        • Undesired long garbage collection or compaction pauses (longer than 0.5 to 1 second)

          Thursday 29 August 2013

          Top Most java interview with Investment bank - 5


          Getting a new job looks very tedious work and it needs the preparation. better you are prepared important topics and you have more chances of winning the interview. It is not just chance, its your hard work which makes way for you. After long time, again I started giving interviews for my next move. This time I am looking for more senior role similar to technical manager but still I need to clear java technical round and here are those questions:





          **Wining Attitude is the Key for interviews**




          Questions :-

          1) Your Current project and Role\ Responsibilities?

          2) Explain your current application and it's design?

          3) Explain JMS Transaction and how you can control transaction from you receive the message to persisting data into DB?

          4) How to handle DB transaction in Spring?

          5) What is benefits of Spring?

          6) HashMap VS TreeMap which one to use, how to decide?

          7) How to create immutable Objects?

          8) What is annotation and what is benefits?

          9) How JIXB xml parsing works?

          10) Threading, what happens if same object instance is read by two threads?

          11) If one reader thread and one writer thread act on one objects double variable and writer thread is trying to update the value from 4 to 5. if both does this call at same time what value reader thread will see for double variable?  [ Hint double writing is not atomic in java]

          12) If you have java application cache where  you have 1000 reads  but very less writes into cache, which locking you will you and how? tell me the class name?

          Suddenly interview moved to web application technology side and they asked these questions:

          1) What is application context in web app?

          2) What dispatcher servlet do in Spring mvc?


          Two design discussion

          1) Large file having text and how we can find the word count in the file and which collection to use?

          2) We have Professor , Course and Student table and one professor can take multiple course and one student can take multiple courses. How to find out which professor is having maximum students write query and table design?

          Best of luck for any upcoming interviews. Important topic to cover for interview -

          1) JAVA 1.5 details
          2) Java Collection Interview questions
          3) XML PArsing
          4) JDBC Interview Questions
          5) Hibernate interview questions
          6) Java Threading questions
          7) Java Concurrency questions.
          8) JMS interview questions.
          9) Spring Framework


          Wednesday 28 August 2013

          Top Most Answers and Questions for Interview when 5, 6, 7, 8 years exp. in Java/J2EE

          Few years back I posted - Interview Questions when 5 or 6 years of Java/J2EE experie
          Above post I wrote in 2012

          I am writing this post in 2013 and in past 3 years nothing significant changed in Java/J2EE. And I am sure in coming years still the hot topics for interview would remain same like Class loading, I/O, Multithreading, NIO in core java, and JSF tag, JMS concept, EJB concept would be in J2EE. 


          When I am taking interview of any 4 or 5 years java experienced person, my expectation is he should be familiar with NIO, Executer framework, Thread safety, ORM, messaging, JSF tags, web services, JSP/Servlet, and any framework. 

          But if experience is 6+ then expectation is bit higher and my most preferred questions are -
          Questions from Executer framework like semaphore, barrier, latch, thread pool, callable, etc. 
          Thread safety, Explicit locking, etc. 
          NIO
          Servlets thread safety, Servlets listeners. 
          ORM, why use ORM, which ORM to use, ORM with cache, problems in using ORM like Concurrency and persistence exceptions. 
          JAX-WS, web services, REST, where to use REST
          One framework is a must. 
          Cloud computing concept and architecture. 

          Messaging advanced, guaranteed delivery and integration, and where to use messaging and where to use web services. 

          This post is the continuation to my previous posts related to Java/J2EE interview questions. Where I want to provide answers to questions mentioned in that post, and also add more answers -



          Core Java -

          -----------

          50 numbers ( 1 to 50 ) are distributed in random order in an array of size 50.

          One number is missing. How to find.
          One approach
          Sort the array. Numbers are Integer. And in the place of missing there would be default value 0.
          We can iterate the array. Can take the zero's place, and the number before and after.
          And we know.

          Why use Inner class.

          I would say Inner class is never mandatory or necessary, there is always workaround
          But at some places they are convinience like in Map.Entry, Iterator inside List, or
          listener in GUI.
          The use is to increase encapsulation and hide some implementation details.
          Classes like Semaphore use internal objects for locking, etc.

          Serialization

          We are writing the Java object in a file, and again creating the java object by reading bytes form the file.
          Above is a kind of a persistence mechanism, but Serialization purpose is not persistence, there are DB's for that.
          Use of serialization is to transfer objects over network.
          We can write the Java object as byte array in memory, and later again construct the object from byte array in memory,
          OR we can write the object over socket, data is sent over wire to receiving socket, and there it would be constructed again.
          OR we convert Java objects in XML instances and later construct back from XML in SOAP context.
          Serialization is the mechanism used by RMI to pass objects between JVMs,
          either as arguments in a method invocation from a client to a server or as return values from a method invocation.
          We should know how to make class Serializable, and also about interface Externlizable.


          Printing alternate numbers where arraylist is getting modified 

          We can get a iterator, and we might get COncurrentModificationException.
          May be we should have used CopyOnWriteArrayList used to avoid that.


          How to implement a Hospital scenario, where doctor is examining patients, and emergency cases,

          and informing doctor of emergency cases, scheduling, etc.
          We can use a priority Queue.


          How to ensure only one instance in Singleton class.

          class Singleton
          {
            private static Singleton instance = new Singleton();

            private Singleton()

            {
              //...
            }

            public static Singleton getInstance()

            {
              return instance;
            }
          }
          Refer - http://www.ibm.com/developerworks/java/library/j-dcl/index.html

          Synchronization -

          Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access,
          including the local variables, parameters, and return values of each method the thread has invoked.
          All objects reside on the heap.There is only one heap inside the JVM, and all threads share it.
          Besides the Java stack and the heap, the other place data may reside in the JVM is the method area,
          which contains all the class (or static) variables used by the program.
          To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class.
          A lock is like a privilege that only one thread can "possess" at any one time.
          If a thread wants to lock a particular object or class, it asks the JVM.
          When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.
          The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code,
          making sure only one thread at a time executes the code.

          Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor,

          the thread must obtain a lock on the referenced object.
          In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization.
          Two opcodes, monitorenter and monitorexit, are used for synchronization blocks within methods, as shown in the table below.
          When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref
          on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed
          for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.
          - See more at: http://www.javaworld.com/javaworld/jw-07-1997/jw-07-hood.html?page=2#sthash.VWVX3ZYW.dpuf

          JGroup

          JGroups is a toolkit for reliable multicast communication.
          It can be used to create groups of processes whose members can send messages to each other
          The most powerful feature of JGroups is its flexible protocol stack


          Garbage Collection - 
          http://shekup.blogspot.in/2011/11/java-runtime-memory-management.html



          When are class garbage collected, when are classes unloaded.

          The only way that a Class can be unloaded is if the Classloader used is garbage collected. 

          How to ensure that instance is never garbage collected.

          A singleton kind of pattern. 
          There's a static reference to a singleton, so it won't be eligible for garbage collection until the 
          classloader is eligible for garbage collection.

          J2EE - 

          ------

          Lightweight J2EE web application

          A typical architecture for J2ee web application is
          Web layer - Business Layer - Database
          JSP - Servlet - Session Bean - Entity Bean
          which later evolved to
          JSF UI - JSF Backing Bean - EJB3 Session Bean - JPA
          Or using some implementation like ADF instead of JSF
          ADF - EJB3 Session Bean - JPA/Toplink
          OR, if using Struts -
          Struts - Business layer
          OR
          Spring MVC - JPA/Hibernate
          OR even
          JSF - Spring WebFlow - JPA/Hibernate
          Some used below
          Struts - Spring - Hibernate
          There was a recent survey done over web frameworks, and result is Spring MVC is most adopted framework
          (http://www.infoq.com/research/jvm-web-frameworks?utm_source=infoqresearch&utm_campaign=rr-content)
          Now remember and note there is one very imprtant layer in the front Client Technologies
          Client Technologies + Web Layer - Business layer - Persistence layer
          Client Technologies include HTML, CSS, Javascript, JQuery, Ajax, JSON, DOJO, REST, FLEX, etc.

          If I go more back and look into evolution


          HTML(high performance poor UI)

          -> CGI(dynamic content, low performance, still bit poor UI)
          -> JavaScript
          -> AJAX
          and somewhere Applets also came.
          But, Google changed the architecture of web applications, esp. when intorduced web applications like
          Google Map using JavaScript, AJAX, JSON,which is a web application but looks like Desktop with amazing UI.
          Google Maps used JavaScript extensively, where when user drags the map and grid squares are downloaded from the server.
          And Web application architecture started thinking of making CLIENT more rich.
          So, Web Architecture, which was
          CLIENT(HTML) - Server(View generation - Controllers - Service layer/Business layer - Repository)
          has changed to
          CLIENT(HTML & JS also DOM, controllers, objects) - Server(Service layer/Business layer - Repository)
          And there is a need to break big service layer into independent services,
          And may be independent services are dependent on other servics coming from platform or cloud.
          And now we consider where ever we can use REST.



          Web Services


          Different protocols for web services - 


          XML-RPC (RPC) - Its a simple, portable way to make remote procedure calls over HTTP. 

          An XML-RPC message is an HTTP-POST request. The body of the request is in XML. 
          A procedure executes on the server and the value it returns is also formatted in XML.
          Procedure parameters can be scalars, numbers, strings, dates, etc.; and can also be complex record and list structures.
          HTTP request is send. No WSDL.  
          (http://tldp.org/HOWTO/XML-RPC-HOWTO/xmlrpc-howto-intro.html)

          JSON-RPC (RPC) - All transfer types are single objects, serialized using JSON. https://code.google.com/p/json-rpc/wiki/Usage

          JSON-RPC is lightweight remote procedure call protocol similar to XML-RPC

          SOAP (SOA, needs WSDL)

          SOAP like XML-RPC, but lot more features, requires WSDL. 

          REST

          SOAP uses interfaces and named operations to expose business logic. REST uses (generally) URI and methods like (GET, PUT, POST, DELETE) to expose resources.

          Managing Session in Web Services

          Normally, a JAX-WS Web service is stateless: 
          that is, none of the local variables and object values that you set in the Web service object are saved from one invocation 
          to the next. 
          Even sequential requests from a single client are treated each as independent, stateless method invocations.
          Enabling stateful support in a JAX-WS Web service requires a minimal amount of coding on both the client and server.
          And there can be several approaches. 
          Like what we can do is - Inject WebServiceCOntext in Web service Impl class. 
          We can access the HttpSessionObject from WebServiceContext. 
          Save objects in HttpSession using setAttribute, and can later retrieved using getAttribute. 
          (Check for more details - http://docs.oracle.com/cd/E17904_01/web.1111/e13734/stateful.htm)


          EJB



          How can EJB/business layer client can execute a use case's business logic in one transaction and in one call. 

          EJB Session Facade pattern. 
          Wrap Entity beans in a layer of session beans, and clients accessing sesison beans. 
          Some precautions must be taken while designing the session facde - 
          1. Avoid very big facade.
          2. Avoid duplicate code in facade methods. 
          I remember a design where we first wrote a Java class(AFacade) with all the implementation code. 
          AFacade implements a interface ASession. and we have a session bean implementation class ASessionImpl.
          AsessionImpl extends AFacade. Generally we were writing very few lines in the ASessionImpl,
          since all the implementation code was already there in AFacade. 
          Benefits, the business logic was also going in a separate application, a jar file.
          Jar file was a batch implementation. Some clients which do not want to make remote lookup,
          or are not running in the app server, were directly using the jar file. 
          Same code when becomes part of EJB, there capabilities added - 
          1. Its exposed for remote lookup
          2. It can exposed as Web Service
          3. transaction capabilities are added
          4. Low Coupling
          5. Clear separation of other layers(like presentation). It represents athe business layer. 
          App Server provides multiple options like pooling, caching so using EJB is not a performance issue. 

          How client can make a asynchronous call along with transaction capabilities. 

          Message Driven Beans
          A Message Driven Bean can also act as a facade. 
          Client send a message to a JMS Queue, MDB's onMessage is invoked. 
          onMessage can be in transaction, and if it fails, the message can be rolled back and sent back to Queue. 
          Some precautions must be taken whiloe using MDB - 
          1. The request, should be properly constructed. We can objects also in reuqest. 
             There are several options for request. 
          2. Prevent Message loss. 
          3. Transaciton handling. 
          4. Exception handling, because actual exeption wont be propagated automatically to client. 
          5. Response to client, because there is no automatic response send. 

          How to prevent Message loss in Message Driven Bean -
          Please read a small post 
          http://shekup.blogspot.in/2012/02/prevent-message-loss-in-message-driven_21.html

          Session Bean and pooling -  

          When Server is first started, several Stateless session bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.  When a bean instance is in the ready state, it can service client requests; that is, execute component methods. When a client invokes a business method, the EJB container assigns an available bean instance to execute the business method. Once execution has finished, the session bean instance is ready to execute another business method.  When the EJB container decides to reduce the number of session bean instances in the ready pool, it makes the bean instance ready for garbage collection. Just prior to doing this, it calls the callback method ejbRemove. If your session bean needs to execute some cleanup action prior to garbage collection, you can implement it using this callback method. The callback method is not tied to the remove method invoked by a client. For a stateless session bean, calling the remove method invalidates the reference to the bean instance already in the ready pool, but it does not move a bean instance from the ready to the does not exist state, as the management of stateless session bean instances is fully done by the EJB container.  
          If all the beans form pool are active, any new client comes, it would be blocked if transaction time outs or time out occurs, Server would throw RemoteException to remote clients and EJBException to local clients. 
          For stateful session bean, When a client invokes a create method on a stateful session bean, the EJB container creates a new instance.  To more optimally manage resources, the EJB container might passivate an inactive stateful session bean instance by moving it from the ready state to the passive state. When a session bean instance is passivated, its (non-transient) data is serialized and written to disk, after which the bean instance is purged from memory, and if cache is full instance would be passivated to disk. For session bean there is algo to remove the bean, like time out, where bean is totally discarded, when bean is in passive state for time longer than session time out. Unlike anonymous stateless sesison beans, stateful have identity, which is used to bound it to client. 
          One important point we should know is that pool is use for stateless(either EJB or thread or anything), and cache is used for statefull(either EJB or entity or anything). 
          We always prefer stateless session bean over stateful. 

          EJB Transactions -  

          EJB provides some options for setting the transaction. We can set the transaction attribute - 
          REQUIRED Methods executed within a transaction. If client provides transaction, it is used; if not, new transaction generated. Commit at end of method. Default attribute set by WebSphere Studio. Well-suited for EJB Sessions.
          MANDATORY - Client of this EJB must create a transaction in which this method operates, otherwise an error. Well-suited for EJB Entitys.
          REQUIRES_NEW - Methods executed within a transaction. If client provides transaction, it is suspended. A new transaction is generated, regardless. Commit at end of method.
          SUPPORTS - Transactions optional.
          NOT_SUPPORTED - Transactions not supported; if provided, ignored.
          Transaction attributes help us create boundaries  but they don't solve the common problems faced, obsolete data or concurrent modification. 
          Some common problems related to data are - 
          Dirty Reads - A transaction reads data written by another transaction that has not been committed yet. Because this data is uncommitted, a transaction failure would roll back these read changes.
          Occurs when one transaction (T2) reads data that has been modified by previously started transaction (T1), but not committed
          What happens if the T1 rolls back? T1 has incorrect data, thus "dirty read".
          Nonrepeatable reads - A transaction rereads data it has previously read and finds that data has been modified by another committed transaction in the meantime.
          Occurs when one transaction (T1) reads same data twice, while another transaction (T2) modifies the data between the two reads by T1.
          T1 gets different value between the first and the second read, thus "nonrepeatable read".
          Phantom reads - A transaction reexecutes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another committed transaction in the meantime.
          Occurs when one transaction begins reading data and another inserts to or deletes data from the table being read.
          Above mentioned problems are solved by setting the isolation level, which can be provided by App server or DB. 

          LinkWithin

          Related Posts Plugin for WordPress, Blogger...

          Labels

          Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt