package examples; /** * CS401 Example 3 * This handout demonstrates some issues relating to reference variables and * using them correctly. * * @author Dr. Ramirez, PJ Dillon */ public class ex3 { public static void main(String[] args) { // The StringBuffer class is related to the String class. See // Section 3.2 in the text for details on the String class. // StringBuffer objects can also store and access strings of // text. However, unlike String class objects, StringBuffer class // objects can be modified after they are created. We will look // more at the benefits of each later on. StringBuffer S1, S2; S1 = new StringBuffer("Hello"); System.out.println("S1 is " + S1); // System.out.println("S2 is " + S2); // This will give a compilation // error S2 = S1; System.out.println("S2 is " + S2); S1.append(" there Java maestros!"); System.out.println("S2 is " + S2); StringBuffer S3 = new StringBuffer("Hello there Java maestros!"); if (S1 == S2) // comparing references System.out.println(S1 + " == " + S2); if (S1 != S3) System.out.println(S1 + " != " + S3); if (S1.toString().equals(S3.toString())) // comparing actual strings System.out.println(S1 + " equals " + S3); S1 = null; // Now S1 cannot be accessed using the "dot" notation but // S2 still refers to the same object // S1.append(" This is not allowed"); S2.append(" This is ok"); System.out.println("S1 is " + S1); System.out.println("S2 is " + S2); } }