Solved

String Concat vs. +

Posted on 1998-11-15
1
336 Views
Last Modified: 2011-09-20

What is the difference between the concat() method in String and the '+' operator for the String?  I thought they were the same, but when I try to "build" a string by concatening (using the concat method) strings to an initially empty string, I appear to get nothing, whereas if I do it via '+' (or in this case '+=') it turns out ok.  
Here is the sample code:

String processedString = "";
String workingString = myTextArea.getText();
int stringLength = workingString.length();

     for (int i = 0; i < stringLength; i++){
        if (workingString.charAt(i) == '\n'){
                processedString += "\r\n";
                // Or processedString.concat("\r\n");
            }
            else{
                processedString += workingString.charAt(i);
                // Or processedString.concat("" + workingString.charAt(i));
            }
        }
    }

Thanks for shedding any light on this!


ap9
0
Comment
Question by:ap9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 4

Accepted Solution

by:
martinag earned 50 total points
ID: 1227491
The concat() function doesn't change the string's value, it just returns a new String object.

processedString = processedString.concat("" + workingString.charAt(i));
should work for you.

Martin
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question