This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

difference in System.out.println() vs. assigning a String  RSS feed

 
justin wall
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm baffled by this. Why do I get and error with the second line and not the first?
System.out.println("INSERT INTO _columns(name,table) VALUES('" + loop.next() + "','" + newSA.tables.get(loopCount) + "')");
String q1 = ("INSERT INTO _columns(name,table) VALUES('" + loop.next() +"','" + newSA.tables.get(loopCount) + "')");
(newSA.tables is a list)
I get this with the second line, but not the first:
java.util.NoSuchElementException
at java.util.AbstractList$Itr.next(AbstractList.java:423)
at tangoParser.parseFile(tangoParser.java:156)

Thanks,
Justin Wall
 
kyle amburn
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Justin-
When you use the System.out.println() method, the method parses the paramaters and calls the toString() method of the paramater object when required. When you declare a String literal (or a String object) this is not done. Therefore you need to append the toString() to the object such as loop.next().toString() whenever the value returned is not a primative type or a String object itself. Also if the object being returned is of Object type but has a String as the actual object, you need to make an explicit cast.
Hope this helps,
Kyle
 
Marilyn de Queiroz
Sheriff
Posts: 9080
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kyle amburn:
When you use the System.out.println() method, the method parses the paramaters and calls the toString() method of the paramater object when required. When you declare a String literal (or a String object) this is not done.

On the contrary, when a String is contatenated to another Object, the toString() method of that Object is called during the contatenation. You do not need to explicitly call toString() on that Object.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!