Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

String Concat vs. +

Posted on 1998-11-15
1
Medium Priority
?
340 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 200 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

963 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