StringBuffer_1.java 2.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
// Test StringBuffer.replace(), reverse(), insert(String), append(String), 
// and delete().

public class StringBuffer_1
{
  public static void main(String args[])
  {
    StringBuffer sb = new StringBuffer("45");
    sb.insert(0, "123");
    sb.append("89");
    sb.insert(5, "6");
    sb.insert(6, '7');
    System.out.println (sb);
    
    sb.delete (3, 99);
    
    String foo = sb.toString();
    
    System.out.println (foo);
    sb.reverse();
    System.out.println (foo);

    System.out.println (sb);
    sb = new StringBuffer("1234");    
    System.out.println(sb.reverse());
    
    sb = new StringBuffer("123456789");
    sb.append ("0");
    System.out.println(sb);

    sb.replace (2, 99, "foo");
    System.out.println (sb);

    sb = new StringBuffer("123456789");
    sb.replace (1, 1, "XX");
    System.out.println (sb);

    sb = new StringBuffer("123456789");
    sb.replace (0, 2, "XX");
    System.out.println (sb);

    sb = new StringBuffer("123456789");
    sb.replace (5, 9, "54321");
    System.out.println (sb);

    sb = new StringBuffer("123456789");
    
    sb.delete (1,4);
    System.out.println (sb);    

    // Test bounds checks
    try
    {
      sb.insert (-2, "x");
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.insert (96, "x");
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.delete (-2, 2);
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.delete (96, 418);
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.delete (4, 2);
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.replace (-2, 2, "54321");
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.replace (4, 2, "54321");
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }

    try
    {
      sb.replace (12, 18, "54321");
    }
    catch (StringIndexOutOfBoundsException x)
    {
      System.out.println (x.getClass());
    }
  }
}