Popular Posts

Monday, March 19, 2012

Detecting and fixing memory leaks in java

What sort of memory leaks are possible in Java and how do I prevent them?

In any language, application-level memory management problems revolve around the deallocation of memory. These problems fall into two categories: premature deallocation (corrupted pointers) and incomplete deallocation (memory leaks).
In the case of incomplete deallocation, there are two subcases: coding bugs and design bugs. Coding bugs are language dependent. In the case of C, this would involve free()ing less than was malloc()ed, while in C++ this might involve using delete in lieu of delete[]. Design bugs, on the other hand, do not depend on the language; instead, they involve simple programmer negligence.
In languages like C/C++, all memory management is handled by the programmer, so all of these problems can arise, even after the programmer has expended much effort to ensure the code is free of such defects. In fact, in C/C++ the more you try to avoid memory leaks, the more likely you are to create corrupted pointers, and vice versa. And, by nature the risk of such bugs increases with code size and complexity, so it's difficult to protect large C/C++ applications from these types of bugs.
In Java, on the other hand, the Java language and runtime together entirely eliminate the problems of corrupted pointers and code-level memory leaks. Here's how:
  • In Java, memory is allocated only to objects. There is no explicit allocation of memory, there is only the creation of new objects. (Java even treats array types as objects.)
  • The Java runtime employs a garbage collector that reclaims the memory occupied by an object once it determines that object is no longer accessible. This automatic process makes it safe to throw away unneeded object references because the garbage collector does not collect the object if it is still needed elsewhere. Therefore, in Java the act of letting go of unneeded references never runs the risk of deallocating memory prematurely.
  • In Java, it's easy to let go of an entire "tree" of objects by setting the reference to the tree's root to null; the garbage collector will then reclaim all the objects (unless some of the objects are needed elsewhere). This is a lot easier than coding each of the objects' destructors to let go of its own dependencies (which is a coding-level problem with C++).


So what about memory leaks caused by poor program design? In such designs, unnecessary object references originating in long-lived parts of the system prevent the garbage collector from reclaiming objects that are in fact no longer needed. Such errors typically involve a failure "in the large" to properly encapsulate object references among various parts of the code.
Another design flaw occurs "in the small," at the level of a faulty algorithm; the use of Collections objects in such cases will typically magnify the error.
As the technology improves, a suitably implemented JVM could help reduce the effects of such designed-in memory leaks by using the garbage collector to track object usage over time. The garbage collector could then rearrange objects in memory according to a freshness factor based on when they were last referenced, for example. Stale objects would become eligible for physical RAM swap-out (even though, for safety, they would still exist).
Ideally of course, programmers would design applications with objects' lifecycles in mind, rather than rely on clever features of state-of-the-art JVM implementations.
In conclusion: Design problems can be mitigated by letting go of object references in one's own classes as soon as one can (knowing that in Java there is no risk of damaging another part of the code).
Tip: The KL Group's JProbe tool can help identify possible sources of memory leaks by showing which objects are holding on to graphs of references to other objects.
Note: Implementations of Sun's JVM prior to HotSpot used a technique called conservative garbage collection, which could introduce memory leaks of its own, beyond those caused by the programmer. To wit, as long as the application contained a 32-bit integer primitive (int) whose value coincided with the address of an object, the garbage collector would not reclaim the object. Although the likelihood was small, it wasn't zero. For this reason, and for the best performance in general, use HotSpot where possible.



Refer :

Sunday, March 11, 2012

Vertical sum in a binary tree

Refer : http://www.geeksforgeeks.org/archives/18215
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;

public class VerticalSumInTree {
public static void main(String[] args) {
Node root = getTree();
printVertcalSumsInTree(root);
}

private static Node getTree() {
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
Node node7 = new Node(7);
Node node2 = new Node(2, node4, node5);
Node node3 = new Node(3, node6, node7);
Node root = new Node(1, node2, node3);
return root;
}

private static void printVertcalSumsInTree(Node root) {

if (root == null)
return;

// Used for storing nodes matches to same horizontal distance
Map<Integer, List<Node>> map = new HashMap<Integer, List<Node>>();
calculateVerticalSum(root, map, 0);

printVerticalSums(map);
}

private static void printVerticalSums(Map<Integer, List<Node>> map) {
if (map == null) {
System.out.println("Tree is empty");
} else {
Set<Integer> keys = map.keySet();

// Sort the keys
// convert set to list for sorting.Because collections accepts list
// for sorting
List<Integer> keysList = new ArrayList<Integer>(keys);
Collections.sort(keysList);
// For each key, get the list of values
for (Integer key : keysList) {
List<Node> list = map.get(key);

// Iterate through the list elements and calculate the sum
int sum = 0;
Iterator<Node> it = list.iterator();
while (it.hasNext()) {
Node n = it.next();
sum = sum + n.value;
}
System.out.println(sum);
}
}
}

private static void calculateVerticalSum(Node root,
Map<Integer, List<Node>> map, int horizontalDistance) {

if (root == null)
return;

// Add this value to the map
List<Node> list = map.get(horizontalDistance);
if (list == null) {
list = new ArrayList<Node>();
}

list.add(root);
map.put(horizontalDistance, list);

// iterate for left and right trees
calculateVerticalSum(root.left, map, horizontalDistance - 1);
calculateVerticalSum(root.right, map, horizontalDistance + 1);
}

public static class Node {

public int value;

// member variables will be initialized to null by default.
public Node left;
public Node right;

public Node(int value) {
this.value = value;
}

public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}

}
}

Immutable objects in java

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. In some cases, an object is considered immutable even if some internally used attributes change but the object's state appears to be unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.
               Immutable objects are often useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.Small immutable objects can easily be copied efficiently, but larger immutable objects require more complicated persistent data structure algorithms to be efficiently copied. Mutable objects are sometimes used instead of immutable objects for performance reasons.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.
Check here for how immutable objects are thread safe ?

Refer : http://www.javaranch.com/journal/2003/04/immutable.htm
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html

Scalable web application


What is scalable application design : 
Tip 1: load balancing the webserver
Tip 2: scaling from a single DB server to a Master-Slave setup
Tip 3: Partitioning, Vertical DB Scaling
Tip 4: Partitioning, horizontal DB Scaling
Tip 5: Application Level Partitioning
Tip 6: Caching to get around your database

Refer : http://blog.nickbelhomme.com/php/scalable-web-applications_158

Also refer :
http://www.infoq.com/news/2010/08/Scalable-Web-Application

Object oriented design questions

Design does not mean implementation.
Design means:
  1. what all classes you will have
  2. The methods(functionality) your classes will provide
  3. What will be the relation between classes you have
  4. What will be the Lifetimes of objects of your classed
  5. Having said a design is not something which gets done in a mere 15-20mins of an interview.It's all blood and sweat and it needs lot of time and consideration albeit discussions to arrive at a good design.
  6. In a interview the Questioner usually want to know if you can think in the right direction atleast.
Check design pattern interview questions here

Interview questions : 

Frequently Used java APIs'


Important java API’s to remember  :
·         Comparable
·         Comparator
·         List
·         LinkedList
·         ArrayList
·         Vector
·         Set
·         HashSet
·         TreeSet
·         SortedSet
·         Map
·         TreeMap
·         HashMap
·         SortedMap
·         Serializable
·         Clonable
·         Integer,Double,Boolean,Long
·         String
·         Object
·         Thread
·         Runnable interface
·         HttpServlet
·         HttpSession
·         Collections
·         Arrays
·         Generics
·         Java.lang.Math
·         StringBuffer
·         StringBuilder
·         ThreadLocal
·         Iterator
·         Enumerator
·         Date
·         Calendar
·         LinkedHashSet
·         LinkedHashMap
·         PriorityQueue
·         Random
·         Stack<E>
·         WeakHashMap
·         Pattern
·         Matcher

