This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String.length() returns strange results Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String.length() returns strange results" Watch "String.length() returns strange results" New topic

String.length() returns strange results

Michael Graf

Joined: Mar 03, 2009
Posts: 1
Can someone explain this to me:

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

Martijn Verburg

Joined: Jun 24, 2003
Posts: 3275

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!

Cheers, Martijn - Blog,
Twitter, PCGen, Ikasan, My The Well-Grounded Java Developer book!,
My start-up.
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 606

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

Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
I agree. Here's the link:
subject: String.length() returns strange results