Solved

String Concat vs. +

Posted on 1998-11-15
1
335 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
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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

730 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