Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Sunday, 9 October 2011

Divide by Zero in case of Java

One of the good interview questions I found was related to divide by zero.
Lets take the case:

What will be the output of this code snippet?

public class NaN {

public static void main(String[] args) {
double d = 2.0 / 0.0;
System.out.println(d);
}
}

What's the answer: The code will not compile or will it throw a DivideByZero error? Both are wrong. The code compiles fine and the output is,
Infinity

Let's check another code snippet,

public class NaN {

public static void main(String[] args) {
double d = 0.0 / 0.0;
System.out.println(d);
}
}

The output in this case is,
NaN

Monday, 3 October 2011

Making collections final

Once we write final
ArrayList list = new ArrayList();

We can add, delete objects from this list, but I can not
list = new ArrayList() or list = list1.

So declaring the list final means that you cannot reassign the list variable to another object.

There are two situations in which this can be useful.
  1. You want to make sure that no-one reassigns your list variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood).
  2. When using inner classes you need to declare variables as final in an enclosing scope so that you can access them in the inner class. This way, Java can copy your final variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.


Wednesday, 22 June 2011

Java Interview: tips for the interviewer

This is a brief entry about how an interviewer should conduct a Java based interview. I have been on both side of the table and this is only based on my own observations.  I think most interviews that I attended in the past, and possibly some I have conducted myself, focus on the basic concept. I accept that developers should be aware of the language principles, but how can an interviewer test more advanced principles?

The interview time have to be split into: 

  1. Theoretical concepts
    This 1st phase is about asking the common questions about OOP concepts, differences between interfaces and abstract classes, differences between List and Set, multithreading and so on. If it is required to store answers, do provide a written paper and avoid multiple choice questions. In my experience, open-ended questions allow the developer to express his knowledge better. Multiple choice questions provide unnecessary hints to question answers. Even if I did forget a terminology or a definition by looking at the various answers provided, I can pick the right answer 9/10 times. Theories are central to practices but make sure can be related to the role you are recruiting for.An important point when interviewing a developer, if you have a developer present during the interview, avoid asking domain specific question unless it is something common. I had some interview with senior and lead developers asking questions about a programming problem they have recently encountered and were able to fix after spending months working on it, how am I supposed to know about that unless I have encountered the same issues in the past.
  2. Practical test
    In order to test a developer capability for the role, it is a must that he/she undertakes a practical test. You do not need to give the developer code with bugs for him/ her to fix, I believe this approach is not very useful. I would suggest that all interviewers prepare the developer to take a practical test using their favourite tools (provide two of the most common open source IDE) and provide them with a simple problem domain. In my experience, I had to write some simple factorial algorithm (a single recursive method) to a domain centric web service application (no DB, store data in memory instead) and to more advance concepts. If application multithreading is part of the main day to day job, then ask the developer to write a simple application that shows that.
    This practice exposes several features of the developer; from its reasoning by writing simple algorithm to coding practice (commenting and Java best practices) and problem solving.


After all, I believe that programming is more about logical reasoning and coding. The more senior we get in our profession, the harder it is to answer simple questions with straightforward answers; we get carried away and provide a complex answer to something so simple. We cannot talk baby talk anymore; our tongue is full of jargon. All developers should follow the KISS principle when answering theoretical questions but ultimately they should excel in the practical test. If they are good enough, they should use a text editor to write their codes and compile it through the shell (JVM command line).
Another thing that all interviewers should know; developers have very good memories and therefore can memorise more than 115 interview questions; I would recommend you to focus more on a practical test.

This was a brief entry for interviewers. The web is full of tips and questions for the interviewees and I do not see any point in duplicating them here.  As usual, this is based on my experience and belief, you are always welcome to comment. Also, support my blog by visiting my advertisers (by clicking on the link on the right) they might have something that you might need.

Saturday, 11 June 2011

How to force the subclasses of a concrete class to override a method?

There is no such real world scenario where a concrete entity will want to force a more specific entity to override its method. If it is to be overridden then why not make the super class as abstract.

Anyways, the logic behind the interview questions being asked now a days is something which requires best talent from the psychology field.

Solution: The solution which I have come up with for the above Java Interview question is to use the instanceof operator in the super class and throw an exception if the instance on which method is being invoked is found to be of the sub class. The sample program showing this scenario follows:

Though still its not like generating compile time error but gives exception at runtime.  Do suggest if you have a better solution.

public class Test{

void test() {
if ((this instanceof Test1)) {
throw new RuntimeException();
}
System.out.println("passed");
}

public static void main(String[] args) {
Test t1 = new Test();
Test1 t2 = new Test1();

t1.test();
t2.test();
}

}
class Test1 extends Test {

}

The output of above program is:
passed
Exception in thread "main" java.lang.RuntimeException
at Test.test(Test.java:5)
at Test.main(Test.java:15)

Monday, 23 May 2011

Java interview questions on garbage collections

Which part of the memory is involved in Garbage Collection? Stack or Heap?

Ans) Heap

What is responsiblity of Garbage Collector?

Ans) Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.

Is garbage collector a dameon thread?

Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.

Garbage Collector is controlled by whom?

Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of jvm can not be guaranteed.
One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.

When does an object become eligible for garbage collection?

Ans) An object becomes eligible for Garbage Collection when no live thread can access it.

Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.

How can the Garbage Collection be requested?

Ans) There are two ways in which we can request the jvm to execute the Garbage Collection.

  • 1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program.
    The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection.
  • 2) Call the System class System.gc() method which will request the jvm to perform GC.

What is the purpose of overriding finalize() method?

Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?
Ans) No

