• Post Reply Bookmark Topic Watch Topic
  • New Topic

Struggling to understand the logic behind this single line of code  RSS feed

 
Johnny Dey
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am following a book intended for beginner in Java and it has a short piece of code explaining the array nature of string.
The code is the following:



this program reverses the chars inside the string. I am having trouble with this line of code


how does this effectively reverses the chars inside string so that the text "Mississippi" becomes "ippississiM"? Why is the result variable being added twice? please help me understand the logic, thanks in advance.
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java you can uses the "+" operator to denote concatenation, overloading the + operator, so what is actually happening there is your string is being accessed and the reverse if being built by adding the sequential character contained in the string to the front of a result, so you get something along this line:
Mississippi
then with each pass your result grows:
M
iM
siM
ssiM
issiM
sissiM
ssissiM
ississiM
pississiM
ppississiM
ippississiM

it's a neat little trick to reverse the String.

You can actually see it happen in the output if you put a well placed println in your code.

 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is the result variable being added twice?

It isn't, really. Here's how I would "say" the code below:

Set the variable result to the character in the variable text at index i plus what's already in the variable result.

Since the right side of the expression is evaluated first, you can use the variable that's getting set. The rightmost result has the value before the assignment and the leftmost result gets the value of the assignment. You see this sort of thing a lot when totalling:

It's so common that Java has a shortcut for it:


 
Bill foster
Ranch Hand
Posts: 66
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I like the string explanation, trying to use the += is not the same as trying to concatenate a string( result=text.charAt(i)+result).

For one thing the += is working with primitives on another the + concatenation in the code above is working with string objects.

Please be sure to recognize the difference, I had a student come up with code similar to this and he was confused.
I was confused because I did not know anything about this subject until I started programming.

Being a math teacher, you can trace the code on paper and also read the API when in doubt in dealing with methods.
The API has a boat load of information on methods dealing with strings

I'm I correct???

Take care have a great weekend!

Bill
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:In Java you can uses the "+" operator to denote concatenation, . . .
But repeated use of + on Strings in a loop can cause poor performance. I would suggest you create a StringBuilder object and use its methods instead of +.
 
Bill foster
Ranch Hand
Posts: 66
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah Richie is right!!

There is a StringBuffer reverse() method, but since the code has one method (if you want to create enterprise app I would not do it this way) I guess you can use the concatenation, and I think the OP said the code was from a book. My guess is the OP is a first year student, and the performance issue will not be address until C.S.II (algorithms study).

I think the author of the book wanted the student to use strings without creating an object out-right, some text books try to show the student a basic version and go over the steps to solve it, just like a math text book.
This is call onion layered teaching: first to teach the simple version then you go down a layer to the meat of the topic and add details.


However if you are using multi threads the StringBuffer is not safe for multi thread(synchronization, says in the API).

Bill
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because String is immutable, so you are not building a String each time you do a String + String, you are making a new String and the old String object(s) are dereferenced, orphaned, and will add into the GC.
Campbell Ritchie wrote:
Les Morgan wrote:In Java you can uses the "+" operator to denote concatenation, . . .
But repeated use of + on Strings in a loop can cause poor performance. I would suggest you create a StringBuilder object and use its methods instead of +.
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"+=" is overloaded as well.

In this specific case they need to use the String = char + String so the result can grow in the appropriate order.

Bill foster wrote:Actually I like the string explanation, trying to use the += is not the same as trying to concatenate a string( result=text.charAt(i)+result).

For one thing the += is working with primitives on another the + concatenation in the code above is working with string objects.

Please be sure to recognize the difference, I had a student come up with code similar to this and he was confused.
I was confused because I did not know anything about this subject until I started programming.

Being a math teacher, you can trace the code on paper and also read the API when in doubt in dealing with methods.
The API has a boat load of information on methods dealing with strings

I'm I correct???

Take care have a great weekend!

Bill
 
Bill foster
Ranch Hand
Posts: 66
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Les,

I did not know that! Does the garbage collector reclaims the memory when the objects are not referenced right?
This happens on the assignment of a new String, I'm guessing.

thanks,

Bill
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the garbage collector marks the items for disposal and then when it gets good and ready, then it will free up the memory. That has been an ongoing discussion and point of refactoring in the JVM for decades now.

When an object is dereferenced, then it will be "collected" and if you so desire you can at any point in your code request the GC to run, but in actuality, it will do it when it is ready to do so.

Just for an example:
When you have
you actually are saying

What used to be reference by string1, on the right hand side of the = operator, is orphaned, and as such, will be "collected" by the GC.

Bill foster wrote:Thanks Les,

I did not know that! Does the garbage collector reclaims the memory when the objects are not referenced right?
This happens on the assignment of a new String, I'm guessing.

thanks,

Bill
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:. . . the old String object(s) are dereferenced, orphaned, and will add into the GC. . . .
And when I try that sort of trick, about 10000 additions make the catenation slow enough that I can see the delay; if I ever tried 1000000 catenations I could make a cup of coffee and probably drink it too before the process finishes.

The best performance comes from a StringBulder (not StringBuffer: since it is a local variable there is no need for synchronisation) which has its capacity set by a constructor argument. I think you will also get better performance if you start with the i and loop through the String backwards.
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill foster wrote:Actually I like the string explanation, trying to use the += is not the same as trying to concatenate a string( result=text.charAt(i)+result).

For one thing the += is working with primitives on another the + concatenation in the code above is working with string objects.

Please be sure to recognize the difference, . . .
I am afraid that is incorrect. The Java® Language Specification (=JLS) says that operands of the String catentaion operator (which looks like +) are converted to Strings; the char on the left is converted to a String as if by new Character(c).toString() before the catenation is carried out. The += operator works like this:-
That second JLS page wrote:E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2))
So s += c; is equivalent to
s = (String)(c + s);
where c is a char and s1 a String. Therefore the char is converted to a String before the catenation is carried out, and there is no difference in the types.
 
Bill foster
Ranch Hand
Posts: 66
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ritchie for the explanation I thought using += to concatenate strings was not an option, in the first example it was used in variables that were assumed to be numbers like this:






Sorry for getting the string classes(String buffer/builder) mixed up!

Thanks for pointing this out!

Bill
 
Fred Kleinschmidt
Bartender
Posts: 572
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might be easier to understand if you split the line into two lines:

We start with result="".
Then we create a new string by taking the first character of text and append 'result' to that (to get just the first character, since result is currently empty).
Then result is set to be that new string.

Next time through the loop, we create a new string by taking the next character of text and appending 'result' to that. So the new string is now the second character followed by the first character. We then set result to that new string.

Next time through we make a new string consisting of the third character of text and appending 'result', so that news string is now the third character followed by (second character followed by first).

this continues for the entire text, with the last time through the loop making a new string consisting of the last character followed by the previous text inversion. that is the n assigned to 'result'.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!