Week 7, Notes 1

Strings

Strings are objects, not primitive values.

Literals

Java provides string literals, but they are not the same as literals of primitive types – more on this later.

Variables

Variables may ‘hold’ string values.  Declaration of a variable requires a type name and a variable name.

Variables may be assigned values, so long as value is of the correct type.

Objects support methods

Strings are objects, so they can be asked to execute methods that they support.

 

See API | package lang | class String

 

String s = "Hello"; // variable s holds a pointer to the string “Hello”

s.length() == 5  // ask s to return its length, which is 5, so the ==

                 // operator returns true

Strings are made up of individual characters

Use methods defined in String class to get at individual characters:

s.charAt(0)     // ask s to return the char at index 0 (the first char)

s.indexOf(‘a’)  // ask s to return the index of the first ‘a’ in s

 

Converting a primitive value to a String value

String floatAsString = "" + 5.5;

 

See ../demos/W07N01.java for a demonstration of how to use these methods

 

Comparing strings.  Here is a method that takes a String parameter and compares the value received with the String “Circle”.

 

// @return true if s matches the string "Circle"

public static boolean isCircle( String s)

{

  return s.equals("Circle"); 

    // ask s if it contains the same characters as the string "Circle"

    // notice that equals() is does a case sensitive comparison

    // to do a case insensitive comparison,

    // use the equalsIgnoreCase() method – see the String class in the API

}