public class StringsDemo1 { public static void main(String[] args) { String firstName = new String("John"); // Strings are rarely instantiated this way String lastName = "Doe"; // since Java allows you to shorten it to this way String middleName; // middleName is null since it was not initialized System.out.println("The length of " + firstName + " is " + firstName.length()); // System.out.println("The length of " + middleName + " is " + middleName.length()); // error since middleName is null middleName = ""; System.out.println("The length of " + middleName + " is " + middleName.length()); // okay since middleName is the null string // null is different from a null string similar to how zero is different from the empty set in math int zip = 19610; zip = zip + 1; System.out.println("zip is " + zip); // zip is 19611 String zipCode = zip + ""; // you can turn an int into a String by concatenating the null string to it System.out.println("zipCode is " + zipCode); // zipCode is 19611 zipCode = zipCode + -1234; // concatenation occurs here since at least one of the two arguments, zipCode, is a String System.out.println("zipCode is now " + zipCode); // zipCode is now 19611-1234 String wholeName = firstName; wholeName += " "; // concatenation wholeName += lastName; System.out.println("wholeName is " + wholeName); // wholeName is John Doe System.out.println("first name is " + wholeName.substring(0, 4)); // firstName is John System.out.println("last name is " + wholeName.substring(5, 8)); // lastName is Doe System.out.println("last name is " + wholeName.substring(5, wholeName.length())); // lastName is Doe System.out.println("last name is " + wholeName.substring(5)); // lastName is Doe System.out.println("The last letter of " + wholeName + " is " + wholeName.substring(wholeName.length() - 1)); // e System.out.println("The letter in the 3rd position of " + wholeName + " is " + wholeName.charAt(3)); // n System.out.println("The letter o is first found in position " + wholeName.indexOf("o") + " of " + wholeName); // 1 System.out.println("The letter z is first found in position " + wholeName.indexOf("z") + " of " + wholeName); // -1 int posBlankSpace = -1; // position of blank space posBlankSpace = wholeName.indexOf(" "); System.out.println("The first name is " + wholeName.substring(0, posBlankSpace)); // The first name is John System.out.println("The last name is " + wholeName.substring(posBlankSpace + 1)); // The last name is Doe String name1 = "Jane"; String name2 = name1; name1 = "Joan"; System.out.println("name1 is " + name1 + " and name2 is " + name2); // name1 is Joan and name2 is Jane // no aliasing occurs because Strings are immutable and are not aliased like other objects } }