• Post Reply Bookmark Topic Watch Topic
  • New Topic

java Integer toString() and static toString() difference  RSS feed

 
Samar Bir
Greenhorn
Posts: 23
IntelliJ IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone.

I am going through API of Integer class. I have a following confusion. It has three versions of toString method. I am confused at these two versions.



I am confused what is the difference. Both methods return the String representation of the primitive. What's use of second version?

Thanks,
Samar
 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first one is invoked on an object of the class which wraps the int value...

The second one is a utility method used on the class itself to transform the int value passed in as an argument to its string representation...
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Samar Bir wrote:Both methods return the String representation of the primitive.

No they don't. The first returns the String representation of an Integer object. There is no primitive involved (except the one that the Integer class is wrapping - perhaps this is what you were referring to ?)
All objects in Java have this method and it is used to produce a String representation of the object.

Samar Bir wrote:What's use of second version?

The second is used when you want a String representation of a primitive int value. Primitives don't have methods, so the Integer class provides various static methods that can have an int value passed to them.
 
Samar Bir
Greenhorn
Posts: 23
IntelliJ IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rico,

That's what my question is. Both are achieving the same thing, then why giving something like on class-level and something on object level.
I am sorry. I am very new to Java. If you can explain your answer with some example, it would be great.

Thanks,
Samar
 
Samar Bir
Greenhorn
Posts: 23
IntelliJ IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Joanne,

Thank you so much. I have understood the concept now. Second one can be used if we want string representation of a primitive. It makes much more sense now.
Thanks so much.

Thanks,
Samar
 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok...

We have an already wrapped value and we want its string representation:


We have an int value and need its string representation
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!