// Strings.java Demo of String functionality public class Strings { public static void main (String args[]) throws Exception { // initialize via assignment vs. constructor String s1 = "Hello"; // assignment String s2 = new String( "World" ); // constructor String s3 = s1 + " " + s2; // s3 is now --> "Hello World; // .length method built into every String System.out.println("The length of s3 is: " + s3.length() ); // prints out 11 // .charAt method built into every String System.out.println("\nThe third letter in s3 is: " + s3.charAt(2) ); // 1st at [0] 2nd at [1] 3rd at [2] etc. // combine charAt and length to print the string backwards System.out.print( "\n" + s3 + " backwards is: "); for ( int i=s3.length()-1 ; i>=0 ; i--) System.out.print( s3.charAt(i) ); System.out.println(); // .indexOf method built into every String. Searches for letter. If not found returns -1 System.out.println("\nThe letter 'W' is at index: " + s3.indexOf('W') ); // prints 6 // boolean .startsWith method built into every String. Try out .endsWith() yourself if ( s3.startsWith("Hello") ) System.out.println("\nThe literal text \"Hello\" is a prefix of s3"); // boolean .equals() method built into every String. if ( s1.equals( s2 ) ) System.out.println("\n" + s1 + " is char by char identical with " + s2 ); else System.out.println( "\n" + s1 + " is NOT char by char identical with " + s2 ); // toUpperCase() method built into every String. Try out .toLowerCase() yourself System.out.println("\n" + s3 + " converted to all upperCase is " + s3.toUpperCase() ); System.out.println( "But calling .toUpperCase() does not modify s3.\nIt is still " + s3 ); // .substring() method built into every String. int fromInd=0,toInd=4; System.out.println( "\nThe first 4 chars of s3 are: " + s3.substring(fromInd,toInd) ); // only get 0..3 System.out.println( ".substring() does not modify s3." ); } // END MAIN } // END STRINGS CLASS