Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

What is this line doing?

 
Ranch Hand
Posts: 262
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in this method exercise

what is this line doing?



I understand that substring is creating another string from an existing string (in this case str)
but position, position + length

position, depending on the length of the string is either 1 or 2 (1 for odd, 2 for even)
i get that, but how is is picking the middle of the string from position to position + length?



 
Rancher
Posts: 4177
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As the code comment says, if the string is an even length then the middle of the String is two characters:
123456
The middle would be 34.

For an odd length the middle is a single character:
1234567 gives 4.

So the if statement has determined whether the String is even or odd, and set the value of position to the first character of the 'middle', and the length of the middle.
So position of 123456 would be 2, which represents the number 3 in the String as positions are 0-based, with a length of 2.

For 1234567 you would have a position of 3 (it's int division, so the 0.5 is lost), which is the position of the 4, with a length of 1.
 
wayne brandon
Ranch Hand
Posts: 262
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
right Dave, I wrote those comments and just needed to check if i was right, thanks!
 
My pie came with a little toothpic holding up this tiny ad:
Java Code Review and Psychology
https://coderanch.com/t/714798/java/Java-Code-Review-Psychology
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!