• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't this "autobox"?  RSS feed

 
Bari Clark
Greenhorn
Posts: 7
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List<String> list = new ArrayList<String>();
list.add("1");
list.add(7);  // why doesn't java autobox int 7 to a String in this case?
 
Bari Clark
Greenhorn
Posts: 7
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bari Clark wrote:List<String> list = new ArrayList<String>();
list.add("1");
list.add(7);  // why doesn't java autobox int 7 to a String in this case?


I think I understand now. Is it because auto boxing would take int 7 and make it an Integer, but can't autobox to a String.
I'm confusing the fact the when concatenating a String, it will convert int to String. String s = "1" + 7 results in s = "17", right?
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bari Clark wrote:. . . auto boxing would take int 7 and make it an Integer, but can't autobox to a String.
Correct If you look in the Java® Language Specification, it will tell you that boxing only affects the eight wrapper classes.
. . . when concatenating a String, it will convert int to String. String s = "1" + 7 results in s = "17", right?
Yes, but that's a red herring. That requires the concatenation operator, which uses a completely different mechanism.

Beware: both links may be difficult to read.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!