• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ambiguity in compilation error

 
Sham Grandhe
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai friends,
this one more, the ans is 4 but i answered it as 1

What will happen when you attempt to compile and run the following code
public class StrEq{
public static void main(String argv[]){
StrEq s = new StrEq();
}
private StrEq(){
String s = "Marcus";
String s2 = new String("Marcus");
if(s == s2){
System.out.println("we have a match");
}
else{
System.out.println("Not equal");
}
}
}

1) Compile time error caused by private constructor
2) Output of "we have a match"
3) Output of "Not equal"
4) Compile time error by attempting to compare strings using ==
plz see to it
thanking u
shyam
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shyam,
I think the answer should be (3), not (4).
First of all, Statement (1) is not correct becos it can compile successfully. Private Constructors only mean, if you have another program, say Test.java, if you want to create an object of type StrEq in Test, it is not allow.
However, it is allowed for an object to create its own instance inside its own methods!!! Becos Private means only the owner class can access the method, but now, it is the owner class to call the method.
Secondly, (s == s2) only means whether object s is the same object as of object s2, and thus, no matter they equal or not, no compliation error will be encountered. And thus, (4) is not correct.
As said, since s is not the same instance of s2, and thus, "NOT EQUAL" will be printed. So, (3) is correct.
Nick.
 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi shyam,

I think the answer is 3 as explained by Nick.Coz strings can be compared using the == operator and this will result true when both s and s2 refer to the same object.
But , here in this case as they dont refer to the same object the result of == operator is false and prints "Not Equal"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic