• 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

2 complex problems

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
plz provide justification on these 2 problems
1) String s = "abcde";
StringBuffer s1 = new StringBuffer("abcded");
if ( s.equals(s1) )
s1 = null;
if ( s1.equals(s) )
s = null;
why does not the compiler give an error?
can a null string buffer be compared or used ?

2) can a method return null?
if yes, what happens in each case when a method returns null and the return type is i) void ii) String iii) int
public String method()
{
return null;
}
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1.
The compiler should not give an error, as long as equels accepts the type send (I believe that equals take Object, so there is no problem). Given that the equals won't return true, neither reference will ever become null. If you change the code so they do, all you get is a runtime-error indicating null pointer.
2.
Yes, a method can return null, if if the returntype is a reference. If the returntype isd void, you can only return from the function, not return something (null count's as something being returned). If the returntype is int, you can only return numbers.
Look at the following

If no customer matching the customerId is found, null is returned, else the matching customer is returned. So you see, not only is it allowed, somtimes it's recomended to return null.
Ofcourse the method-example you gave can be a usefull way of implenting some abstract method you don't like to code right now, but need to test other parts of the program.
/Mike
 
reply
    Bookmark Topic Watch Topic
  • New Topic