Saturday, March 10, 2012

All algo questions

Common stuff

Sql questions

String question list

All sorting questions

All matrix questions

All DP Questions

Friday, March 9, 2012

Check leap year


/** determine if the given year is a leap year.<p>

The Gregorian calendar rule states that a leap year occurs
every fourth year, except every 100 years, except every 400
years.<p>

@param year The year to be tested. Make sure this is a four digit year\!<p>
@return true if "year" is a leap year.<p>
*/
boolean isLeapYear(int year) {
boolean y4 = ( (year % 4) == 0 );
boolean y100 = ( (year % 100) == 0 );
boolean y400 = ( (year % 400) == 0 );
return ( y400 || (y4 && ! y100) );
}

Thursday, March 8, 2012

Memcached

From POSIX to COM/DCOM or RMI to SOAP, we simply try to share data among threads or applications. By decoupling service with client, Memcached is a new and better solution to share data. Because Memcached is an abstract service, it can serve different applications written in different programming languages running on different platforms simultaneously.

Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. In short, Memcached is a huge hashmap.
public class DummyServiceImpl {

//CustomMemCachedClient is wrapper class internally developed in our product to access cache
private CustomMemCachedClient mCustomMemCachedClient;
public String retrieveDummy(String regId) {
String dummy = null;
String key = "dummy#" + regId;
Object cachedValue = mCustomMemCachedClient.get(key);

if (cachedValue instanceof String) {
dummy = (String)cachedValue;
}
if (dummy == null) {
dummy = "dummy has been set for regId: " + regId;
System.out.println("dummy is just set for " + regId);
mCustomMemCachedClient.set(key, dummy);
}

return dummy;
}

public CustomMemCachedClient getCustomMemCachedClient() {
return mCustomMemCachedClient;
}
public void setCustomMemCachedClient(
CustomMemCachedClient pCustomMemCachedClient) {
mCustomMemCachedClient = pCustomMemCachedClient;
}

}

Now, let's study the results of the tests above. When user A login, there was no dummy data in memcached. So, the dummy service generated dummy data and stored it in memcached under key "dummy#A". When user A refresh the page, dummy service was able to grep data right out of memcached, so no new dummy data was generated. Since we set timer as 10 seconds for dummy data to stale, new dummy data need to be generated after a timeout. From these, we can see how memcached caches data. But does it work the same way as hard coding? When user B login, there was no dummy data for that user in memcached yet. All memcached had was for user A, so dummy service generated a new dummy data for user B under key "dummy#B". From there, user B should have the same experience as user A had.
MemCached is just that simple. 

In web applications the majority of the latency in serving a request is caused by interactions with a database. Databases are often necessary for managing persistence and to providing a way to sort and filter large collections of information. However, databases are also overused to frequently read and write infrequently-changed information -- or worse, information that never changes.Memcached provides a shared memory cache where arbitrary information can be read frequently without incurring the overhead of a database.

Refer : http://wiki.cerb4.com/wiki/Performance#Memcached

Wednesday, March 7, 2012

Design patterns

Important sites

J unit test

Types of testing :
  • Unit testing : The goal of unit testing is to test each part of the program in isolation and show that the individual parts are correct, and identify programming/logical issues at a low level, thereby promoting an Extreme Programming paradigm.
         Unit testing is engraved into Extreme Programming methodology, and hence strive to make it cost effective.
Perform white box testing of each line of code. Testing should be narrow, covering each line of code.
  • Integration testing
  • End to end testing(QA)
  • Performance testing
  • Smoke testing
White Box Test : 
    Requires the knowledge of implementation
    Requires program language, script like HTMLUNIT, Selenium in Java
    Since the tests are based on the actual implementation, if the implementation changes, the tests probably will need to change, too.
Black Box Test :
    Requires NO knowledge of implementation
    No programing but use tool like STIQ
    Try to explore the software's behavior from the outside

Refer here for Junit frame work

Optimistic locking failure

There are cases like multiple threads try to modify the entries depending on the already existing row information.If one thread commits the
info after other thread reads the info,then date will get corrupted and will lead to abnormal behavior.To avoid this condition,we add one more column in database tables
so thatwhen a thread reads the row,it will increase this value in column to one and before writing the info it will recheck.If both are same,then commits the value.Otherwise
it will throw optimistic lodking failure exception.


Optimistic Locking is a strategy where you read a record, take note of a version number and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.
This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoidDeadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactiona using two-phase commit protocols (such as XA or COM+ Transactions) work.

Spring framework

What is Spring

Spring is a lightweight inversion of control and aspect-oriented container framework.
Explain Spring

      Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
    Inversion of control (IoC) : Loose coupling is achieved in springusing the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
    Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
    Container : Spring contains and manages the life cycle and configuration of application objects.
    Framework : Spring provides most of the intra functionality leaving rest of the coding to the developer.

What are the different modules in Spring framework

    The Core container module
    Application context module
    AOP module (Aspect Oriented Programming)
    JDBC abstraction and DAO module
    O/R mapping integration module (Object/Relational)
    Web module
    MVC framework module

What is the Core container module

This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
What is Application context module

The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
What is AOP module

The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.
What is JDBC abstraction and DAO module

Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.
What are object/relational mapping integration module

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.
What is web module

This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to yourbusiness objects. It also contains integration support with Jakarta Struts.

Refer : http://en.wikipedia.org/wiki/Spring_Framework

Thread pool

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.

One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.

An important advantage of the fixed thread pool is that applications using it degrade gracefully. To understand this, consider a web server application where each HTTP request is handled by a separate thread. If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain.

Thread pool pattern : http://en.wikipedia.org/wiki/Thread_pool_pattern

Tuesday, March 6, 2012

Java frequent interview questions

=====================================================================
Java interview questions : 
5) What is hashcode and equals contract?
6) What is the difference between == and equals method?
8) What is the difference between String and StringBuffer classes?
9) What is the way to store the integer value in a string object to an integer variable?
10) What are sorted collections in Java?
12) What is JDBC API?
14) What is final, finally and finalize?
15)********** What is weakhashmap?
16) ************What is the purpose of reflection API?
18) What is bucketing in Java?
19)*************** How does Java manages the threads?
23) **************What are the different ways of creating a thread?
24) ************** What is inter thread communication?
25) ************** What are instance and class level locks? What is synchronization?
29) What are the coding standards for naming variables, constants, methods and classes?
30) What is a literal and what is special about String literals?
31) **************What is flyweight design pattern?
32) **************How will you create a Singleton class? Is it thread safe?
35) What is the purpose of instanceof operator?
37) What is the difference between private, protected, default and public access specifiers?
38) What are this and super keywords?
39) What are transient and volatile keywords?
41) ***************Are all the classes specified in import statement actually imported?
42) Can an inheritance relationship exist between two interfaces?
46) What is the meaning of various keywords specified in creating the main method?
47) What is  the purpose of ^ operator?
48) What is the difference between pass by value and pass by reference?
49) ***************What are the various types of inner classes?
50)*************** What are the various memory areas in JVM and what kind of information is stored in each of them?

Phone screen questions : 
Given a domain model, describe the process you follow to create a service.
Expect to hear: UML (class & interaction diagram), Data Model, SQL/DDL, API definition & documentation, Interface, Unit tests, integration tests.
How do you test your services?
Expect: JUnit, TestNG, or similar. Unit & integration tests, test cases.
Describe how you have used the Spring Framework.
Expect: IOC, JDBC Templates, controllers, annotations.
Describe your experience with high-volume website development.
Describe how you have addressed scalability/performance issues with large datasets.
Describe the approach you use to analyze performance issues. (Service API down.) (Web tier)
Expect to hear: profiler, SQL explain plan, debugger
What's the latest version of Java you have used. What, if any, changes did you take advantage of?
What's the latest version of Spring you have used. What, if any, changes did you take advantage of?
Describe the build systems you have used.
Expect: Ant, Maven, other.
Have you used any continuous build systems?
Expect: Cruise control, Hudson, other.
Which sounds like the most fun(Optional):
Refactoring some code that has bothered you for a long time.
Designing a new service API
Creating an AJAX based form processing framework.
Creating an automated testing/performance framework.
Porting a legacy application to your favorite language
===================================================================== 
  • What are the 4 basics of OOP?
  • Define Data Abstraction. What is its importance?
  • Given a cube of size n*n*n (i.e made up of n^3 smaller cubes), find the number of smaller cubes on the surface. Extend this to k-dimension.
  • What is the time and space complexities of merge sort and when is it preferred over quick sort?
  • Write a function which takes as parameters one regular expression(only ? and * are the special characters) and a string and returns whether the string matched the regular expression.
  • Explain polymorphism. Provide an example.
  • Given an array all of whose elements are positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7)
  • You are given some denominations of coins in an array (int denom[])and infinite supply of all of them. Given an amount (int amount), find the minimum number of coins required to get the exact amount. What is the method called?
  • What is the difference between an object and a class
  • you are provided with a stream of numbers, design a data structure to store the numbers in the stream along with their no. of occurrences.ans:I told him to use a Trie and he asked me why not BST, and asked me to compare both..
  • Given two sorted arrays A1 and A2, of lengths L1 and L2 , L1 < L2 and the last L1 slots in A2 are vacant, get me all the numbers in A2, sorted in the most efficient manner without using extra space. This was a written test question in which I blabbered quick sort will do.......In fact the answer was merge sort. I misunderstood the question a bit and was thinking in some other direction. But after he clarified the question, I wrote the code immediately.
  • In an array of size n, there is one number missing and one number repeated twice. Find them.I was a fool not to notice the sum of numbers and sum of squares of numbers property immediately. But after getting a clue, I answered it.
  • What is the effect by keeping a constructor private? (in terms of inheritance),
  • Say you are using a map in your program, how would you count the number of times the program use put() and the get() function? How would you do that if its using multiple maps in the program? How would you do that if the map is sent as a parameter in a method? How would you do it if the multiple maps are passed into the methods (as parameters), and are use differently? (it went on forever….)
  • What do you know about Java generics
  • what is object reflection in Java
  • What is polymorphism.
  • Design an OO parking lot. What classes and functions will it have. It should say, full, empty and also be able to find spot for Valet parking. The lot has 3 different types of parking: regular, handicapped and compact.
  • Coding: I have an integer array where every number appears even number of times and only one appears odd times. Find the number.(I said hashtable and he asked me to write code with Hashtable)
  • What data structure would you use to look up phone numbers for customer names.(I said Hashtable. Asked why hashtable, why not a tree. I said HT has O(1). Asked is order always 1, when more than O(1) in HT.
  • Data Structures: How will you use a hashtable to find data in a tree. (Then he rephrased) suppose I have a hashtable, I want to store the data in a tree instead of a bucket. How will I do it. What complexity to find an element.
  • Bits & Bytes: Find if a binary representation of a number is palindrome. The function should work irrespective of number of bytes for an integer. Suppose if our machine is 4 bytes for an int, how will you use the program for 8 byte machine.
  • What is the flaw in the design of Java.lang.Stack class of Java
  • What is the use of volatile variable.Explain it in Singleton class also for lazy initialization.
  • How to implement your own HashMap in java
  • Why should you not make your Sinleton claas as Serializable and Clonable.
  • What is the limitation of singleton pattern
  • Why Java language designer has chosen to make all the variable inside an Interface as public ,static and final.
  • What are the various ways in singleton pattern can be made to fail and how to avoid them ?
  • The wrapper classes also offer utility methods for converting to and from the int values they represent. Thus if you have a string that could also represent a number, you can use a wrapper class to perform that calculation.
  • I have a class A which implements serializible and there are two sub classes B and C which extends A. I want clsss B not be serializible ? How can I achive it?                                                          Refer  :http://www.careercup.com/question?id=7508689
  • Why do we need thread class when we have Runnable interface ? http://www.careercup.com/question?id=7571666
  • Name all the memories which are available in JVM? I knew only heap and perm. Is there any other memory also? http://www.careercup.com/question?id=7547664
  • What intern method does in java?  http://www.roseindia.net/java/string-examples/string-intern.shtml http://www.careercup.com/question?id=7184154
  • what is daemon thread in java? daemon thread is a low priority thread that is terminated as soon the vm exits. It is generally used to do all the house keeping work like gc thread is a daemon thread.It can be set using thread.setDaemon(true); And then start the thread.  The main thread terminates it if it is finished.
  • What is Java Reflection API? Java reflection supports dynamic retrieval of information about classes and data structures by name, and allows for their manipulation within an executing Java program.
  • What is the difference between Serializable and Externalizable interfaces ?  http://www.careercup.com/question?id=3220676
  • Given a sorted array of n integers that has been rotated left or right by k places, give an algorithm that searches and finds an element in the array in log n time.   Example Input : 8 9 0 1 2 4 5 6 (sorted array rotated right by 2 places)http://www.careercup.com/question?id=2319661
  • What are features of optimum Java code : reusability/modularity,  data/functional abstraction,  complete code coverage,  fail-safe (crashes safely.. no one can totally avoid crashing).. most imp of all.. meet the user requirements.. add more if needed. Takes care of garbage collection.
  • Explain what is in a deployment descriptor file? give an example of a deployment descriptor ?           A deployment descriptor contains configuration data that the run-time environment uses for an application. A deployment descriptor can include information about the following:
               * The structure and content (enterprise beans or servlets, for example) of the application.

              * References to internal and external dependencies of the application. For example, an enterprise bean in an EJB module can require another enterprise bean that is not bundled in the same module.

            * References to resource factory objects, such as URLs, JDBC DataSources, JavaMail Sessions, JMS Connection Factories, JMS Destinations, and J2C Connection Factories.

        * Security roles that the container uses when implementing the required access control for the application.

        * Transactional information about how (and whether) the container is to manage transactions for the application.


  • How does the Collections API handle collisions? How does the API handling making the collection "some-what" collision safe?Explain- which collection does this affect and the best way to deal with it.Also explain, the most common scenario that causes this issue- hint* one is in threading(how can this be caused). Refer for discussion : http://www.careercup.com/question?id=417089
  • Can Java constructor has private or protected access type?                                                        Refer : http://www.careercup.com/question?id=296844
  • Write a Java program that prints the size of a non-primitive Java object.
  • What is the default visibility of an instance variable in java? What is package visibility?
  • What is the use of volatile variable?  http://www.careercup.com/question?id=2726
  • Why should you not make your Singleton class as Serializable and Clonable?http://www.careercup.com/question?id=2711
  • implement a counting semaphore in Java? http://www.careercup.com/question?id=133664
  • write java code for prime number generation?
  • What is the limitation of singleton pattern? http://www.careercup.com/question?id=2789
  • Why is access to static variables not allowed from non-static methods in java?http://www.careercup.com/question?id=2462
  • What is Garbage Collection in Java. How is it implemented? What kind of algorithms does the garbage collector use? How does it know that references can be collected? What are advantages and disadvantages of garbage collection? http://www.careercup.com/question?id=3111
  • How does Java achieve synchronization? Given an class with Synchronized method A and B, a normal method C, there are 2 threads, one instance, can these two threads call A at the same time? call A and B at the same time? A & C at the same time? http://www.careercup.com/question?id=57337
  • You are using a map in your program, how would you count the number of times the program use put() and the get() function? How would you do that if its using multiple maps in the program? How would you do that if the map is sent as a parameter in a method? How would you do it if the multiple maps are passed into the methods (as parameters), and are use differently? (it went on forever....)http://www.careercup.com/question?id=58095