How many times does the garbage collector calls the finalize() method for an object?
Ans) Only once.

What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object terminates.

What are different ways to call garbage collector?
Ans) Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().

How to enable/disable call of finalize() method of exit of the application
Ans) Passing the boolean value will either disable or enable the finalize() call.

Runtime.getRuntime().runFinalizersOnExit(boolean value) . 

Java interview questions on packages

Which package is always imported by default?
No. It is by default loaded internally by the JVM. The java.lang package is always imported by default.

Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains anything about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*?
No you will have to import the sub packages explicitly. Importing com.bob.* will import classes in the package bob only. It will not import any class in any of its sub package’s.

Explain the usage of Java packages.
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
For example: The Java API is grouped into libraries of related classes and interfaces; these libraries are known as package.

Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.BOB compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, cannot resolve symbol.

Thursday, 28 April 2011

Interview Questions : JEE Web Application Development

The answers are very brief and are intended to provide the direction towards which one should format his answer. Be more detailed and clear with your answers. All the best.


1) How do you differentiate between Core Java and Enterprise Java?
Expected Ans: Core Java is something that provides the API's like regular expression, String handling, collections. But enterprise java involves writing scalable, secure and per-formant applications which can have large user base.

2) What do you generally do after you have resolved a problem?
Expected Ans: Perform the Root Cause Analysis and make sure the changes done have not effected any other module.

3) What is JSON? Can you represent JSON as Java Object?
Expected Ans: JSON stands for Javascript object notation and is used to initialize Javascript objects. Yes it can be used as Java object also. Provide more info here

4) What kind of HTTP request does the <a href="url">text</a> generate?
Expected Ans: It will generate HTTP GET request

5) What are the common browser issues you will keep in mind while creating a web application?
Expected Ans: 1) User pressing back/refresh button
                            2) Browser crashing
                            3) Session issues
                            4) Compatibility across web browsers

6) What steps will you take for ensuring the proper security of an web application?
Expected Ans: Stuff like Encryption, Authentication and Authorization

7) The Server and Database are working fine at your end but not on customer machine. What will you do?
Expected Ans: 1) Check if the customer has not done any customizations
                             2) Provide a test build same as running at my end (ask customer to take a backup of their  app)
                             3) Check out how the customer is using the application


8) A web application is running but pages are loading slow. How will you figure out what the problem is?
Expected Ans: Look for threading, database, caching issues.

9) What is the difference between frameworks like Jquery/DOJO and AJAX?
Expected Ans: Jquery and DOJO are java script frameworks for writing rich web applications but AJAX is a server communication mechanism which can issue requests without page reload.

10) What are the reasons for a page not found error and how will you sort it out?
Expected Ans: 1) The URL being sent is wrong
                             2) The web.xml mapping is wrong 
                             3) The web server is down 
                             4) The application has not been deployed

11) How will you know whether a Java file is a servlet or not?
Expected Ans: It will extend from HttpServlet class

12) When will you use Servlet and JSP or MVC framework?
Expected Ans: While framework provides a number of components and allows one to concentrate more on the business logic but Servlets and JSP are used for controller and view layer respectively.
13) What are the common issues you have faced in web applications and how did you resolve them?
Expected Ans: 1) Server not starting up. Proper heap size not set
                             2) Migrating from JBoss to Weblogic. Wrote a number of XML configurations
                             Any other generic problems faced during development/support


14) How do you keep yourself updated about the latest web technologies?
Expected Ans: Whatever websites/blogs/forums/authors you follow.

15) What was the last technical book you read?
Expected Ans: Whatever you have read

Sunday, 17 April 2011

Cloning Interview questions

Q1) What are different types of cloning in Java?

Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning.

Q2) What is Shallow copy?

Ans) In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.


      
Original
Figure 1: Original java object obj
The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.
Shallow Copy
Figure 2: Shallow copy object obj1

It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contain any other object no new reference is created

Q3) What is deep copy and how it can be acheived?

Ans) In deep copy the object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.



Original
Figure 3 : Original Object obj
When a deep copy of the object is done new references are created.
Deep Copy
Figure 4: obj2 is deep copy of obj1

One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks:

You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have a third-party class for which you do not have the source and which is marked final, you are out of luck.
You must be able to access all of the fields of the class̢۪s superclasses. If significant parts of the object̢۪s state are contained in private fields of a superclass, you will not be able to access them.
You must have a way to make copies of instances of all of the other kinds of objects that the object references. This is particularly problematic if the exact classes of referenced objects cannot be known until runtime.
Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain. The method must be revisited any time a change is made to the class or to any of its superclasses.
Other common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is simple: Write the object to an array using JOS̢۪s ObjectOutputStream and then use ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling repeated references to the same object within the graph.

It will only work when the object being copied, as well as all of the other objects references directly or indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.) Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let Java̢۪s default serialization mechanisms do their thing. Java Object Serialization is slow, and using it to make a deep copy requires both serializing and deserializing.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and writeObject() methods), but this will usually be the primary bottleneck. The byte array stream implementations included in the java.io package are designed to be general enough to perform reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream .

Q4) What is difference between deep and shallow cloning?

Ans) The differences are as follows:

Consider the class:
public class MyData{
String id;
Map myData;
}

The shallow copying of this object will have new id object and values as “” but will point to the myData of the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will be new id object and also new myData object and independent of original object but with same values.

Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For deep copying some extra logic need to be provided.

Q5) What are the characteristics of a shallow clone?

Ans) If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.

Q6) What are the disadvantages of deep cloning?

Ans) Disadvantages of using Serialization to achieve deep cloning –

Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..