Use StringBuffer instead of String, this will solve your problem.
public static void main(String[] args) { StringBuffer s = new StringBuffer("Hello"); changeString(s); String res = s.toString();
Or, if you really need to use only String, so here is a solution using reflection:
public static void main(String[] args) { String s = "Hello"; changeString(s); String res = s; //res = "HelloWorld" } private static void changeString(String s){ char[] result = (s+"World").toCharArray(); try { Field field = s.getClass().getDeclaredField("value"); field.setAccessible(true); field.set(s, result); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); } }
source share