• 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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
  • Piet Souris
  • Himai Minh

2 complex problems

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
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.
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.
Trust God, but always tether your camel... to this tiny ad.
Free, earth friendly heat - from the CodeRanch trailboss
    Bookmark Topic Watch Topic
  • New Topic