Comp 110 String

String

What is a String?

  • A String is a type
  • Short for a "string of characters"
  • Can be a word or a phrase
  • Useful for all textual data
  • Must be enclosed in quotation marks "like this"
  • A String is actually a complex data types, but it is so commonly needed it is built into the Java language (and most others)
  • We can connect multiple Strings or Strings and variables together through concatenation
  • Watch out for case errors! String is capitalized, unlike many other types 

Take this concrete String example:

String foo = "hello there!";

Since a String is capitalized, there are a number of methods associated it. This includes length, substring, and equals. There are many other methods listed at String documentation.

length 

The length() method's signature is:

int length();

It returns the length of the String. Take the following examples:

String foo = "This is a test";
String bar = "Recognize";
System.out.println( foo.length()); // prints 14, the length of "This is a test"
System.out.println( bar.length());//prints 9, the length of "Recognize"
System.out.println("abc".length()); //prints 3, the length 

substring

The substring() signature is:

String substring(int <start index>, int <end index>);

The substring method is called upon a string, and it returns the substring from the character of of the start index, to the character of the end index minus one. 

Take the following example:

String foo = "This is a test";
String bar = "Recognize";
System.out.println( foo.substring(0,2)); //prints "Th"
System.out.println( foo.substring(2, foo.length()  ));//prints "is is a test"
System.out.println("I like pizza".substring(7,12) ); //prints "pizza"

equals

The equals signature is as follows:

boolean equals(String)

The equals method must be used when evaluating Strings. You cannot use the "==" signs when checking if Strings are equal. This is because Strings are a type of object. 

Take the following example:

String foo = "hello";
String bar = "goodbye";
String jer = "hello";
System.out.println(foo.equals(bar)); //prints "false"
System.out.println(foo.equals(jer));//prints "true"
System.out.println(jer.equals(foo));//prints "true"
System.out.println("goodbye".equals(bar)); //prints "true"