title: Java Problem: creating a string from a sequence of bytes
body: <p>I came across the following program and its showing unexpected results.</p>
  
  <pre><code>public class StringFromByte
  {
         public static void main(String[] args)
         {
               byte bytes[] = new byte[256];
  
               for(int i = 0; i &lt; 256; i++)
                   bytes[i] = (byte)i;
  
               String str = new String(bytes);
               for(int i = 0, n = str.length(); i &lt; n; i++)
                   System.out.print((int)str.charAt(i) + " ");
         }
  }  
  </code></pre>
  
  <p>Technically this program should print the integers from 0 to 255 in order. But if you ran the program sometimes it shows this sequence (0 to 255) sometimes it shows some other sequence. Its behavior is unspecified. What's going on?</p>