Sunday, December 18, 2011

Static Block of a Class

This post intended to be a quite quick. So let's begin. Could you tell me the output of the code written below?


public class EmptyClass {

static{
System.out.println("Hello World.");
}

}

There can be following options
A. It will not compile.
B. It will compile but it will not run and it will just print exception.
C. It will compile and it will not run but it will print "Hello World" and then will print the exception.
D. It will compile and Run without issues.

After seeing the choice, answer looks quite simple. Is not it?
Anyways lets analyze.
A. It will compile as static blocks are allowed in java and java does not force you to write main method in each and every class. So there are not any issues while compiling the class. So A is not the right option.

B. It will not run, true. As java says, there should be main method to run an application. There is not any run method is the application. But there is a static block in the application. What will happen to this static block? This options seems to correct but puzzle has not completely solved yet. Lets move forward and see if B is correct or there is any other better option available.

C. We accept it will compile but it will not run as main method is not available in the class or JVM. But as java say, before as soon as it loads any class in memory it executes all its static blocks first. So to run the application class will be loaded into the memory so static block exists in the class will executed which in turn will print "Hello World". So it seems to be most appropriate answer.

D. Do we have any scope and requirement left to discuss last options. No

I learnt this lesson while discussing few basic java questions with my friend. Nice but tricky is not it... Anyways will stop here. B bye.

Tuesday, December 13, 2011

Problem with Class Downcast

Sometime I think, I have gained a lot of knowledge in Java and I know lot of things in Java, but once in a while Java keeps pushing my believes to the corner and demonstrates it's superiority. Most of times it is basic java which deceives me. Here is my story.

Today one of my colleague asked one question and I did not have any answer for his question. The issue in concern belongs to the program written below.


class SuperClass {

void display(){
System.out.println("SuperClass Display.");
}

}

class SubClass extends SuperClass{

void display(){
System.out.println("SubClass Display.");
}


public static void main(String[] args){
SuperClass superClsInstance = new SuperClass();
SubClass subClsInstance = (SubClass) superClsInstance;
subClsInstance.display();
}

}

In this case I assumed downcast should happen without any issues and it should print message based on object instance. So in this case subClsInstance is referring to Object of SuperClass and it should print message mentioned below.
SuperClass Display

But no. It is not so simple.

It will throw ClassCastException. Heck Why? What have I done which made it throw such stupid and merciless exception? I am devastated and I do not even know basic of DownCasting, shame on me a 5 year experience java developer do not know such small thing. Anyways let me find out the reason for this behavior.

Hmmm, Interesting na.... I always knew that I am not very good in java and google and Sun have proved me right. As per the information available downcast is possible if and only if object created is a type of Class reference being downcasted to..

Lets take few example... Dog is an animal and An animal is dog only if it is a Dog. If you write same thing in the code so it would be...

Animal ani = new Dog();
Dog dg = (Dog) ani;

So in example listed above, Dog is an animal and it will down cast without problems as code is saying Dog is Dog...


Animal ani = new Animal();
Dog dg = (Dog) ani;
So here in example listed above, here Animal is an animal and it will not down cast as code is saying Animal is Dog...It can not be, we do not have information about Animal. This can be some other animal so Java can not assume anything. It will say that it does not have any idea about this animal so Buzz off.

In our case same thing is happening.We have created an object of SuperClass and asking it to tie up with SubClass. Java says no, do not bog me out with such stupid things and take care of your code better.

Oops java is right and I am wrong. Cool then I learnt something today and shared with you all. Hope you will learn and will not cause such stupid problems in code and will not screw up your interview. 


PS: Stay away from downcasting it is not only but also venomous and code safe.

Tuesday, October 4, 2011

Override Annotation JDK 5 v/s JDK 6

Sometime problems are way beyond your understanding and you could not find the solution for them.

Problem 1

I faced one such problem while I was working on eclipse and JDK5. I created a derived class extending the abstract class. Following is the definition of my abstract class.


public abstract class test {
public abstract void unimplementedMethod(Object[] params);
}

I overrode my abstract class in the class mentioned below.

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

Eclipse was showing a red around the method I had implemented and it was displaying error mentioned below. 
The method unimplementedMethod(Object[]) of type ImplementedTest must override a superclass method

As I see I have not done anything incorrect, I took the exact signature required and pasted in the derived class. After couples of hours of brain storming I found out a import definition of Object. 

import org.omg.CORBA.Object;
public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

So how did It manage to sneak into my class? Sometimes eclipse assist you to add required import statements. This time also it appended the import statements, but it appended one additional statement which was not required, and to figure out such a small thing( From the code of 2k lines) it took hours of efforts.

Problem 2
In JDK5, @Override annotation was not working for me. I had an interface and one of my class was implementing the interface.

public interface Test {
public void unimplementedMethod(Object[] params);
}

Class implementing the interface is as follows:

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

Eclipse shows the error mentioned below:
The method unimplementedMethod(Object[]) of type ImplementedTest must override a superclass method

If I remove @override from here it works fine.
If I change my JDK to JDK6, it works without showing any error.
If I change Test interface to test abstract class, it works.

public abstract class Test {
 public abstract void unimplementedMethod(Object[] params);
}

Class implementing the interface is as follows:

public class ImplementedTest extends Test{
@Override
public void unimplementedMethod(Object[] params) {
// TODO Auto-generated method stub
}
}

It works fine. This was non-understandable behavior along with sun has not provided any information about such behavior.

But this behavior has been encounter by different individuals and according to them, in JDK5 when you are implementing the interface then JDK5 do not understand it is override and @Override annotation does not work whereas when you are overriding the method from other class then @Override annotation work without any problem. This confusion was removed later in JDK6. In JDK @override works for interface and general classes.

Source of Reference:

Thursday, September 22, 2011

Eclipse/ANT Error Specified VM install not found



My company provided me new laptop and happily I moved from my old rusted desktop to new shining, powerful and portable laptop. Everything was copied without problem and I started working. But is not it strange to see everything working perfectly fine? I was stunned but happy as well. 

I started using the installed application. Eclipse was working fine until I tried building (Using ant) my application. Ant showed me a scary popup displaying "Specified VM Not found..." 



Simple solution, there is JDK/JRE problem with the system. Correct the JRE and JDK of the project. I did, but it did not work. I googled and found following 2 solutions.

You might even face this problem when you upgrade ant plug-in.

Solution 1
Remove the file which stores build information about the project and restart the eclipse. You can find the respective file in "${PROJECT_WORKSPACE}/.metadata/.plugins/org.eclipse.debug.core/.launches/${PROJECT_NAME} build.xml.launch"

Solution 2 (Location and Screen Shot may differ for different Eclipse Version. Following screen shot and paths are valid for Eclipse Version 3.7)

Go to RUN->External Tools ->External Tools Configurations… 


It will open console below. Select your build.xml(in my case it is abc build.xml). Move to JRE tab. 



Select the appropriate JRE.



Apply the changes and run the build xml. No need to restart eclipse, and you will not face the problem again.

Bmmm, Solved. Saved time.

Friday, September 16, 2011

Immutable Classes

Class whose instance object can not be modified are called immutable classes. In Java, Strings are best example of immutable classes. Though Java tackles Strings in differently manner but still they maintain the immutability of String class. In more technical terms, Immutable object are the objects whose state can not be changed.

What is the state of the object?
State of the object is value of its fields.

public class User {
String firstName;
String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

If you create instance of User class with Java as first name and Developer as last name, then userObject state is Java Developer.

But later you can change the last name to Programmer. So latest state would be Java Programmer. So in this case our class is mutable and it can alter the state based on the requirement.

What is an Immutable Object?
As mentioned earlier object whose state can not be altered is immutable object.

In Effective Java, Joshua Bloch makes this compelling recommendation :
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

How to create Immutable object/class?
To create immutable object prototype should be such that it should not provide a way to change the value once object has been created. Sun has defined one contract which should be followed to create immutable classes. Sun Immutable class contract.

Remove the setter methods.

public class User {
String firstName;
String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

Lets analyze if this solution will make the class immutable completely. Actually it will not. Because by default fields are visible to the class existing in same package. firstName and lastName are still exposed to classes in the same package. So it is still not safe.

Make all fields as private to the class


public class User {

private String firstName;

private String lastName;

public User(String firstName, String lastName, int identitiNumber) {

this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

Looks like we are safe now. But it does not look like. Though in our strings are immutable objects but lets say firstname and lastname are mutable objects. Then some one can take the reference of the object and change its property. So to by pass this problem, we will not return reference of the object but we will return cloned object.

Get should return cloned object


public class User {

private String firstName;

private String lastName;

public User(String firstName, String lastName, int identitiNumber) {

this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName.clone();
}
public String getLastName() {

return lastName.clone();

}

}



Make the class prototype final and all the final


Seems like class is safe and will do great. But to secure class/code secure from security threats and reflection uses we should mark class and its fields final. Generally class is marked as final so that any developer should not create any mutable class extending immutable class. If you are leaving this class non-final then java docs should provide basic purpose of leaving this non-final, so that developer extending the class should be sure about the complete feature of the class. For more information

Make the class prototype final and all the final


public final class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName, int identitiNumber) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}

What are the advantages of Immutable object?
Okay, I have created immutable object. What next? How will it help me to improve my application? There are lot of questions that bugged me after creating first real immutable object. I search a little bit and most of the places suggest me thread safety is the biggest advantage of immutable classes. Lets figure out all possible advantage of immutable classes over mutable classes.

Thread Safe
When threads are sharing objects then it is mandatory to synchronize the shared object when state of shared object is changed by . In case of immutable objects we do not have any ways with which state of the shared object can be modified. So if multiple threads are sharing the same object, even then we do not have to worry about changes in shared data. As data for all the threads will remain consistent so there will not be any reading issues. So while writing thread code, we can use immutable object without any issue.

As immutable objects do not need additional protection at the time of thread handling, so additional efforts of synchronization will be by-passed. So application will become little faster than synchronized application.

Simple to construct, test, and use
Due to immutable behaviour of the object, these object are less error prone and can be tested easily. They are safe in threads so there are less complexity involved with the threads.

Do not need a copy constructor and clone
It is not required to create copy constructor for any immutable classes, because reference of the class will solve the purpose of copying.
For mutable classes copy constructor creates the copy of the existing object and later this copy can be altered as per the business need. Whereas in case of Immutable object user can not change the object, so instead creating the same object again, it is more advisable to return the same object.

Allow hashCode to use lazy initialization, and to cache its return value
Lazy initialization is the process to delay the process of instantiate/process something until it is necessary. So in case of immutable objects compiler need not to use hash code operation for each and every object until it is necessary. As hash code of the object will not change until the object remains in the memory, so hash code for the object can be cached for future references.

Do not need to be copied defensively when used as a field
It is not required to copy all the fields of the immutable object. As everything is unshakable so it is okay to return the reference of the object instead copying it deeply.

Make good Map keys and Set elements
As caching of the object's hashcode is possible so it makes better performing Maps and sets which internally uses hashing for faster access.

Always have failure atomicity
The transaction subtracts 10 from A and adds 10 to B. If it succeeds, it would be valid, because the data continues to satisfy the constraint. However, assume that after removing 10 from A, the transaction is unable to modify B. If the database retains A's new value, atomicity and the constraint would both be violated. Atomicity requires that both parts of this transaction complete or neither.

If an immutable object throws an exception, it's never left in an undesirable or indeterminate state.

What are the disadvantage of Immutable object?
So many advantage, then why caring about disadvantage. Why does every java developer not make all classes immutable? Why do we need mutable class when immutable are solving all the earthly and programmatic complexities. Anyways I believe we should know it. Following are few problematic areas of immutable objects.

Memory requirement

With immutability, any time you need to modify data, you need to create a new object. This can be expensive. Imagine needing to modify one bit in an object that consumes several megabytes of memory: you would need to instantiate a whole new object, allocate memory, etc. If you need to do this many times, mutability becomes very attractive.
Conclusion
As it is evident immutable object has lot of advantage over mutable object.Immutable objects (and more particularly, immutable collections) avoid all of these problems. Once you get your mind around how they work, your code will develop into something which is easier to read, easier to maintain and less likely to fail in odd and unpredictable ways. Immutable objects are even easier to test, due not only to their easy mock ability but also the code patterns they tend to enforce. In short, they're good practice all around!

Source/References(Used to write this post)


http://www.javalobby.org/articles/immutable/index.jsp

http://www.informit.com/articles/article.aspx?p=20530

http://www.javapractices.com/topic/TopicAction.do?Id=29

http://www.ibm.com/developerworks/java/library/j-jtp04223/index.html
http://www.javaranch.com/journal/2003/04/immutable.htm
http://www.javalobby.org/articles/immutable/index.jsp
http://www.ibm.com/developerworks/java/library/j-jtp02183/index.html
http://en.wikipedia.org/wiki/Immutable_class
http://stackoverflow.com/questions/5652652/java-advantages-of-of-immutable-objects-in-examples

Sunday, September 4, 2011

Why do we need Good API design?

I am not gonna write down some document on this. I am just giving you a video where Josh is describing the requirement of having good API infrastructure.

http://www.youtube.com/watch?v=aAb7hSCtvGw

Friday, August 5, 2011

Java: Pass by Value

I was in an interview and interviewer asked me the following question.

public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

What is the output of the following problem?

Though I knew Java is pass by value but at the time of function call Java passes memory reference of the objects. So with the conviction I wrote the output of the program.

Before function call S1 is: A1
After function call S1 is: A12

Interview was over, I returned home, wrote the program and ran it in my eclipse. Bomb... It exploded. Results were not as I expected. WTF, why are those results not the same as I expected? I am the Java bond I can not be wrong. Instantaneously I pinged for an assistance. I wanted to hear "there is a problem with my eclipse instance. I should dump the current eclipse and take the latest eclipse soon." But instead hearing those words  I got following response.

Before function call S1 is: A1
After function call S1 is: A1

My expectation were shattered and I started arguing. Argument ended with my broken believe and I figured out "I have to cover a lot more about java fundamentals".

Anyways let me tell  you how does java pass the object to the function. In general java do not differentiate between Objects and primitive data type. It uses copy operation to pass the value of both type of data types.
If you have overridden copy method of your class then java will copy the object based of your implementation otherwise it will copy the object shallowly, in other words we say java uses shallow copy functionality of the objects. In case of shallow copy it creates a new reference to the object passed to the method. Now whenever you change in this method, are reflected back in the mutable classes, whereas in case of immutable classes it is not possible to change the object so we refrain ourselves to changing anything in those classes.

Lets review the following program.


public class PassByValueInJava {

int xy = 0;
private static void modifyPav(PassByValueInJava pav3 ,PassByValueInJava pav4) {
int temp  = pav3.xy;
pav3.xy = pav4.xy;
pav4.xy = temp;
}

public static void main(String[] args) {
PassByValueInJava pav1 = new PassByValueInJava();
PassByValueInJava pav2 = new PassByValueInJava();
pav1.xy = 10;
pav2.xy = 20;
System.out.println("Before Modify:::: pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
modifyPav(pav1, pav2);
System.out.println("After Modify::::pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
}

}


Can you guess what is the output of the program written here?
After seeing the above example I thought it should not switch the values. So results should be the following
Before Modify:::: pav1 x:10 pav2 x:20
After Modify:::: pav1 x:20 pav2 x:10

Now it is strange. Why did swapping happened? Was there something different?

Okay, lets analyze what has happened in this program? Main function calls the modify function and providing them the copy of pav1 and pav2. As copy is a shallow copy, so in this case Java will create a reference which will point to the same memory location of the previous object. Memory location depicts the situation well here.

Why did not same thing happened when string object was passed to the method.
As string in java are immutable so java deals with string in a different manner. Initially when S1 = A then string was pointing to one memory location and as soon as S1 = S1 + 1, it creates new string object and S1 was assigned to it.

Now when Main called modify function s1 was pointing to A1 memory location whose reference was passed to modify function. When string s2 got changed, then it started pointing to the A12 string object's memory location. But s1 is still pointing to the A1 string object's memory location. That is why value for s1 did not modify.

So it is clear that java always uses pass by value and as java tackles string in a complete different way, this is the reason we see such a huge difference between objects and strings.

Program mentioned above could enhance with the following


public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          s1 = modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

It will result in the expected output.

Friday, July 22, 2011

Interview Question: Puzzle - 100 Prisoners

In my latest interview I encountered the following puzzle.

There are 100 prisoners in the prison. All of them have either black or white cap.

Jailer has asked them to stand in the queue such that nth guy can see caps of all the guys standing ahead of him, but he can not see his own cap.

It means Guy standing at 100th position can see caps of all other 99 guys. Prisoner standing at 99th position can see caps of rest of 98 guys standing ahead of him.

Now jailer proposes to release the guy who can guess correct color of his own cap.

Assuming All the prisoner are nice guys ;), who can sacrifice for others, device a method which can help to release maximum number of prisoners.

Tuesday, June 14, 2011

Interview Question: Database Query: Find nth maximum salaried employee.

This question was asked to me in an screening process of a product based company.

Oracle database has employee table having EMPLOYEE_ID and SALARY as columns. Identify all the employee who get 3rd best salary in the company.

My instant answer was as follows:

SELECT * FROM EMPLOYEE WHERE ROW_NUMBER = 3 ORDER BY SALARY DESC

There was instant reaction, this query is wrong. Yes, it is. It will give me the 3rd most earning employee of the company but it will give me the THIRD BEST salary of the company.

So I modified my query a little bit and answered as follows:

SELECT * FROM EMPLOYEE WHERE SALARY = (SELECT DISTINCT(SALARY FROM EMPLOYEE WHERE ROW_NUMBER = 3 ORDER BY SALARY DESC) )


This query will work fine on oracle database but will not run on any other database. Interviewer was right. Now I did not know the way to figure out the third best salary. I did some Google search and found following options.

SELECT * FROM (SELECT EMPLOYEE_ID, SALARY, RANK() OVER (ORDER BY SALARY DESC) RANKSAL FROM EMPLOYEE) WHERE RANKSAL = 3;


SELECT * FROM EMPLOYEE E WHERE 3=(SELECT COUNT(DISTINCT SALARY) FROM EMPLOYEE WHERE E.SALARY<= SALARY);

SELECT LEVEL,MAX(SALARY) FROM EMPLOYEE WHERE LEVEL =3 CONNECT BY PRIOR SALARY > SALARY GROUP BY LEVEL;


So there are few ways to to figure out the third best salary.

Now during interview this question can be twisted in the following manner.

  • Find the 3rd Minimum Salary.
  • Find 10th Maximum/Minimum Salary.
  • Find nth Maximum/Minimum salary of the Employee.
  • Find all employees having salary less than 3rd best salary.

Interview Questions - Puzzle

A person has 50 Red Balls, 50 Blue Balls and two empty Jars with the capacity of 200 balls. This guy has to distribute following balls in the jars available to him.

Distribute the balls such that probability of withdrawing the red ball is maximum.

Assumptions:

  • Person can pick any ball from any of the jars.
  • Jars need not to have number of balls.
  • It is not possible to place all the red balls on top of blue balls (This ordering will not work.) Person can shake the jars before withdrawing the ball.
In case of any doubts regarding the question, please comment.

Monday, May 16, 2011

Time Complexity of the Solution

Could you suggest me time complexity of the following solution:

02.// import java.math.*;
03.class Solution {
04. 
05.int sum = 0;
06.int sumTillCurrentIndex = 0;
07.int sumFromBack = 0;
08.int equi ( int[] A ) {
09.for(int i : A){
10.sum += i;
11.}
12. 
13.if(sum - A[0] == 0 ){
14.return 0;
15.}
16.if((sum - A[A.length -1]) == 0){
17.return(A.length -1);
18.}
19.sumFromBack = sum - A[0];
20.for(int index = 1; index < A.length - 1; index++){
21.sumTillCurrentIndex += A[index - 1];
22.sumFromBack -= A[index];
23.System.out.println("" + sum + ":"
24.+ sumTillCurrentIndex + ":" + sumFromBack );
25.if(sumFromBack == sumTillCurrentIndex){
26.return(index);
27.}
28.}
29.return -1;
30.}
31.}