Sunday, July 4, 2010

Core Java Interview Questions, Core Java Questions, Java Certification questions

1) What is meant by pass by reference and pass by value in Java?


Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
Take the badSwap() method for example:

public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}

When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:

public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}

public static void main(String [] args)

{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}

If we execute this main() method, we see the following output:

X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0

The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.
Image 1


Image 2

***************************************************************

2) If one is overriding method equals() of an object, then which other method should also be considered?


hashCode()

2 comments:

Unknown said...

Good work.
You can also refer
http://pragyarawal.blogspot.com/

Unknown said...

Thanks for that post, it was really helpful.
If you have very little experience or you have just started your career, then CAPM certification will surely help you to take your career to the next level. This certification shows your employer that you are a capable person, and you have the ability to manage projects. It also shows that you are well aware of the terminology used in the PMBOK Guide.