I know Java methods are always pass by value, but I found this code that when you pass JSONObject into this method and modify that object inside the method, it remains modified when the method comes back.
This method is used to replace some value of json object, and it is working fine.
Can someone explain how this happens when Java is pass by value?
public static void setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym))) {
js1.put(key, valueNew);
return;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
}
}
return;
}
This is how you can call it
public static void main(String[] args) throws JSONException {
String text="{\"a\": { \"b\": { \"c\": \"x\", \"d\": \"y\" }}}";
JSONObject json = new JSONObject(text);
setProperty(json,"a.b.d","************");
System.out.println(json.toString(4));
}