File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Head First Android this week in the Android 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: 607

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
It's not a secret anymore!