Saturday, June 8, 2013

15 Mandatory Core Java Interview Questions - Part 1

1. What is the Object class?

java.lang.object is the superclass of all Classes in java. All classes extend this implicitly, hence All Classes isA Object. They show Object behaviour.

In the sense that all methods in Object classes are available to all classes in Java.


Object of any class can be assigned to Object.



2. Is Java Truly and Object Oriented Language?

Yes, Java is an Object Oriented language but not a pure one. Question arises Why? It is because java supports primitive datatypes like int, float, double. We have wrapper classes Integer, Float, Double also, but for simplicity it also supports primitive classes.

3. Why is main() method static in Java?

Main() method is the entry point of any program. It is loaded before any Class Object is created. Since Static function can be accessed directly from Class level and don't need an object creation. In short, main() is called before Object creation, hence main() is static.

4. Is overloading main() supported?

Yes. main() function can be overloaded. Read here for more details.

5. Explain Method Overloading and Overriding.

When multiple methods in the same class have the same name, it is called method overloading. Function arguments list can differ.
When a subclass, redefine a method present in parent class, it is called Method Overriding. Function name, arguments and return type needs to be the same while Overriding.

6. Example of Multiple Inheritance in Java?

Multiple Inheritance is not allowed in Java. A class cannot extend multiple classes but can implement multiple interfaces. 

7. Difference between JDK, JRE, JVM.

Java Virtual Machine (JVM) is a layer on top of the real hardware. For those who interact with it, JVM acts as though it is the real boss (Machine). But in reality it’s just a Software Hoax on which program is executed. It makes Java platform independent.

Various implementations of JVM which are installed on various Platforms are called JRE (Java Runtime Environment). This is the software which runs and interact with the Real Hardware and provide a JVM. It also contains the libraries required to run applications.

JDK contains JRE, JVM and compiler (javac.exe) along with other things. With JDK one is able to compile (convert *.java to *.class bytecode) and run (java.exe) a program.

For more details read JDK-JRE-JVM.

8. Explain static member/method in Java?

static member/method in Java, can be accesses without instantiating a class and loading an Object of that class. (Class.method). An important quality of static method is that it cannot be overridden. Overriding is resolved runtime with class Objects. Since with static the concept is different, hence overriding is not possible.

9.  What are the primitive data types supported in java?

Below are the data types in Java. For more details read. primitive data types java.

Data Type
Size
Default Value
Min
Max
boolean
1 bit
false
false
true
char
2 byte
'\u0000'
'\u0000' (or 0)
'\uffff' (or 65,535)
byte
1 byte
0
-128 (-2^7)
127 (2^7 -1)
short
2 byte
0
-32,768 (-2^15)
32,767 (2^15 -1)
int
4 byte
0
- 2,147,483,648 (-2^31)
2,147,483,647 (2^31 -1)
long
8 byte
0L
-9,223,372,036,854,775,808
(-2^63)
9,223,372,036,854,775,807
(2^63 -1)
float
4 byte
0.0f


double
8 byte
0.0d



10. How can you define a class as static?

Class as such can't be define as static. All methods/members can be defined as static. We can call such a class as static.
However inner classes can be defined as static. 

11. What all datatypes can be used in switch/case?

A serious drawback of Switch-Case was it just worked with expressions that evaluated to int (int, short, byte, char, Enum). Not anymore. With Java 7 it can take Strings too. Isn’t is awesome?
String fruit = "apple";
switch (fruit) {
case "orange":

12. Give an example of Marker Interface.

Serilaizable/Cloneable are two famous examples of Marker Interface. They are empty interface with no methods inside, but are used to enabling some functionality in the implementing classes.



13. What is the difference between sleep/wait?

Difference in Sleep and Wait

14. Give a usage of instanceof Keyword.

instanceof keyword is used to check if a given Object belongs to a particular class or not. It becomes useful in case of inherited classes. All objects are instanceof Object class.



15. What is Thread in Java?

Thread relates to running of a program. A Thread is a single chain of execution within a program. click here for more details.


Sunday, May 12, 2013

DEPENDENCY INVERSION (D INV)

To put it straight, DI = IoC + D Inv. How? Lets explore.
Before the helper and DI were introduced, Hands/Legs/Face were designed first. When Body was created it just used new Hands/Legs/Face. Body does not dictate the design of Hands or Legs. Suppose Hands were designed to have teeth. Body can’t dictate that Hands should not have Teeth (High level module can’t interfere with design of Low level module, it can just use it). There are there and Body has to live with it. So everyone will eat off their hands, literally.
Programming wise Body is High Level Component and Hands are Low Level Component and are kept in separate packages. Body Component Package depended upon Hand Component Package for compilation. Thus HLC depends upon LLC for compilation.
DInv says other wise. Low Level Components (Hands) also need to confirm  to some abstraction (Hands have to be type of SomeHands, so now we have SmallHands, ThinHands and also TeethHands which are type of SomeHands, but NOT all Bodies need to have TeethHands). Body is also bound by SomeHands. It can’t fit ShortLeg instead of SomeHands.
DInv says both Low Level and High Level modules need to confirm to some abstraction.
Programming wise, this is achieved by separating High Level component  (Body) and Low Level component  (Hands) into separate packages. And the Interfaces (SomeHands, SomeLegs) defining the Behavior/Services which the HLC needs are inside HLC package and are owned by it. Here LLC implement the interfaces owned by HLC. Thus LLC depend on HLC for compilation. Thus usual Dependency relationship is INVERTED.

Saturday, March 23, 2013

Reverse a String in Java

How to reverse a String in java?

Input: javaonjava
Output: avajnoavaj

Well there are some complex approaches to it. Storing the String as character array and then reverse the character array. Convert it back to String.

But since Java is Java. We have all the support available.




Wednesday, March 20, 2013

DEPENDENCY INJECTION (DI)

What I feel is people understand Dependency Injection (DI) more than Inversion of Control (IoC). When I ask in an interview, “What have you used spring for?”. The answer normally is, “I have used it for IoC” or “I have used it for DI”. But when I ask the difference between IoC and DI, I mostly  get the answer, “They are the same” or “DI was earlier called IoC”.
What really is DI? Is it the really new name for IoC? Is there any difference between DI and IoC? Lets try and explore there questions.
Let me begin by stating that DI is not the new name of IoC. DI is something which affirms to IoC concept. When we do DI, we are doing IoC (Not the other way round). Following IoC does not mean DI would have happened. DI is just one of the ways to achieve IoC.
Example: God creating Man
When God creates Man. He would start with an Empty Body (Body Class). Then he would create new Hands, new Legs, new Face inside the Body (inside Body constructor). This Body now has to live with whatever Hands, Legs, Face were created (Tightly coupled). But no one can refute that a Man is created alright.
Now if God wants to create another Man (He would need to do so a lot, given there are 6 billion of us on this planet, and we are born regularly), God will start with another empty Body and try and put different features to it. Say SmallHands, RoundFace, LongLegs.
So now God will keep on creating new Bodies (class Body1, class Body2, class Body3) etc. Poor God!
How nice it would have been, had God just created one Body (written one Body class) and said that it will have SomeHands, SomeFace and SomeLegs.
How nice it would have been had God had a helper (Framework like Spring), who would create different Hands (SmallHands, LongHands), different Faces (RoundFace, SquareFace). He would just copy the generic Body God created and will insert these Hands/Legs/Face to it independently. Good for God!
This is called Dependency Injection, where dependencies (on which Body depends) are not created (inside constructor) when Body is created by God. They are instead created and fitted when Body needs to be sent to Earth.
This affirms to IoC as control of creating new Type of Hands/Face/Legs lie not with the God but with the Helper who makes job of God easier,
This is what they call “Don’t call us, We’ll call you” (Hollywood Principle). Body, please dont call Hands() constructor to create new Hands, instead when Helper needs a Body() to be sent to Earth,  it will create new Hands(), will then call Body and inject the Hands.

Tuesday, January 1, 2013

INVERSION OF CONTROL (IOC)

The more I read about IoC, the more it gets complicated. One thing gets clear though, it is one of the the most misunderstood terms. More often than not, it is confused to be an old name for Dependency Injection (DI). Also people tend to understand it directly via some Code Snippet or via its implementation by any Framework.
In reality it’s just a concept borne out of some one’s imagination one fine day. Hence it should be understood irrespective of any code/framework. First came the logic and then came the code.
Most of the people I meet at workplace, have started off their careers by reading a Java or C++ book before they started to code at workplace.
My case have been the other way round. I started off my career without reading any language specific book per say. I googled knowledge out of internet as per the need arose.
I think this would be an apt example of Inversion of Control. Instead of a Book controlling what I learn and in which sequence. I was in the control of what I needed to learn. Googling (Sending Event) about a particular topic as and when required, I learned that topic (Note: The explanation of topics on Google  is eventually the same as in the book).
To be more specific, the e-version of a book v/s printed version. In e-version, I can search the topic I want to read. So the control moves from book (printed version) to the user (e-version)
Thus the Control got INVERTED.
Examples:
1. GMAT vs CAT
Another good example that I can think of IoC is GMAT exam vs CAT exam. Those who have taken GMAT would understand this better. A question pops up, you have answer it. Then only you can move to the next question. You can’t skip and come back later to the same question. The control is with the Application (GMAT Software).
Consider at the same time CAT Online Exam. We can skip questions, come back later. Choose what question to solve when. Thus some control is shifted to the person who is taking the Exam (Inversion of Control).
2. Simple Delivery vs Midnight Delivery
Another Example is Simple vs Midnight Delivery Service. In simple service, we book a courier. It is upto the delivery guy at what time he will deliver within the SLA.
Midnight Delivery Service is when we want to send our Girl Friend flowers at midnight. Here we are able to set the time when the Delivery guy should deliver (midnight). We can even call the Delivery person and specify/change the timing. Some control shifts from the wish of Delivery Guy to us.
Complete IoC will happen if say someone has sent us a courier. When we get home, we call up the delivery guy and say , “Now I am home, you come and deliver”.

Monday, September 17, 2012

JDK JRE JVM

When we say Java is Platform independent, we mean that same code can run seamlessly on Windows/Linux/Mac machines. We need not change our code or make any special provision in the code to run it on different machines. Such provision is very common in C/C++ code (like porting the code from Windows to Linux), where we instruct the program to run certain parts in linux and bypass them while running on Windows and vice-versa. Its not the case with Java. This is achieved by three simple terms that we will discuss here JDK JRE JVM, the eternal triumvirate.
The relationship can be understood by the diagram below, which we will explore in detail.
jdkjrejvm1

JVM (Java Virtual Machine)

It is primarily JVM that makes Java platform independent. As the name suggests it is a Java Virtual MachineReal Machine is the linux box (real piece of hardware) on which we run our application. Virtual Machine is a layer on top of the real hardware. For those who interact with it, JVM acts as though it is the real boss (Machine). But in reality it’s just a Software Hoax.
Like any Computing Machine, it comes with the caravan of instruction sets and power to play with memory. For different platforms (Windows/Linux/Mac), we have different implementations of JVM. These interact with different Machines in different ways but provide a uniform Virtual Environment. Java program needs to interact just with this Virtual Machine and not the Real Machine, making Java Platform independent. Different JVM implementations might differ, mostly in areas which are not covered by specification provided by Java and does not affect the results of a Java program. These are areas like garbage collection, performance etc.
JVM takes  Java bytecode as input, which it interprets into Machine code compatible to specific Hardware on which JVM is running. To run a program JVM uses class libraries and java.exe provided in the JRE.
Java Bytecode: JVM does not understand *.java files. JDL compiled *.java files and create *.class files, which contain bytecode and understood by JVM. If we take the same bytecode and run it on different enviroments, due to the JVM which is uniform, we will get same results.
This make life simpler for developers,  isn’t it? Why worry about where the code will run. Just write the code and be done.
Compiler compiles the code in a bytecode for a Virtual Processor (JVM) which in turn converts it into Machine code for a Real Processor (LinuX/Windows platform).

JRE (Java Runtime Environment)

Various implementations of JVM which are installed on various Platforms are called JRE (Java Runtime Environment). This is the software which runs and interact with the Real Hardware and provide a JVM. It also contains the libraries required to run applications. Note that it cannot complie the code. It can just provide JVM and libaries which can run a comiled code (bytecode). For compiling the code we need JDK.
In effect JRE = JVM + Few Java packages + Runtime libaries (java.exe)
How it happens is, JVM will run a program using runtime libararies and other files which are there in a JRE. If JRE is missing you cannot run a Java program.

JDK (Java Developer Kit)

This is the Ace among the three. It contains JRE, JVM and compiler (javac.exe) along with other things. With JDK one is able to compile (convert *.java to *.class bytecode) and run (java.exe) a program. It is maily for developers. Without JDK installed there is no point writing a Java code as you will not be able to compile and test it.
Normally if you get a Windows machine to work on, you wont find JDK installed by default. You would just be having JRE (required to run online games which were complied by JDK). Apart from that a lot of softwares we want to run on Windows have JDK compiled code which again requires JRE to run. We need to install JDK separately.
Source code (Test.java) is converted to Test.class (bytecode) by javac.exe compiler tool. Then java.exe (application launcher in JRE) runs it on JVM (which converts bytecode to machine code and run it on OS).

Monday, July 16, 2012

JAVA.UTIL.CONCURRENT BLOCKINGQUEUE INTERFACE

This interface extends Queue interface (which in turn extends Collection interface). All implementations of Blocking Queue are Thread-Safe. Blocking terminology comes from the fact that BlockingQueue provides methods which can make the calling Thread to Wait before proceeding further.

Consumer Thread

If the Queue is empty, the Consumer Thread does not have to explicitly check for the emptiness (and write code to wait() till it becomes non-empty), BlockingQueue provided methods which encapsulate all this. Makes life simpler. So if the Queue is empty, consumer Thread will WAIT, till some element is inserted in the Queue.
1. take(): Just as in a Queue following FIFO, it removes and returns the head. If Queue is empty, it will make the Thread to WAIT till an element becomes available.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Taking example of Continuous Consumer
Queue simpleQueue = new ArrayDeque(10);
...
...
while (true) {
    synchronized (simpleQueue) {
        while (simpleQueue.isEmpty()) {
            simpleQueue.wait();
        }
        simpleQueue.remove();
    }
}
//This can be simplified to below
BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
...
...
while(true) {
    blockingQueue.take(); //Waits till Queue becomes non empty. While loop not continuous
}
2. poll(): Just as in a Queue following FIFO, it removes and returns the head. If Queue is empty, it returns a null. No Blocking here.
1
2
3
while(true) {
    blockingQueue.poll(); //Wont make the Thread WAIT, Continuous while loop
}
3. poll(TIMEOUT): Just as in a Queue following FIFO, it removes and returns the head. If Queue is empty, it will make the Thread to WAIT till the specified  TIMEOUT or till an element becomes available (whichever comes first). Returns null in case it waits till TIMEOUT.
4. remove(object): Just as a Collection, it removes element from Queue when element.equals(object). If more than one element are equal, the one closer to HEAD is removed. Returns TRUE if found, FALSE otherwise. In case of multiple elements which element is removed can be checked with the following code.
1
2
3
4
5
6
7
8
9
10
11
12
BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
blockingQueue.put("1");
blockingQueue.put("2");
blockingQueue.put("1");
blockingQueue.put("3");
System.out.println("Before: " +blockingQueue);
blockingQueue.remove("1");
System.out.println("After: "+ blockingQueue);
Output:
Before: [1, 2, 1, 3]
After: [2, 1, 3]

Producer Thread

Similarly, there are methods to insert in the Queue, whereby we don’t have to write code to check if Queue is full not (and wait() till it has some space free). All this is provided to us already. So if the Queue is full, producer Thread will WAIT, till some element is deleted from the Queue.
1. put(object): Just as in a Queue, inserts the object to the tail. Will make the Thread to WAIT till BlockingQueue is full (specified size for the bounded Queues or Integer.MAX_VALUE for unbounded Queues). Once space is available, inserts the object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Taking example of Continuous Producer
Queue simpleQueue = new ArrayDeque(10);
...
...
while (true) {
    synchronized (simpleQueue) {
        while (simpleQueue.size() == 10) {
            simpleQueue.wait();
        }
        simpleQueue.add("1");
    }
}
//This can be simplified to below
BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
...
...
while(true) {
    blockingQueue.put("1"); //Waits till space becomes available. While loop not continuous
}
2. add(object):  Just as in a Queue, it inserts the object at the tail. If Queue is full, it throws an Exception, else returns TRUE. No Blocking here.
3. offer(object): Just as in a Queue, it inserts the object at the tail. If Queue is full, it returns a FALSE, else TRUE. No Blocking here.
4. offer(TIMEOUT): Just as in a Queue, it inserts the object at the tail. If Queue is full, it will make the Thread to WAIT till the specified  TIMEOUT or till the space becomes available (whichever comes first). Returns FALSE in case it waits till TIMEOUT, TRUE other wise.

Points to Note

1. null elements are not allowed in the BlockingQueue. Remember poll() returns null if Queue is Empty. Hence this restriction.
2. addAll(..) type bulk operations methods inherited from Collection Interface are not atomic. So it might happen that post adding couple of elements, Queue becomes full and fails to add anymore, throwing an IllegalStateException.