String.concat() vs + operator in strings concatenations

Whats the difference between String.concat() and + operator in strings concatenation?
I cant find any functional one.
Are there any performance differences?
Thanks

TM-Nite wrote:
Whats the difference between String.concat() and + operator in strings concatenation?
I cant find any functional one.There isn't any for all one can tell from the API docs. More details would be up to the String implementation.
Are there any performance differences?No. Both are bad if repeated a lot, as long as there aren't exclusively compile-time constants involved. Use StringBuilder/StringBuffer instead, in those cases.

Similar Messages

  • Why only +String concatation for Operator Overloading ?

    Java does not support operator overloading other than the + operator for addition of two Strings or a number and a String.Why only the + operator and Strings, even when we have a concat() for addition of Strings ?
    Wondering if anyone could provide me some link as to why this only this (+) operator was chosen.
    Thank you for your consideration.
    Edited by: amtidumpti on Apr 27, 2009 6:40 AM
    Edited by: amtidumpti on Apr 27, 2009 6:40 AM

    amtidumpti wrote:
    stevejluke wrote:
    amtidumpti wrote:
    Java does not support operator overloading other than the + operator for addition of two Strings or a number and a String.Why only the + operator and Strings, even when we have a concat() for addition of Strings ? I assume the + was implemented (even with the concat() method present) for simplicity with working with Strings. Why only +? What other operators make sense as String manipulation operators? Why are they useful?We already have String,StringBuilder,StringBuffer for simplicity and manipulations of Strings or may be they were added later,but even then we have this +.Right, and you can use those methods instead of +. But String is a much-used class, has several special attributes given to it, and the + is very self-explanatory when applied to Strings.
    Also would == qualify as the other operator for operator overloading in java ?== has no special meaning for Strings (or really for Objects at all). It has exactly one purpose, to compare the value of the operands provided. When the operands are primitives, it compares their values exactly as you or I would (if the primitive values are equal you get true). When the operands are reference types the value of the references are tested for equality (if they don't hold a reference to the same Object, then == returns false).
    >
    int iAge1=0,iAge2=0;
    String sName1="Java",sName2="Rocks";
    double dMark1=89.02,dMark2=92.0;
    if(iAge1==iAge2)
    System.out.println("HURRAH");
    if(sName1==sName2)
    System.out.println("HURRAH");
    if(dMark1==dMark2)
    System.out.println("HURRAH");Also in case of boolean :
    boolean bFlag1=false,bFlag2=true;
    if(bFlag1=bFlag2)
    System.out.println("Value Assignment done");Here is " = " working not only as a assignment operator as well as conditional operator ?
    Thanks for your consideration.

  • String concat PROBLEM??? Please Help

    I have this strange Question regarding String concat
    If I say:
    String str = "Welcome";
    str.concat(" to Java");
    System.out.println(str);
    The output is: Welcome.
    How do I get the output to Welcome to Java??

    I have this strange Question regarding String concat
    If I say:
    String str = "Welcome";
    str.concat(" to Java");
    System.out.println(str);
    The output is: Welcome.
    How do I get the output to Welcome to Java??
    The problem is that String is immutable, The String you have held in str does not change, rather a new Srtring is returned. So all yo have to do is grab the new String
    str = str.concat("to Java");
    or use the new String without keeping it.
    ie
    System.out.println(str.concat("to Java"));

  • String.  Relational operator and odd printing

    Hi,
    I'm wondering if someone could help me with this puzzlement I have. I've search the forum and I search the tutorial with "string and relation operator" and "string and compare" but I couldn't find any answer.
    Basically, I want to make sure that we can't use "<", ">", ">=", and "<=" between two strings because I got compiler error. Tutorial only says to use equals() method but I can't find anything that says "Don't use relational operator such as... !"
    Another question I have is I have this test code just to know String more.
    <code>
    public class Test {
    static void compare (String s1, String s2) {
    System.out.println ("s1 is = " + s1);
    System.out.println ("s2 is = " + s2);
    System.out.println (s1 + " == " + s2 + s1==s2); //this line prints "false"
    System.out.println (s1 + " != " + s2 + s1!=s2); //this line prints "true"
    System.out.println ("s1.equals(s2): " + s1.equals(s2));
    public static void main (String args[]) {
    compare ("Hello", "huhaha");
    compare ("Hello", "hello");
    compare ("Hello", "Hello");
    </code>
    I'm wondering why the line that I commented prints "false" and "true" where I expected to print the value of s1 which is "Hello" and s2 which is "huhaha"?
    Sorry if the question seems stupid. I do admit I'm a little slow.
    Thank you!

    This question is asked all the time on this forum.
    Basically, the "==" operator between any two Objects (Strings included) is comparing instances. That is, are the two Objects references to the same "real" instance? If so, it will return true. However, just because two Strings contain the same value does not mean they are the exact same instance. So two different strings which contain the value "XXX" could still have "==" return false. For this reason, it is recommended that (in general) you use "==" and "!=" as it relates to Objects only when comparing them to null (there is only one null).
    Instead, use the "equals()" method. There are no "<", "<=", ">", or ">=" operators in relation to Objects. Instead, use the Object's compare() method, if available (which it is for Strings).

  • String concat problem

    Hi folks,-
    i know this question might be very simple but i just cannot see what i am doing wrong here.
    String stringA, stringB, stringC;
    stringA= new String();
    stringB= new String();
    stringC= new String();
    stringA = null;
    stringB = "TRUE";
    stringC = "Error:";
    stringA.concat(stringB); // my code stops and quits here w/o error
    // other codewhat is wrong here?
    thanks much

    could you then please explain the following?
    public String concat(String str)Concatenates the
    specified string to the end of this string.
    If the length of the argument string is 0, thenthis
    String object is returned. Otherwise, a new String
    object is created, representing a charactersequence
    that is the concatenation of the charactersequence
    represented by this String object and thecharacter
    sequence represented by the argument string.
    Examples:
    "cares".concat("s") returns "caress"
    "to".concat("get").concat("her") returns"together"
    Parameters:
    tr - the String that is concatenated to the end of
    this String.
    Returns:
    a string that represents the concatenation of this
    object's characters followed by the stringargument's
    characters.
    Throws:
    NullPointerException - if str is null.It returns a new String, which you are
    throwing away. Change your code like this:
    stringA = stringA.concat(stringB);
    and then you'd get somewhere.yes, it makes sense but the description does not say this.
    i think that will work but my problem is with the description of this
    concat operation on the java web site.
    thanks for the help

  • Removing characters from a String (concats, substrings, etc)

    This has got me pretty stumped.
    I'm creating a class which takes in a string and then returns the string without vowels and without even numbers. Vowels and even characters are considered "invalid." As an example:
    Input: "hello 123"
    Output: "hll 13"
    The output is the "valid" form of the string.
    Within my class, I have various methods set up, one of which determines if a particular character is "valid" or not, and it is working fine. My problem is that I can't figure out how to essentially "erase" the invalid characters from the string. I have been trying to work with substrings and the concat method, but I can't seem to get it to do what I want. I either get an OutOfBoundsException throw, or I get a cut-up string that just isn't quite right. One time I got the method to work with "hello" (it returned "hll") but when I modified the string the method stopped working again.
    Here's what I have at the moment. It doesn't work properly for all strings, but it should give you an idea of where i'm going with it.
    public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         }So does anybody have any advice for me or know how I can get this to work?
    Thanks a lot.

    Thansk for the suggestions so far, but i'm not sure how to implement some of them into my program. I probably wasn't specific enough about what all I have.
    I have two classes. One is NoVowelNoEven which contains the code for handling the string. The other is simply a test class, which has my main() method, used for running the program.
    Here's my class and what's involved:
    public class NoVowelNoEven {
    //data fields
         private String str;
    //constructors
         NoVowelNoEven(){
              str="hello";
         NoVowelNoEven(String string){
              str=string;
    //methods
         public String getOriginal(){
              return str;
         public String getValidString(){
              String valid = str;
              int start = 0;
              for(int i=0; i<=valid.length()-1; i++){
                   if(isValid(valid.charAt(i))==false){
                             String sub1 = valid.substring(start, i);
                             while(isValid(valid.charAt(i))==false)
                                  i++;
                             start=i;
                             String sub2 = valid.substring(i, valid.length()-1);
                             valid = sub1.concat(sub2);
              return valid;
         public static int countValidChar(String string){
              int valid=string.length();
              for(int i=0; i<=string.length()-1; i++){
                   if(isNumber(string.charAt(i))==false){
                        if((upperVowel(string.charAt(i))==true)||lowerVowel(string.charAt(i))){
                             valid--;}
                   else if(even(string.charAt(i))==true)
                        valid--;
              return valid;
         private static boolean even(char num){
              boolean even=false;
              int test=(int)num-48;
              if(test%2==0)
                   even=true;
              return even;
         private static boolean isNumber(char chara){
              boolean number=false;
              for(int i=0; i<=9; i++){
                   if((int)chara-48==i){
                        number=true;
              return number;
         private static boolean isValid(char chara){
              boolean valid=true;
              if(isNumber(chara)==true){
                   if(even(chara)==true)
                        valid=false;
              if((upperVowel(chara)==true)||(lowerVowel(chara)==true))
                   valid=false;
              return valid;
    }So in my test class i'd have something like this:
    public class test {
    public static void main(String[] args){
         NoVowelNoEven test1 = new NoVowelNoEven();
         NoVowelNoEven test2 = new NoVowelNoEven("hello 123");
         System.out.println(test1.getOriginal());
         //This prints hello   (default constructor string is "hello")
         System.out.println(test1.countValidChar(test1.getOriginal()));
         //This prints 3
         System.out.println(test1.getValidString());
         //This SHOULD print hll
    }

  • Using OR operator with string

    How we can use OR operator with string in java??

    Gaurav1 wrote:
    its logical OR operator;how can we use it with matcher classLike its been said already. The "logical OR" is used the same everywhere.
    Why don't you post the code you're having problems with. (Only the relevant areas, please. And use code tags.)

  • [svn:bz-trunk] 18053: BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo. java

    Revision: 18053
    Revision: 18053
    Author:   [email protected]
    Date:     2010-10-07 03:27:37 -0700 (Thu, 07 Oct 2010)
    Log Message:
    BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo.java
    Updated the code to use the right operator.
    Check-in Tests: PASS
    QA: Yes
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-571
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/VersionInfo.java

  • Why not use "new" operator  with strings

    why we not use new when declaring a String .because in java String are treated as objects. we use new operator for creating an object in java .
    and same problem wiht array when we declare array as well as initialize .here we are alse not using new for array
    why

    Strings aren't just treated as objects, Strings are Objects.
    As for why not using new for Strings, you can, if you want.:
    String str = "this is a string";
    and
    String str = new String("this is a string");
    do the same thing (nitty-gritty low level details about literals aside). Use whatever you like, but isn't it simpler not to type new String(...) since you still need to type the actual string?
    As for arrays, you can use new:
    int[] ints = new int[10];
    or
    int[] ints = { 0, 1, 2, 3, ..., 9 };
    But the difference here is you are creating an empty array in the first one, the second creates and fills the array with the specified values. But which to you often depends on what you are doing.

  • Formula string with boolean operations

    Hello all,
    I created sample logic to do Boolean operations with string.
    Example:
    (True or false) && False = false
    False && True || false = false
    Note: Syntax should not be any error (like wrong brackets/extra and/or.
    Can anyone tell me is these is any way to optimize this code?
    Munna
    Attachments:
    Formula String to Boolean operations.zip ‏30 KB

    I figure there has to be a way to get to a formula node by way of scripting.  So I started playing around.
    See this.
    Now this is just a VI that is basically operating on itself and shows the classes and properties do exist.
    I think for your situation, you would need to dynamically create a new subVI.  Run scripting code to generate a formula node, the inputs and output node to the formula, controls and indicators to link to those nodes along with the wiring connections.  Then place the formula expression into the formula.  Then dynamically call the VI (may need to save it first) to send it your values and return the output.
    It seems like it would be a lot of work, but certainly doable.
    Attachments:
    Example_VI.png ‏34 KB

  • Use Operator == for String Comparison

    Hi,
    I would like to know more about the impact of using operator == in String Comparison.
    From the reference I get, it state this :
    "Operator (==) compares two object addresses to see whether it refers to the same object."
    I've tested it with 2 codes as below :
    Code 1:
              String Pass1 = "cosmo";
              String Pass2 = "cosmo";          
    if (Pass1==Pass2)
                   System.out.println("1&2:same");
              else
                   System.out.println("1&2:not same");
    Output : 1&2:same
    Code 2:
              String Pass3 = new String("cosmo");
              String Pass4 = new String("cosmo");
              if (Pass3==Pass4)
                   System.out.println("3&4:same");
              else
                   System.out.println("3&4:not same");
    Output : 3&4:not same
    Can anyone kindly explain why is the result so? If operator == compares the addresses, isn't it that the 1st code should also have the output :"1&2:not same".

    Can anyone kindly explain why is the result so?It's an implementation artifact. Strings are pooled internally and because of that any String literal will be represented by exactly one object reference.
    Knowledge of this shouldn't be utilized though. It's safer to follow the basic rule: Use == to compare object references and equals to compare object values, such as String literals.

  • *****Assignment Operator Question - String Operations*****

    There's a lot of code here, but my question pertains to the italicized portion. I am assigning one StringObject to another. But when the assignment is tested with a System.out.println in the TestStringObject class, it doesn't look like the assignment has occurred properly. Even thought the string is reversed with the myObj.reverse() method, when the object is printed to the screen, it does not appear to be reversed. Is there really a problem with the way the assignment is occurring or am I misunderstanding the way assignment occurs in Java. By the way, the TestStringObject class must stay as is, but the StringObject code can be modified. Thanks!
    class TestStringObject{
       public static void main(String [] args){
          StringObject myObj, yourObj;
          myObj = new StringObject("Hello-World!!! Java/is/awesome.");
          yourObj = new StringObject("a man a plan a canal panama");
          myObj.stripCharacters("-!/.");
          myObj.displayStringObject();
          System.out.println();
          myObj.reverse();
          myObj.displayStringObject();
          System.out.println();
          yourObj.stripCharacters(" ");
          System.out.print("yourObj = ");
          yourObj.displayStringObject();
          System.out.println();
    myObj = new StringObject(yourObj.getStore());
    myObj.reverse();
    System.out.print("myObj = ");
    myObj.displayStringObject();
    System.out.println();
    if(myObj.equals(yourObj))
    System.out.println("they are equal");
    else
    System.out.println("they are not equal");
    import java.lang.String.*;
    class StringObject{
       private String store;
       private int storeLength;
       public StringObject(String s){
       //Creates a new StringObject by saving the string s in
       //the instance variable store and its length in
       //the instance variable storeLength.
       store = new String(s);
       storeLength = store.length();
       public void displayStringObject(){
       //Display the instance variable store.
       System.out.println(store);
       public void reverse(){
       //Updates store to hold the reverse of its contents.
       String reverseString = new String();
       char reverseLetter;
       for (int z = storeLength - 1; z > -1; --z){
           reverseLetter = store.charAt(z);
           reverseString = reverseString + reverseLetter;
       store = reverseString;
       public void stripCharacters(String stg){
       //Update store to hold its contents after each of the
       //characters in stg has been removed.
       int tempLength = stg.length();
       char newChar;
       for (int i = 0; i < tempLength; i++){
           newChar = stg.charAt(i);
           stripACharacter(newChar);
           storeLength = store.length();
       public boolean equals(StringObject sObj){ 
       //Determines if the store in sObj is identical to
       //the store in the receiver without regard to case.
       String newStore = sObj.store;
       if (newStore.equalsIgnoreCase(store))
          return true;
       else
          return false;  
       public String getStore(){
       //Return the store to the caller.
       return store;
       private void stripACharacter(char ch){
       //Update store to contain its contents after every occurrence
       //of character ch has been removed.
       String testString = new String();
       char letter;
       for (int x = 0; x < storeLength; x++){
           letter = store.charAt(x);
           if (letter != ch){
              testString = testString + letter;
       store = testString;
    The Output:
    D:\CMU>java TestStringObject
    HelloWorld Javaisawesome
    emosewasiavaJ dlroWolleH
    yourObj = amanaplanacanalpanama
    myObj = amanaplanacanalpanama
    they are equal

    It looks to me like your output is correct. What were you expecting when you compared a palindrome to its reverse?
    I changed it to something that is not the same in both directions and got this output, which is also correct:HelloWorld Javaisawesome
    emosewasiavaJ dlroWolleH
    yourObj = abcdefg
    myObj = gfedcba
    they are not equal

  • Output strings from loop into one string

    im trying my best to explain my problem so ber in mind:)
    hey having a bit of trouble with outputing strings from loop
    example
    i typed ab into the textbox
    the output should be 12
    but since it is in a loop it would only output the last string and in this case is 2
    im trying to get both strings from the loop and output strings from loop into one string.
    here is some of my code to understand my problem
    // characters a to f
         char[] charword = {'a','b','c','d','e','f'};
         String charchange ;
      // get text from password textbox
                          stringpassword = passwordTextbox.getText();
                          try {
                          // loop to show password length
                          for ( int i = 0; i < stringpassword.length(); i++ ){
                          // loop to go through alfabet     
                          for (int it = 0; it < charword.length; it++){
                             // if char equals stringwords
                               if (stringpassword.charAt(i) == charword[it]){
                                    System.out.print("it worked");
                                    // change characters start with a
                                    if (charword[it] == 'a'){
                                         charchange = "1";
                                    // change to 2
                                    if (charword[it] == 'b'){
                                         charchange = "2";
                                        }

    Not sure how you are displaying the result but you could display each value as soon as you find it.
    if (charword[it] == 'a'){
        System.out.print("1");
    }If it is in a text field then use append. Or if you really need a String with the entire result then use concatenation.
    if (charword[it] == 'a'){
        charchange += "1";
    }

  • How many java String objects are created in string literal pool by executin

    How many java String objects are created in string literal pool by executing following five lines of code.
    String str = "Java";
    str = str.concat(" Beans ");
    str = str.trim();
    String str1 = "abc";
    String str2 = new String("abc").intern();
    Kindly explain thanks in advance
    Senthil

    virtuoso. wrote:
    jverd wrote:
    In Java all instances are kept on the heap. The "String literal pool" is no exception. It doesn't hold instances. It holds references to String objects on the heap.Um, no.
    The literal pool is part of the heap, and it holds String instances.
    [http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#22972]
    [http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html#67960]
    You're referring to the JVM. That's not Java.It's part of Java.
    There is nowhere in Java where it is correct to say "The string literal pool holds references, not String objects."

  • String objects with the same string pointing to the same place but?

    Hi,
    Here is a simple sample
    String str1 = "a";
    String str2 = "a";I understand that in Java str1 and str2 pointing to the same place in memory and Java compiler wouldn't save the string "a" in two different places in memory. Am I right?
    If so, if the value of str1 changes to something else as following:
    String str1 = "a";
    String str2 = "a";
    str1 = "b";why str2 which has been pointing to the same place as str1 before is still containing ?a? and not ?b????
    Thanks!

    Maria1990 wrote:
    Hi,
    Here is a simple sample
    String str1 = "a";
    String str2 = "a";I understand that in Java str1 and str2 pointing to the same place in memory and Java compiler wouldn't save the string "a" in two different places in memory. Am I right?Correct.
    Maria1990 wrote:
    If so, if the value of str1 changes to something else as following:
    String str1 = "a";
    String str2 = "a";
    str1 = "b";why str2 which has been pointing to the same place as str1 before is still containing ?a? and not ?b????Because str2 is pointing to the same "a", but it is not pointing to str1.
    This is what happens:
    String str1 = "a";
    /*                 +---+
             str1 ---->| a |
                       +---+
    String str2 = "a";
    /*                 +---+
             str1 --+->| a |
                    |  +---+
                    |
             str2 --+
    NOT:
                       +---+
         +-> str1 ---->| a |
         |             +---+
         |
         +- str2
    str1 = "b";
                       +---+
                 +---->| b |
                 |     +---+
                 |
                 |     +---+
            str1-+  +->| a |
                    |  +---+
                    |
             str2 --+
    */

Maybe you are looking for

  • Creating Custom Mobile Application with CRM

    Hi , After reading some staff about the CRM Mobile client solutions , I have not figure it out weather I can create my own mobile applications  using the CRM Mobile Technology . I know that the mobile clients need CRM Middleware server for synchoniza

  • ITunes will not install correctly on my PC with Windows 8.  Any hints?

    iTunes will not install correctly on my PC with Windows 8.  Any hints? The error message reads: iTunes.exe - Entry Point Not Found The procedure entry point ADiAdlD_AcquireMatchSlotIfNecessary could not be located in ghe dynamic link library C:\Progr

  • What kind of cellular plan do you need for iPod Touch?

    I'm thinking of replacing my Classic with a Touch. What kind of cellular service lan do I need?

  • Manual payment advice

    Dear all My client requirement is to take manual payment advice for partial cleated invoices and fully cleared invoices so I tried by correspondence I have done the following steps 1. Post invoice---FB60 2. Make out going payment by F-53 3. Requested

  • Duke's Bookstore - bugs in tutorial

    Hello Friends, I've installed the latest J2EE 1.4 tutorial, and tried to compile Duke's Bookstore example. I got many errors - references to classes that don't exist. For example, database.BookDetails - the class is not in database package. The only