• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ambiguity in compilation error

 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic