• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Why is it not required to use the reference returned from the method.?

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why the following code dont give compiler error because we are not fetching the return value.

class Temp { }

public class WeirdStringTest
{
public static void main(String args[])
{

WeirdStringTest obj= new WeirdStringTest();

obj.add();

}


public Temp add()
{
return new Temp();
}
}
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because getting returned values is not mandatory. It's generally not a good idea to ignore returned values, but there are time when you just don't care about the returned value. Look at Map#put(Object key, Object value), most of the time you will not use the returned value.
 
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

public static void main(String args[])
{

WeirdStringTest obj= new WeirdStringTest();

obj.add();

}



In the above code .when you invoke add() method you are creating an object .Once add methods finishes execution two things may happen--
1.if you return that object and in main method you store that object reference in a reference variable.It indicates that object has active reference in your program,May be you want that later on in your program.

2.if you dont assign the reference of that object to any reference variabel whose scope is larger than method or if you dont return the object ,then that object is unreachabel after method execution.ie garbage collectible.
 
Please enjoy this holographic presentation of our apocalyptic dilemma right after this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic