Saturday, March 6, 2010

Interviews: Core Java, Swing, NMS, EMS, GWT and Puzzles

Interview Questions (Top search results on Google):

  4. (garbage collection alg)
  6. (UML class diagram basics)
  7. (Essential classes of JDK)
  8. (Collections tutorial)
  9. (Serialization and Externalization)

Go through java related sites like JavaWorld, JavaLobby, etc. and prepare on JVM Internals, threading internals, collection framework in depth and design.

Topic Set 1:

From Cisco,

Java Basics:
1. Usual questions in java collections , Thread and Exception handling
2. JDK tools
3. Java Monitoring and profiling, debugging tools and techniques
4. Customizing class loaders and find out the ClassLoader of a specific class
5. Serialization : Externalizable Vs Serializable and Versioning. Some scenarios

Some scenario discussion to find out deadlock, same as Producer Consumer problem but with some differences.
1. How does Thread lock work?
2. How to create Threads using Java, what is the difference
3. Discussion on wait() and notify(), notifyAll()
4. Why wait() and notify() have to be within synchronized block

Real time problem discussion : Designing
1. Design a Security Manager that authenticates a system using username and password

1. SNMP – getBulk() Vs getNext()
2. How SNMP index works
3. SNMP V1 vs V2 vs V3 at PDU level and functional level
4. SNMP message processing subsystem for V3

Programs :
1. To find out the SQRT of a given number
2. To find whether a given number is a Power of two or not
3. Program to convert a Doubly Linked List with N elements to N Singly Linked List. This is to be discussed at design level

Topic Set 2:
1. UML Patterns

a. Draw a UML diagram expressing the relations between various Managed Elements in NMS.
b. Various UML symbols and their meaning

2. NMS/EMS questions

>Define NMS and EMS
>Explain FCAPS
>Where snmp traps fit in FCAPS?
>Difference between snmp-get and snmp-get-bulk commands
>Difference between snmpv2 and snmpv3 message format?
>When would I call a trap as an inform request?
>What would you do if trap processing thread pool is overloaded?
>what is alarm-correlation?
>what happens in NMS when a trap is received? (explain till event gets propagated to GUI)
>how snmpv1 and snmpv2 differ in PDU format?
>how would you get the index/id/oid of a table when the table oid itself is not a valid oid, but its children are?
>advantages/disadvantages of getnext and getbulk, when used, to query a table?
>In which protocol layer, the acknowledgement to inform request is issued(DataLink/IP/Transport/Application)?
>When you receive clear trap for a failure whose trap you never received, what actions will you take? should it be processed at all?
>Format of getBulk request?
>how do you form getnext request? what goes in there?

3. Core Java

a. What is the need/purpose for the existence of Exception concept in java?
b. How would you define your own Checked Exception?
c. What do you know about Exception escalation among different layers of a java application?
d. Garbage collector algorithms (if you don't know the algorithm, then design an algorithm/methodology for garbage collection - i said don't know and i was asked to design a new one, so better know some basics in garbage collection algorithms to design a new one)
e. Serialization
f. Java Patterns and write a program explaining factory pattern
g. Write singleton pattern program (aware of all the loopholes in that simple singleton program)

4. Threads

a. what is a thread?
b. write a program to demonstrate thread communication in java
c. working mechanism of wait(), notify() and notifyAll() methods
d. role of synchornization in thread communications and understanding of class or instance level synchronization
e. differences in method-level and block-level synchorization
f. why do we need threads?
g. Thread Pool and Working Threads (i didn't know this... so they stopped this topic)

5. General questions

a. how would you handle the situation when you didn't properly complete a development and your manager asks you to deliver it immediately without knowing that you didn't do the work satisfactorily?
b. how would you start your work every day?
c. how would you handle a friend-cum-teammate who does unethical thing in work?

You will get J2EE questions if have put any in your resume. I said i didn't know about J2EE at all. So, they didn't ask. But our project uses J2EE server. So, they'll definitely ask this.

Topic Set 3:
- producer consumer problem/ wait(), notify(), join() and synchronization
- gc and its implementation, design a garbage collector, can we force garbage collection?
- What factor determines the start of garbage collection.
- cloning hashtable (if object-stream, is it efficient?)
- Avoiding memory leaks
- how to go about doing profiling
- runtime polymorphism sample (B b = new B(); A a = (A) b; a.f1(); what's the o/p if f1() is overridden by child class B?)
- diff between inheritance(extending) and interface
- thread pool
- Exceptions: can we define our own RuntimeException? Differentiate checked and runtime exception.

write code throwing an exception... why should throw an exception instead of returning an error code?

why do we need exceptions at all?
- design patterns (singleton and factory)

- diff snmpv2 and snmpv3
- snmp bulk request
- difference between snmpget and snmpbulkget.

- Block diagram of the project upto the end-device
- satisfying work/moments in your project/experience

Question: What is similarities/difference between an Abstract class and Interface?
Answer: Differences are as follows:
· Interfaces provide a form of multiple inheritance. A class can extend only one other class.
· Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
· A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
· Interfaces are slow as it requires extra indirection to find corresponding method in in the actual class. Abstract classes are fast.

SNMP Stuff
The following list shows the differences between SNMP from V1 to V3.
(The basic functions of V3 are from V1 and V2)
New SNMP message format
Set Request
Security for message and Access Control
Get Response
Set Request

SNMP v1 Trap

SNMP v2 Trap


  1. XML parsers in java [DOM and SAX]
  2. Tomcat(called apache tomcat) and Apache(called apache webserver) are different? Yes. Tomcat is pure java implementation and provides tools for configuration and management. But apache is C implementation with no tools.
a. public class ThreadRecursion {
c. public static void staticMethod()
d. {
e. System.out.println("Inside static method...");
f. ThreadRecursion tr = new ThreadRecursion();
g. tr.normalMethod();
h. }
j. public void normalMethod()
k. {
l. System.out.println("Normal method...");
m. ThreadRecursion.staticMethod();
n. }
o. /**
p. * @param args
q. */
r. public static void main(String[] args) {
s. ThreadRecursion tr = new ThreadRecursion();
t. //any of the following calls lead to stack overflow; no issues for the main thread to acquire the lock
u. tr.normalMethod();//main thread calling instance synchronized method
v. ThreadRecursion.staticMethod();//main thread calling static synchronized method
w. }
y. }
  1. How to detect a loop in a one-way-linked list?
  2. Nested classes: 1. Static nested classes, 2. Non-static nested classes are also called inner classes
  3. Default Annotations are SuppressWarning, Override (detects wrong overrides) and Depricated
  4. writeObject() readObject() for serialization are private methods. JVM can call this private methods. Using reflection you can call private methods (methodObj.setAccessible(true))
  5. serialver tool is used to create serialVersionUID (this is done for serialized objects)
  6. Thrown NullPointerException need not be caught at compile time. At any situation RuntimeExceptions will not be complained by Compiler (either the throws clause or throw caluse)
  7. When you write large amount of objects into ObjectOutputStream, OutOfMemoryError is thrown, why? Because, ObjectOutputStream caches all the objects written into it and these copies are not cleared though all the objects are not being used by the application
  8. Why Object is not Serializable() and Cloneable()? Because of security reasons. Anyone can clone or serialize and send it across the network or into a file. This opens up all the private data members as well.
  9. How to implement a Queue using two Stacks? (NetApp)
  10. Static members will not be serialized.
  11. ReadResolve() and WriteReplace() are found in serialization context when you need to designate alternate Object to be used for serialization.
  12. When serialVersionUID doesn’t match, serialization throws exception
  13. System.gc() and Runtime.gc() are the same. System.gc() calls Runtime.gc() internally.
  14. Volatile variables are not in-lined(replaced by actual values done by compiler as optimization strategy). Normal instance variables are in-lined(copies) and in a multi-threaded environment, this could lead to wrong value. So, declaring such members as volatile is a must to avoid compiler optimization in multi-threaded environment.
  15. Java is completely pass-by-value. The object references passed to a method are actually a new copy of the passed object reference. That is same reference (as with c++ pointers) is not carried through method call hierarchy.
  16. Uncaught exception is caught and displayed by “main” thread. Before “main” thread is terminated it calls the UncaughtExceptionHandler which is “system” ThreadGroup in this case and after executing the uncaughtException() method it terminates.
  17. JVM has 4 daemon system threads. [Reference Handler, Signal Dispatcher, Finalizer, Attach Listener] whose priority respectively [10,9,8,5]. The priority of main thread is 5.
  18. When a new thread is spawned it gets the priority of parent thread.
  19. The default UncaughtExceptionHandler for main thread is “system” ThreadGroup.
  20. Defining immutable object:
  21. String immutable topic
  1. UI Manager
  2. Swing MVC is more accurately called Model-Delegate (controller and view combined together into UI delegate)
  3. Thread safe methods in swing are repaint(), revalidate() and invalidate()
  4. UI delegate is derived from abstract class ComponentUI
  1. Which thread the listeners run on? Event Dispatcher
  2. Which thread invokeLater() call will run on? Event Dispatcher
  3. Will main thread terminate when a swing application is run but frame is not closed? Main thread terminates. Only EDT Event Dispatcher Thread lives.
  4. Will Model intimate the UI for changes and how? Yes.
  5. To insert a column in a table dynamically, where should we change? On DataModel or ColumnModel? In ColumnModel.
  6. How a thread other than EventDispatcher thread, can update a GUI? It can’t except for the thread safe methods, invalidate(), revalidate() and repaint()
  7. Can I use paint() method to refresh my component? Just a component yes. Even repaint() calls paint() on the components.
  8. What is the difference between repaint() and paint()
  9. What is the difference between revalidate(), repaint() and invalidate()
  10. Class Loaders?
  11. Where did you use reflection?
  12. What is the access modifier of clone() method
  13. In which class readObject() and writeObject() methods are located?
  14. In which class clone() method is located?
  15. Which one is efficient to make a copy of an object, Cloning? Or, Serialization/deserialization?
NetApp (see GWT section on GWT questions)
  1. Multiple huge files (thousands of GBs) are there. Reverse the letters in each word and create a new file. Design your application to do efficient copying. [Using stack to reverse the characters in the words; and threads to read, write and reverse letters so that you can make it faster]
  2. Write a class to make a growable array without using any collections framework classes
  3. How can you make a non-serializable third party class to serializable in your application? (one object handing over to another object to serialize/deserialize, externalization?)
  4. Why do we need JSON when XML is available? (XML is fatty with repeating tag names)
  5. There is a thread which is allowed to crash (you should restart it) 5 times within an hour. In this case, the thread will be restarted. If it exceeds 5 within an 1 hour time frame, exit the system. Design this system.
  6. You have 1 million data at server. You can’t show everything in client. How do you pull this large amount of data using dynamic data pulling?
Questions sites:-
Data structures and algorithms
Global scholars, RedKnee and Firetide
  • Write a class to implement a growing array without using available collection framework [I used an object array with fixed size and periodically increasing it's size as it grows by copying it to a bigger array]
  • Write a Node class to implement a node in a linked list. Then write a method to reverse list (one way linked list) which takes rootNode as argument and returns new root node.
  • How would you find 3 biggest numbers in a given array without using Collections framework?
  • How would you find the 2nd biggest number in a given array without using Collections framework (similar to above)?
  • How would you find the 3 numbers which will give biggest product (a*b*c)? The array can have zero, positive and negative numbers. Without using collections framework.
  • How can you achieve pass-by-reference for primitive arguments in java? (I didn't answer this question)
  • How can you bit reverse a given number for a given processor (32bit or 64bit)? Write a program in java. (I only wrote partial answer as pseudo code; which involves plucking one bit by bit from the given number by doing AND with 1 and doing right shift continuously. As you pluck bit by bit, construct a new number by left shift)
  • Can you call obj.x (where x is a private member of the class) inside the same class? I said no, but he said yes, it is possible in java.
  • In the following program, where compilation will fail and why?

class A {}

class B extends A {

public static void main(String[] args)
A obj1 = new A();
B obj2 = new B();
A obj3 = new B();
B obj4 = new A();
B obj5 = obj3;
  • Write equals method override version for an object which has a string and integer data members. This object needs to be used as key in a hashmap.
  • What JVM parameter will you use to tune garbage collection?
I. Creational Patterns - How objects are created
1. Factory Pattern - Creates different class objects based on the input
2. Abstract Factory Pattern - Creates different factory classes based on the input
3. Builder Pattern - Creates a complex object composition. Not just instantiation of one object
4. Prototype Pattern - Builds a complex object once and then copies it or clones it whenever a new object needs to be created
5. Singleton Pattern - Only one object of a particular class is maintained
II. Structural patterns - How to compose or structure objects
1. Adapter Pattern - Translates one interface to another
2. Bridge Pattern - Decouples interface and its implementation so that both can be varied without the need to recompile the other
3. Composite Pattern - Composition of multiple objects
4. Decorator Pattern - Moves the custom behaviour outside of the class so that multiple behaviours can be imposed on the same class as needed
5. Facade Pattern - Simplifies interfacing with a complex system, by providing single point of contact for all API invocations
6. Flyweight Pattern - Multiple objects store common data outside of themselves in a common place
7. Proxy Pattern - defers copying of some data of an object till it is necessary
III. Behavioral patterns - How objects communicate1. Chain of Resposibility Pattern - Event is passed among multiple parties until it reaches the right party who can take some action
2. Command Pattern - Defined commands invoke particular action on the other side
3. Interpreter Pattern - A syntax interpreter for a new protocol
4. Iterator Pattern - How to move through a list
5. Mediator Pattern - Decoupling the communication dependency between two objects and placing it in a mediator object
6. Momento Pattern - Persisting an object regardless of its functional or behavioural aspect
7. Observer Pattern - How changes on one object can be intimated to others
8. State Pattern - Different contained objects are used to provide memory for data members of container class thus dynamically changing the object behaviour
9. The Strategy Pattern - Provides algorithm in a class
10. The Template - Providing abstraction which would allow customization later. Inheritance is a template pattern.
11. The Visitor - The Visitor pattern adds function to a class so that it can visit later as part of iteration
Note that constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.
Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the line
to your constructor. But then other threads can use instances to access the object before construction of the object is complete. [Just know that while you modify your critical data inside the constructor, the other threads might start using this object and can modify your critical data parallel to the constructor. But still synchronized code is not allowed to multiple threads though the object is being constructed still.]
  1. With versions prior to Java Platform, Standard Edition 5.0, an additional step was required to build stub classes, by using the rmic compiler. However, this step is no longer necessary.
  2. the ability to download code dynamically, is often called a behavior-based application.
  3. RMI classes are made network accessible through webserver to download class definitions dynamically
  4. Write an RMI server client program.
Design Questions
  1. There is a web server which receives too many web requests and currently not able to scale. To make it efficient without using distributed architecture (other servers), what are all the things will you consider to improve the performance and scalability?
  2. There is a string in a file. Read it from the file and reverse the words in that string (keeping the words intact) without using another data structure. Splitting the string with space as delimiter creates one extra array of tokens. Provide some other way without using extra data structures other than the final resulting string or array. (do not use utility methods to reverse). Also do a complete reverse (character by character) of the string.
  3. There is an unsorted array of integers of length N. It contains unique numbers from 1 to N+1. Find the missing number. One simplest way is find sum S of all elements in the array. Then calculate Q = P * (P + 1) / 2 where P equals to N+1. Find the difference that is (Q - S) which will give you the missing number. If you can arrive at any other way, please do.
  4. There is an unsorted array of integers of length N. It contains unique numbers from 1 to N. But, only one number is occurring twice. Find that repeating number. Because one number is repeating and it is not a sorted array, the second occurrence of the repeating number can replace any number between 1 to N. So, the above formula cannot be used. I was not able to arrive at any efficient method to find the repeating number.
  5. How will you implement an LRU Cache (Least Recently Used items discarded in the Cache first) using Linked List? That is least recently accessed elements should be at one end of the linked list. Solution is to add new elements at the top of the list, and whenever someone reads any other element, remove it from there at put it at the top of the list. This would give most recently used elements at the top. Now, you can read from the end of the list to fetch least recently used elements. Or to delete least recently used elements, you can start deleting from the end of the list when cache overflows.
  6. How do you implement priority queue?
  7. The main method looks as shown below. What will happen to the new thread started? Will it be killed or interrupted?

{ Thread t = new Thread(); t.start(); t = null; }
  1. There are large numbers of English words to be stored. All words are unique. Anyone can add new words to the data structure. And also, you should be able to return any requested word, or words starting with given substring (like all words starting with 'hell' would be 'hell', 'hello', 'hells', or any junk words added earlier as well; need not be proper English words.). Design an efficient data structure for this requirement. I used alphabetically sorted tree to achieve this. Where partial strings will be as parent nodes, and full words will be leaf nodes. While inserting a new word say, 'hello', you need to pick up the tree starting with 'h', then go to 'he' child, then to 'hel' child, then to 'hell', then to 'hello' node and then add a leaf node called 'hello'. While some one searching for all words starting with 'hel', then go to 'hel' node and collect all leaf nodes under it and then return.
  2. There is a binary tree which can be unbalanced. That is left side of the tree might contain more elements than right hand side or vice-versa. Store this binary tree in an array in such a way that you should be able to reconstruct the binary tree later. The best solution I could arrive at is, find the capacity of the binary tree, that is based on the depth (number of levels in the tree), maximum number of elements that can exist (right hand side and left hand side of the tree are equal and full), though the actual number of nodes of the tree is lesser; take this as array length; put the root node in the middle of the array. Then recursively place left side tree in the left side portion of the array and also right side tree on the right hand side of the array. The array cannot overflow, because its length is based on maximum capacity of the binary tree.
  3. There is a question paper. This can have any type of questions. Do a modelling for this question paper so that you have a system to store this question paper into a data base and also easy to print the paper, or to evaluate the answer extra. Guidelines: List the parameters of any question paper you should consider. Then, arrive at interfaces and classes for your data structure. Then arrive at, database table design. Also, at last consider that the question paper also has match the following (one left option can match to multiple right side options) type of questions. [I said, type of the question like choose the answer, fill in the blank, provide your own answer, etc. Then, this decides question type, section under which questions are coming; then weight that is mark for each question. Data structure should be able to store multiple options of each question. How many number of blanks are there in fill in the blanks. Also, Question class should be able to accept relevant answers and validate or throw exception when wrong answer is fed. That is giving fill in the blank answers for multiple choice question. Then evaluation of the question. Then Question DB table with unique ID for each question. Then Options table with all the options per row, also having question ID as one of the column to indicate to which question this option belongs to. For fill in the blanks, having one blank option for each blank. Then, at last for match the following question, use separate table for left options and separate table for right options with question id as another column. When you need to match, you can match left side option with multiple right side options.
  4. There are two strings S1 & S2 as character arrays. Find all the common sub strings occurring in these two strings even the repeating sub strings. I after some time, arrived at sliding mechanism. Take the shortest string and position below the bigger string as though they appear to be character sliders. That is first character of big string is exactly above the last character of small string. Slide, one character at a time and try to find the common string until the first character of the small string reaches the last character of the longer string. The complexity would be (n1 + n2) loops where n1 and n2 are the lengths of these strings. Each loop is a search common string which would mark the start index position when same character occurs and mark the end index position when different characters occur. This would give the common sub strings.
  1. There are 3 boxes. One box contains all apples. One box contains all oranges. The last box contains mixture of Orange and Apples. But all these are wrongly labeled. Say A, O, AO like that. You can take one fruit from only one box without peeking inside it and see that fruit. Based on that, re-label the boxes correctly.
  2. There is a bridge which can be crossed by only two people maximum at a time with the help of a torch. There are four people with different speeds. One can cross the bridge in 1minute; one in 2 minutes; one in 5minutes and the other in 10minutes. How quickly these four people can cross the bridge. 19 minutes is easy to arrive. But they can cross in 17minutes. How?
  3. There are five jars containing equal number of pills of same kind and size. But, one jar contains full of defective pills whose weight is half of the proper pill. There are two scales. One is digital which will give exact weight if you put something on it. The other is balance scale which will show comparative weight. Left or right side will be lower. You can use only one of these two scales and that too only once. How will you find the jar which has defective pills. [ I was breaking my head with balance scale but couldn't arrive at any solution. Then he gave a clue that, it is possible to find this only with digital scale. ]
  4. Describe yourself in 5 sentences.
  5. 6 areas of weakness?
  6. Rate yourself in hard working in the scale of 1 to 10?
  7. Rate yourself in problem solving skill in the scale of 1 to 10?

  1. Automatic Resource Inclusion: The GWT compiler will bundle all the static resources required to run your application including the style sheets (images, etc). This mechanism is called Automatic Resource Inclusion.
  2. Deferred Binding: At runtime, GWT uses a mechanism called deferred binding to load the correct permutation for the end user's browser. Deferred binding serves just the code the user needs and no more. What are the benefits of deferred binding? Because each permutation is tailored to work around the bugs and idiosyncrasies of its intended web browser, using deferred binding is
· Faster, for the user.
Your application download contains no unnecessary bytes. The application doesn't need to sniff for browsers or provide multiple branches for each browser.
· Faster, for you.
GWT does the work of generating the correct JavaScript for each browser so that you don't have to spend so much time dealing with differences among browsers.
In addition browser detection, deferred binding can also generate customized versions of your application for any number of other variables. One very common example is internationalization. With deferred binding, GWT generates a separate implementation of the application for each language, so for example, an English speaker doesn't have to download the French text (and vice versa).
  1. Overlay types: Not only do you want to be access the array of JSON objects, but you want to be able to work with them as if they were Java objects while you're coding. GWT overlay types let you do this.
  2. How to handle history in GWT?
  3. What is the difference between directly creating an object and using GWT.create() method to create an object?
  4. Can we use same beans (data objects with setter and getter methods) in both server and client side in GWT?
  5. What is hosted mode?
  6. How to start your GWT module? (EntryPoint/onModuleLoad())
  7. How GWT handles sessions?