The Java Program: StringFest.java

  1 // StringFest.java -- examples of most of the methods of java.lang.String
  2 
  3 class StringFest {
  4 
  5    public static void pr (String x) { System.out.println (x); }
  6 
  7    public static void main (String[] args) {
  8 
  9       String str1 = "abc";
 10       String str2 = new String();
 11       String str3 = new String (str1);
 12       String str4 = str1;
 13       char data[] = {'a', 'b', 'c'};
 14       String str5 = new String (data);
 15       String str6 = str1.concat (str3);
 16       String str7 = str1 + str3;
 17 
 18       pr ("str1: " + str1);
 19       pr ("str2: " + str2);
 20       pr ("str3: " + str3);
 21       pr ("str4: " + str4);
 22       pr ("str5: " + str5);
 23       pr ("str6: " + str6);
 24       pr ("str7: " + str7);
 25 
 26       pr ("Length of str1: " + str1.length());
 27       pr ("Length of str2: " + str2.length());
 28       pr ("Length of str6: " + str6.length());
 29 
 30       pr ("Index of 'b' in str6: " + str6.indexOf('b'));
 31       pr ("Last index of 'b' in str6: " + str6.lastIndexOf('b'));
 32       pr ("The character at position 2 in str7: " + str7.charAt(2));
 33       pr ("The substring of str7 from position 2 to 4: " +
 34           str7.substring(2, 5));
 35 
 36       if (str1 == str4) {
 37          pr ("str1 and str4 refer to the same object.");
 38       }
 39       if (str1 != str3) {
 40          pr ("str1 and str3 do not refer to the same object.");
 41       }
 42       if (str1.equals(str5)) {
 43          pr ("str1 and str3 contain the same characters.");
 44       }
 45 
 46       int r1 = str1.compareTo ("abc and more");// negative (str1 shorter)
 47       int r2 = str1.compareTo ("azc");         // negative ('b' < 'z')
 48       int r3 = str1.compareTo ("abc");         // zero means equal
 49       int r4 = str1.compareTo ("aac");         // positive ('b' > 'a')
 50       int r5 = str1.compareTo ("ab");          // positive (str1 longer)
 51 
 52       boolean r6 = str1.equalsIgnoreCase ("AbC"); // true
 53       boolean r7 = str7.endsWith   ("bc");        // true
 54       boolean r8 = str7.startsWith ("ab");        // true
 55 
 56       String str8="\t \rThis is the string inside.\n \r";
 57       pr ("'" + str8.trim() + "'");
 58 
 59       pr ("A string in upper case: " + str7.toUpperCase());
 60       pr ("A string in lower case: " + "ABCAbC".toLowerCase());
 61    }
 62 
 63 }