Strings and StringBuffers.

// The program demonstrates various methods of String and StringBuffer
// classes. 
// The main difference between the two is that String objects are immutable
// (once created, they can't be changed), so you have to assign
// the result of every operation to a variable.
// StringBuffer is mutable (can be changed directly in memory)
 
public class StringTest {
	public static void main( String [] args) {
	    String s1 = "Hi there!"; // don't need 'new' to create a string

	    // STRING OPERATIONS

	    // create a new string "HI THERE!", store its address in s1
	    s1 = s1.toUpperCase();
	    System.out.println(s1);

	    // string concatenation ("gluing together"):
	    String s2 = s1 + " Haven't seen you in a while...";
	    System.out.println(s1); // s1 doesn't change
	    System.out.println(s2);

	    // various String methods (see more in the API)
	    boolean b = s2.startsWith(s1);
	    System.out.println("b = " + b);
	    int length = s1.length();
	    System.out.println("length of " + s1 + " is " + length);


	    String s3 = "HI THERE!"; // another string with the same contents

	    // comparing strings: == compares the addresses
	    System.out.println("comparing with ==");
	    if (s1 == s3) {
		System.out.println("the strings are the same");
	    } else {
		System.out.println("the strings are different");
	    }

	    
	    // comparing strings: .equals compares the contents 
	    System.out.println("comparing with .equals()");
	    if (s1.equals(s3)) {
		System.out.println("the strings are the same");
	    } else {
		System.out.println("the strings are different");
	    }

	    s2 = s2.toLowerCase();
	    System.out.println(s1.equalsIgnoreCase(s2));

	    // What's going on there? Try different strings. 
	    s1 = "apples";
	    s2 = "oranges";
	    int result1 = s1.compareTo(s2); // The result is an integer!
	    System.out.println("s1.compareTo(s2) = " + result1);
	    int result2 = s2.compareTo(s1); // The result is an integer!
	    System.out.println("s2.compareTo(s1) = " + result2);

	    // YOU CAN DO MUCH MORE WITH STRINGBUFFER
	    // The StringBuffer is changing
	    StringBuffer sb1 = new StringBuffer("Apples are tasty");
	    sb1.insert(11, "red and ");
	    System.out.println(sb1);
	    sb1.replace(0,6,"Tomatoes");
	    System.out.println(sb1);
	    sb1.reverse();
	    System.out.println(sb1);
	    sb1.reverse();
	    System.out.println(sb1);
	    sb1.delete(13,21);
	    System.out.println(sb1);
	}
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.