GWU

CS 1111

Introduction to Software Development

GWU Computer Science


Lecture Notes 08: Chars (ASCII), Strings, and the String API


Objectives

By the end of this module, for simple HelloWorld-like programs, you will be able to:




Before Starting

If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:




Catching Up

Before we move forward, let's catch up (complete any remaining work from the previous module)
In this case, make sure we've got:

  1. Nested loops. Reading and writing! avoid initialization errors and bugs relating to the iterations.




Characters vs strings

About characters:

For example:


public class CharExample {

  public static void main (String[] argv) 
  {
    char first = 'o';
    char second = 'y';
    char third = '!';
    System.out.print (first);
    System.out.print (second);
    System.out.println (third);
  }

}

    
In this example: Activity 1: In a file called MyCharExample.java write up a similar example with different characters (expressing surprise).

A String, on the other hand, has zero or more characters.

About strings:

We'll look at some string examples further below.




Character examples

char variables can be used in a for-loop, as in:

public class CharExample2 {

  public static void main (String[] argv) 
  {
    for (char ch='a'; ch <= 'z'; ch++) {
      System.out.print (ch);
    }
    System.out.println ();
  }

}

    
Activity 2: In a file called MyCharExample2.java modify the above to print the letters in reverse order, from z to a.

Characters and ASCII
Characters are represented as integers in the machine.

It is often useful to work with the integer representation, and to go back and forth between representations.

For example:


public class CharExample3 {

  public static void main (String[] argv) 
  {
    // A typical char:
    char first = 'a';            

    // Now extract the int representation:
    int i = (int) first;               
    System.out.println (i);

    // Perform integer arithmetic:
    int j = i+2;                 

    // Convert (or cast) back to char:
    char third = (char) j;

    // Print as char:
    System.out.println (third);
  }

}
Activity 3: Write up, compile and execute the above program.

Note: Important digression:

OK, back to characters.

Activity 4: In a file called MyCharExample3.java write code to identify the integer values for the capital letters 'A' to 'Z'. What are the characters represented by the integers 97 through 122?




Strings

Let's look at an illustrative example:


public class StringExample {

  public static void main (String[] argv) 
  {
    // Declare a string variable and assign it an actual string:
    String s = "The quick brown fox jumps over the lazy dog";
    System.out.println (s);

    // Extract its length:
    int k = s.length ();
    System.out.println (k);     // 43. Includes spaces.

    // You can identify any character in the string, such as:
    char c = s.charAt(0);
    System.out.println (c);     // Prints 'T'.

    // The very useful concatenation operator +
    String s1 = "The";
    String s2 = "quick";
    String s3 = s1 + s2;        // s3 is "Thequick"

    // You can concatenate any number of strings in an expression:
    String s4 = "brown";
    String s5 = s1 + " " + s2 + " " + s4;
    System.out.println (s5);

    // You can concatenate any other type:
    String allLetters = "";
    for (char ch='a'; ch<='z'; ch++) {
      allLetters = allLetters + ch;
    }
    System.out.println ("The alphabet: " + allLetters);

    // Example with concatenating integers onto a string:
    String num1to10 = "";
    for (int i=1; i<=10; i++) {
      num1to10 = num1to10 + " " + i;
    }
    System.out.println ("Numbers 1 to 10: " + num1to10);

    // Example with a BUG when concatenating integers onto a string:
    String num11to20 = "";
    num11to20 = num11to20 + (11 + 12 + 14 + 15 +16 +17 +18 + 19 + 20);
    System.out.println ("Numbers 11 to 20: " + num11to20);  
  }

}
 
Activity 5: Write up the above program, compile and execute.

Now let's understand the code: Strings can contain the escape characters we saw earlier in Lecture Notes 02.

Example:


public class StringExample2 {

  public static void main (String[] argv) 
  {
    String s = "";
    
    int last = 5;
    for (int i=1; i<=last; i++) {
      for (int j=1; j<=i; j++) {
        s = s + "*";
      }
      s = s + "\n";
    }
    System.out.println ("A triangle with base=" + last + ":\n" + s);
  }

}
  
Activity 6: Write up the above program, compile and execute. Change the base of the triangle to 10.

Activity 7: Trace the execution of the above program, showing how the string s changes.

Note: It is convenient to use the short-cut version of "concatenation to the same variable". Thus, instead of
      // Concatenate to s and assign to s:
      s = s + "\n";
    
write
      // Short-cut version:
      s += "\n";
    
Activity 8: In MyStringExample2.java rewrite the above program (for base=10) using the short-cut version.

Activity 9: Consider this snippet of code:
    int q = 5;

    System.out.println (q);
    System.out.println ("q");
    System.out.println ('q');

    String s = "q";
    char c = 'q';
    
What gets printed? Ponder about the differences between the three.




Input from the terminal

As we've seen before, we can use additional Java tools to force the program to wait until a user types input into the terminal.

The following is code is simillar to programs we've used before:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22


  import java.util.Scanner;  // Import the Scanner class

  public class ScanAndParse
  {
    public static void main(String args[])     
    {
      // Prints prompt for user:
      System.out.println ("Give me a number and then press Enter: ");
      
      // Scanning code starts here
      Scanner myScanner = new Scanner (System.in);
      String s = myScanner.nextLine ();
      // Scanning code ends here
      
      // Input conversion to Double starts here
      double sAsDouble = Double.parseDouble(s);
      // Input conversion to Double ends here
         
      System.out.println ("The number is: ");
      System.out.println (sAsDouble);        
    }
  }  
  

These two things and the way they are written, will be explained in detail in a future module, but for now, here is a brief description of what is going on:




The String API

API means Application Programming Interface. It is a set of rules that people can interact with (Interface) for those people who wish to use a certain tool to create (Program) a Service (Application) of some sort.

Another way of calling it would be: rules for using our tool to program a service.

Strings are tools that someone else made and that other people can use as long as they know how to declare, initialize, and access their methods.

In the next module, we'll use the String API to manipulate Strings in a more powerful way, which will include: