How does String works as Object in Java

I am quite confused with how Object works in Java since I run into this problem.

Let's say I have a function called checkDateValue (code looks like this)

private boolean checkDateValue(Date d1, String msg) {
    if (d1 == null) {
        msg = "d1 is null!";
        return false;
    }
    return true;
}

Here is the place I call this function:

String msg = null;
Date d1 = null;
if (!checkDateValue(d1, msg)) {
    system.println(msg); //msg is still null..... 
                         //what I need is the message generated in the function
}

As far as I know, if I put a customized Object (eg

myObj { private String msg;} 

) into a function, and we change the value of msg inside the function, when we get out of the function, the change of msg is kept. However, I think String is also considered as an Object in java. Why the change is not kept?


String is special, is immutable and is diffrent from normal Object. Java's String is designed to be in between a primitive and a class.

String is passed by value, but unfortunately every change on String make new value, so your old reference has old value.

I think this is good explanation: https://stackoverflow.com/a/1270782/516167


Java doesn't have "out" function arguments; they are copies of references. Even though you change msg in the function, it does not affect the caller's variable.


In Java, you cannot pass back a value to calling code by assigning to a method parameter. You are right that you can alter the internal structure of any parameter and that change will be seen in the calling code. However, assigning to a parameter is not the same thing as altering the internal structure. Also, a String is immutable—once created, its internal structure cannot be altered.

A common trick to do what you what is to use an array argument:

private boolean checkDateValue(Date d1, String[] msg) {
    if (d1 == null) {
        msg[0] = "d1 is null!";
        return false;
    }
    return true;
}

Then call it like this:

String[] msg = new String[1];
Date d1 = null;
if (!checkDateValue(d1, msg)) {
    system.println(msg[0]);
}
链接地址: http://www.djcxy.com/p/20892.html

上一篇: SWIG,我可以为从Java传递到C的char **分配一个值

下一篇: String如何在Java中作为Object使用