File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String.length() returns strange results" Watch "String.length() returns strange results" New topic
Author

String.length() returns strange results

Michael Graf
Greenhorn

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
author
Bartender

Joined: Jun 24, 2003
Posts: 3274
    
    5

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: 605

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: http://aspose.com/file-tools
 
subject: String.length() returns strange results