This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Gurus, I am trying to setString once and change the value of variable in side the setString. It doesn't work and I see it's preserving first value and not taking subsequent changes in the variable. Here is piece of code: PreparedStatement pstmt = conn.prepareStatement("insert into testtable ( ch ) values (?)");//line1 String st = new String("123");//line2 pstmt.setString(1, st );//line3 pstmt.executeUpdate();//line4 st = new String("456");//line5 pstmt.executeUpdate();//line6 After line6, I see my testtable has two rows, but with values "123" & "123" instead "123" & "456". If this expected behavior? Is there a way to setString once and then change variable and let this gets inserted in the database? Thanks in advance.
In Java, primatives and Strings are pass-by-value, not pass-by-reference. In line 3, you are assigning the value "123" to the prepared statement. In line 5, you are having st point to a new string. The prepared statement remembers that you passed it the value "123". It doesn't know or care that you happen to be pointing to something else now. Also, new String("456") doesn't buy you any more than "456" does.