4 Replies Latest reply: Dec 24, 2010 1:41 PM by 806067 RSS

    String Concat doesn't work

      Hi All!

      I have the following code:
                      if (roundedWorstCompressFactor < 0.75 || roundedAvgCompressFactor < 0.75 || roundedBestCompressFactor < 0.75) {
                          String impossibleCFs = "";
                          if (roundedWorstCompressFactor < 0.75) impossibleCFs.concat("Worst Case");
                          if (roundedAvgCompressFactor < 0.75) impossibleCFs.concat(" Average Case");
                          if (roundedBestCompressFactor < 0.75) impossibleCFs.concat(" Worst Case");
                          jLabel23.setText("It isn't possible to achieve " +  impossibleCFs + " CFs");
      When I debugged my code, I realized that even the inner if statements becomes true, the concat method doesn't make any difference. Therefore, resultant jLabel's text becomes "It isn't possible to achieve CFs". Why concat method of String class doesn't work?
        • 1. Re: String Concat doesn't work
          Syed Ullah
          When you apply the concat function on a string, it does not change the original string, it returns a new string with the desired result. So you have to assing the returned value to your variable. So, try this:
             impossibleCFs = impossibleCFs.concat("Worst Case");
          As an alternative, also look into the StringBuffer data type. It has the append() function that you can use without assigning the result back to the original variable. Once you are done, you can use StringBuffer.toString() to get the final String.
          • 2. Re: String Concat doesn't work
            • 3. Re: String Concat doesn't work
              String.concat has been around since Java 1.0. Did you really think you were the first one to discover a bug in it? Thats what your title suggests. ;)

              String is immutable so you cannot change it only return another String with the results.
              In your case you would be better off using String Builder or a plain expression.
              jLabel23.setText("It isn't possible to achieve" +  
                  (roundedWorstCompressFactor < 0.75 ? " Worst Case" : "") +
                  (roundedAvgCompressFactor < 0.75 ? " Average Case" : "") +
                  (roundedBestCompressFactor < 0.75 ?  " Best Compress" : "") + " CFs");
              Shouldn't the last string be "Best Compress"
              • 4. Re: String Concat doesn't work
                Yes! Title was a little bit similar to the today's commercial ads on the TV, next time I will try something ordinary. Thanks for the nice snippet, I was thinking about the blank spaces in between.