How do I concatenate two strings in Java?

前端 未结 23 3055
长情又很酷
长情又很酷 2020-11-22 04:47

I am trying to concatenate strings in Java. Why isn\'t this working?

public class StackOverflowTest {  
    public static void main(String args[]) {
                


        
相关标签:
23条回答
  • 2020-11-22 05:21

    For exact concatenation operation of two string please use:

    file_names = file_names.concat(file_names1);
    

    In your case use + instead of .

    0 讨论(0)
  • 2020-11-22 05:21

    So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.

    Different ways by which Strings could be concatenated in Java

    1. By using + operator (20 + "")
    2. By using concat method in String class
    3. Using StringBuffer
    4. By using StringBuilder

    Method 1:

    This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.

    String temp = "" + 200 + 'B';
    
    //This is translated internally into,
    
    new StringBuilder().append( "" ).append( 200 ).append('B').toString();
    

    Method 2:

    This is the inner concat method's implementation

    public String concat(String str) {
        int olen = str.length();
        if (olen == 0) {
            return this;
        }
        if (coder() == str.coder()) {
            byte[] val = this.value;
            byte[] oval = str.value;
            int len = val.length + oval.length;
            byte[] buf = Arrays.copyOf(val, len);
            System.arraycopy(oval, 0, buf, val.length, oval.length);
            return new String(buf, coder);
        }
        int len = length();
        byte[] buf = StringUTF16.newBytesFor(len + olen);
        getBytes(buf, 0, UTF16);
        str.getBytes(buf, len, UTF16);
        return new String(buf, UTF16);
    }

    This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.

    Method 3:

    This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.

        private int newCapacity(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = value.length >> coder;
            int newCapacity = (oldCapacity << 1) + 2;
            if (newCapacity - minCapacity < 0) {
                newCapacity = minCapacity;
            }
            int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
            return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
                ? hugeCapacity(minCapacity)
                : newCapacity;
        }
    
        private int hugeCapacity(int minCapacity) {
            int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
            int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
            if (UNSAFE_BOUND - minCapacity < 0) { // overflow
                throw new OutOfMemoryError();
            }
            return (minCapacity > SAFE_BOUND)
                ? minCapacity : SAFE_BOUND;
        }

    Method 4

    StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.

    In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.

    0 讨论(0)
  • 2020-11-22 05:22

    There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.

    Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.

    String first = "I eat";  String second = "all the rats."; 
    System.out.println(first+second);
    
    0 讨论(0)
  • 2020-11-22 05:23

    you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).

    0 讨论(0)
  • 2020-11-22 05:25

    In java concatenate symbol is "+". If you are trying to concatenate two or three strings while using jdbc then use this:

    String u = t1.getString();
    String v = t2.getString();
    String w = t3.getString();
    String X = u + "" + v + "" + w;
    st.setString(1, X);
    

    Here "" is used for space only.

    0 讨论(0)
提交回复
热议问题