SoFunction
Updated on 2025-05-22

Implementation of Java parameter value transfer mechanism

A very classic question: Is it a parameter to enter Java method? Is it a value or an address?

The answer is: value passing.

Today I checked a production problem, and the database link resource was not closed.

The general code logic is as follows:

try{
    Preparestatement ps = null;
    String sql = "select * from tableA where id=?";
    (ps,sql);
}catch(Exception e){
    ("error:",e);
}finally{
    if(ps!=null){
        ();
    }
}

private void query(Preparestatement ps ,String sql){
    ps = ();
    ........//Unimportant query logic}

You can see that the object instance ps is passed to a private method: query(Preparentatement ps,String sql), and the value is assigned in the method. Then close the empty space outside the method.

It is obvious that the author of this code is not familiar with the value transfer mechanism of JAVA.Although ps is passed to the method to assign a value, the ps object outside the method is still null, so the code in the finally module does not execute close. It just looks like it will close the resources.

In fact, ps outside the method and ps inside the method are not the same object, or do not point to the same address.Java passes values ​​rather than addresses. This is the biggest difference from C language.

Java can modify the properties of an object in a method (such as ("myName")). This modification can affect objects outside the method, but it cannot reassign objects outside the method through the = sign (such as a=getNewObject())

This is the end of this article about the implementation of the Java parameter value transfer mechanism. For more related Java parameter value transfer content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!