# String.length() returns strange results

Michael Graf

Greenhorn

Posts: 1

posted 6 years ago

- 0

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!

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.

posted 6 years ago

- 0

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

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 |