wood burning stoves 2.0*
The moose likes Servlets and the fly likes Confusion with return type of getAttribute() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Confusion with return type of getAttribute()" Watch "Confusion with return type of getAttribute()" New topic
Author

Confusion with return type of getAttribute()

upanshu vaid
Ranch Hand

Joined: Sep 07, 2012
Posts: 73

Hi,
In chapter 5 of head first servlets and Jsp I am not able to understand the below code
getServletContext().setAttribute("foo","22");
getServletContext().setAttribute("bar","42");
out.println(getServletContext().getAttribute("foo");
out.println(getServletContext().getAttribute("bar");
As the return type of getAttribute()method is Object so why we there is no casting done.
Thanks
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

You can easily answer this yourself: What type of parameter does the println() method expect?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
upanshu vaid
Ranch Hand

Joined: Sep 07, 2012
Posts: 73

Println method expect string so if I am not wrong tostring method of string class will be called
Verify me if I am correct
Thanks
German Gonzalez-Morris
Ranch Hand

Joined: Nov 16, 2009
Posts: 191

Yes, that's right.

For any doubt in method is always useful to check the javadoc:

http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#println%28java.lang.Object%29

[javadoc] println

public void println(Object x)

Prints an Object and then terminates the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

Parameters:
x - The Object to be printed.
[/javadoc]


http://devwebcl.blogspot.com/
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

German Gonzalez-Morris wrote:Yes, that's right.

Well, no it's not; as the javadoc you linked to points out.

upanshu vaid wrote:Println method expect string so if I am not wrong tostring method of string class will be called
Verify me if I am correct

You are not correct. Don't guess -- check the documentation as German has suggested.
German Gonzalez-Morris
Ranch Hand

Joined: Nov 16, 2009
Posts: 191

Bear Bibeault wrote:
German Gonzalez-Morris wrote:Yes, that's right.

Well, no it's not; as the javadoc you linked to points out.


yeah, it is wrong my first comment line...
Fortunately I copy-paste the javadoc where it is verbatim explained
 
 
subject: Confusion with return type of getAttribute()