Strings in Java

Strings are a special type of object in Java.   

    For most objects, one can only access/modify them using dot (.) notation, e.g.,


   Java provides special syntax for Strings including

        string literal values and concatentation.

String literal-- a set of characters within quotes, e.g., "string literal".

    String s = "hello";

    Internal representation:    a list of characters delimited with '\0'

    Java hides internal representation


    concatenation means to meld two strings together.


        String s1 = "abc";
        String s2 = "def";
        String s3 = s1+s2;   // s3 = "abcdef"

    Can be used to build a string character by character

    String s = "";  // start with empty string
    s = s + "a";
    s = s + "b";

Accessing characters within Strings:

    Normal object dot notation is used.

    from Java API:

char charAt(int index)
          Returns the character at the specified index.
 int length()
          Returns the length of this string.


    String s = "abcdefg";
    char c = s.charAt(3);  // value of c is 'd'

    int l = s.length(); // value of l is 7

    Potential Errors (Exceptions)

IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

    Can write careful code to check for potential errors:

    throw {
        while (i<10)
            char c = s.charAt(i)
    catch (IndexOutOfBoundsException e)

In-Class Assignment
This assignment will help you understand strings and help you with your Lexer assignment

1. Write a program which counts the number of times the digit '3' appears in a string. Your program should contain a method:

        int countThrees(String s)
    and a main that calls countThrees with a string literal parameter then prints out the result.

2. Add a method which grabs the first word in a string. Assume a word is a sequence of letters (a-z or A-Z), and that "first word" means the first such sequence in the given string. Here is the signature for the method:

    String getFirstWord(String s)