The following simple Java program appears to display the string Hello World through the statement System.out.println("Hello World"); but it doesn’t. It simply replaces this with another string which is in this case, Good Day !! and displays it on the console. The string Hello World is not displayed at all. Let’s look at the following simple code snippet in Java.
package goodday;
import java.lang.reflect.Field;
final public class Main
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
static
{
try
{
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set("Hello World", value.get("Good Day !!"));
}
catch (Exception e)
{
throw new AssertionError(e);
}
}
}
Just one question about this code here. It works exactly as expected but I can not reduce the length of the string Good Day !!. If an attempt is made to do so, it causes a java.lang.ArrayIndexOutOfBoudsException. If the length is increased, the program runs well but the rest of the characters in the displaying string are truncated means that the length of the both of the strings should somewhat be the same. Why? This is the thing that I couldn’t understand.
The
valuefield is achar[]which internally stores the character array that the string uses as its backing store. Other fields indicate the initial offset into the character array, and the length of the string. (So to take a substring, it just creates a newStringobject which refers to the samechar[]but with a different starting offset and length.)If you modify those fields as well, you can do pretty much whatever you like with the string. Sample: