concat() and + operator when linking strings

Asked 2 years ago, Updated 2 years ago, 118 views

If you have the string a, b in Java, you can connect it

a+=b
a.concat(b)

There's a way like this. Are these two the same? I have the code for the concat method, but there is no code for + operator. Please show me the code if possible. And I want to know how the + operator works.

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    } } else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

string java

2022-09-22 22:29

1 Answers

The concat method and + operator are not the same. For the first reason, if you do a.concat(b) when a is null, you will face a null PointerException. But a+=b; works well even if a is null. Also, the concat method only allows the String value + operator is available if the factor can be converted to String.

So the concat method is more restrictive than the + operator.


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.