• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String.length() returns strange results

 
Michael Graf
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain this to me:

testWithBraces is OK, testWithoutBraces fails due to
junit.framework.AssertionFailedError: expected:<1> but was:<3>


 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Michael and welcome to Javaranch!

The answer here is due to the order of operations, in the 2nd case the "".length() is executed first (which == 0) and then the month + 0 is executed, month is 3 so 3 + 0 == 3.

Hope that made sense!
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Case 1 -

int month = 3;
int length = (month+"").length();

Evaluates as
a. length = (month+"").length();
b. length = (3+"").length();
c. length = ("3").length(); //Gets the length of the String "3"
d. length = 1

Case 2 -

int month = 3;
int length = month+"".length();

Evaluates as
a. length = month+"".length();
b. length = 3+"".length();
c. length = 3 + 0 //Gets the length of the String "" which is 0
d. length = 3
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic