title: Java String Mutability - java.lang.NoSuchFieldException: offset
body: <p>I'm new to Java and I saw a Q&amp;A section <a href="http://algs4.cs.princeton.edu/12oop/" rel="nofollow">here</a> with two examples where mutability is removed. Upon testing <a href="http://algs4.cs.princeton.edu/12oop/MutableString.java.html" rel="nofollow">MutableString.java</a>:</p>
  
  <pre><code>import java.lang.reflect.Field; 
  
  public class MutableString {
  
      public static void main(String[] args) { 
          String s = "Immutable"; 
          String t = "Notreally"; 
  
          mutate(s, t);
          StdOut.println(t); 
  
          // strings are interned so this doesn't even print "Immutable" (!)
          StdOut.println("Immutable");
      } 
  
      // change the first min(|s|, |t|) characters of s to t
      public static void mutate(String s, String t) {
          try {
              Field val = String.class.getDeclaredField("value"); 
              Field off = String.class.getDeclaredField("offset"); 
              val.setAccessible(true); 
              off.setAccessible(true); 
              int offset   = off.getInt(s); 
              char[] value = (char[]) val.get(s); 
              for (int i = 0; i &lt; Math.min(s.length(), t.length()); i++)
                  value[offset + i] = t.charAt(i); 
          } 
          catch (Exception e) { e.printStackTrace(); }
      } 
  
  } 
  </code></pre>
  
  <p>I received the following error:</p>
  
  <pre><code>java.lang.NoSuchFieldException: offset
  </code></pre>
  
  <p>Any input on the following would be greatly appreciated:</p>
  
  <blockquote>
    <p>a) why do I get this exception<br>
       b) how do I check which fields exist in a class (Java strings specifically)</p>
  </blockquote>