Firstly, you cannot do it1, since a String
is immutable in java.
However, you can create a new String object with the desired value, using the String#substring() method (for example):
String s = "123456789";
String newString = s.substring(0, 3) + "foobar" + s.substring(3+3);
System.out.println(newString);
If you do want to achieve it efficiently, you could avoid creating some intermediate strings used by the concatinating and substring()
method.
String s = "123456789";
StringBuilder sb = new StringBuilder();
char[] buff = s.toCharArray();
sb.append(buff , 0, 3).append("foobar");
sb.append(buff,3+3,buff.length -(3+3));
System.out.println(sb.toString());
However, if it is not done in a very tight loop - you should probably ignore it, and stick with the first and more readable solution.
(1) not easily anyway, it can be done with reflection - but it should be avoided.