Module 6: Characters, Strings, and Some Tools


Objectives

 

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

 

6.0 Audio:
 


6.0    Characters vs strings

 

About characters:

  • The term character is used to mean:
    • Letters like a, b, X, Y.
    • Symbols like #, $, @, !.

  • Each character is a single symbol.

  • The reserved word char is used to declare variables that hold such values.

  • Pronounce char as the English word char, rhyming with "far".

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:
  • The reserved word char is used to declare the variable first
    	char first = 'o';
        

  • Single quotes delineate an actual character:
    	char first = 'o';
        
 

6.1 Exercise: 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:

  • Strings are declared using String as in
    	String s = "meh";
        
  • Strings used double-quotes for delineation.

  • Examples: "meh", "yada yada", "Alfred E. Neumann", "The quick brown fox jumps over the lazy dog"

  • It is possible to declare and use an empty string, as in:
    	String s = "";
        

We'll look at some string examples further below.
 


6.1    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 ();
    }

}

    
 

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

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);
    }

}
 

6.3 Exercise: Write up, compile and execute the above program.
 

Note:

  • The conversion from one type of variable (say, int) to another type (say, char) is called casting.

  • You would say "I'm casting a char into an int".

  • The syntax is to have the target type in parens on the right side of the assignment symbol:
    	char third = (char) j;
        

  • In some cases, we don't explicitly need to cast. We could have written
    	// Going from char to int:
    	int i = first;               
        

  • As a general stylistic rule, it's best to specify a cast even if not explictly required.

  • Why, then, does the compiler allow some casts without programmer intention stated explicitly?
    • It's considered safe to go from more specific to more general.
    • All char's are int's
    • But not the other way around.
    • Thus, there are some integers that have no char equivalent.
    • The compiler then wants you to say "I know what I'm doing" by explicitly stating the cast.
 

6.4 Video:

 

Important digression:

  • We've learned a really important concept: type.

  • That is, variables have a property called type.

  • So far, we've seen integer and character types.

  • As it will turn out, every variable must have a type.

  • There are strict rules in going back and forth between types.

  • These rules are very useful in helping programmers avoid mistakes.

  • For example, without "types" you could accidentally use an int for 3.141 and have that incorrectly represented as 3.

  • In later units we will encounter a deeper understanding of "types".

OK, back to characters.
 

6.5 Exercise: 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?
 


6.2    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);
    }

}
 
 

6.6 Exercise: Write up the above program, compile and execute.
 

Now let's understand the code:

  • First, the declaration using (with cap 'S') String
    	String s = "The quick brown fox jumps over the lazy dog";
        

  • The variable is called s and value of this variable is "The quick brown fox jumps over the lazy dog".

  • Now for something strange:
    	int k = s.length ();
        
    It is possible to call a method, seemingly attached to the string itself.

  • There are, it turns out, many such methods. Example:
    	char c = s.charAt(0);
        
    This method even takes an integer argument (parameter) like 0.

  • One of the most useful ways to combine strings is to concatenate (join) them using the +. operator.
    	String s5 = s1 + " " + s2 + " " + s4;
        

  • This is the same "plus" operator we used for integers. It's doing double-duty as concatenation operator for strings.

  • You can concatenate all kinds of things into strings.

  • For example, integers:
    	    num1to10 = num1to10 + " " + i;
        
    Here, it's worth pointing out, num1to10 is a string variable but i is an integer variable.

  • At long last, we can make output more friendly.

  • Thus, instead of just printing
    	System.out.println (allLetters);
        
    we print
    	System.out.println ("The alphabet: " + allLetters);
        
 

6.7 Video:

 

Strings can contain the escape characters we saw earlier in Module 2.

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);
    }

}
  
 

6.8 Exercise: Write up the above program, compile and execute. Change the base of the triangle to 10.
 

6.9 Exercise: In module6.pdf trace the execution of the above program, showing how the string s changes.
 

Note:

  • Note that we inserted the "new line" symbol \n in two places.

  • Once here:
    	    s = s + "\n";
        
    and once here:
    	System.out.println ("A triangle with base=" + last + ":\n" + s);
        
 

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";
    
 

6.10 Exercise: In MyStringExample2.java rewrite the above program (for base=10) using the short-cut version, remembering to change the class name to match the file name.
 

6.11 Exercise: Consider this snippet of code:

    int k = 5;

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

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

6.12 Audio:
 


6.3    Fun with strings

 

We will occasionally introduce programs we've written to both simplify your programming and yet allow for interesting examples.

If all we did was compute with integers, it would be boring.

You've already seen one example of such a tool: DrawTool.

We'll now use WordTool, another tool that you will use by calling appropriate methods.

You are welcome and are encouraged to "look inside" by skimming over the code in any tool.

Let's start with an example:


public class RandomSentence {

    public static void main (String[] argv) 
    {
	//Get some random parts of speech:
	String adj = WordTool.getRandomAdjective ();
	String noun = WordTool.getRandomNoun ();
	String noun2 = WordTool.getRandomNoun ();
	String verb = WordTool.getRandomVerb ();
	String prep = WordTool.getRandomPreposition ();

	// We'll try and make it past tense.
	verb = verb + "ed";

	// Build a sentence.
	String sentence = "The " + adj + " " + noun + " " + verb + " " + prep + " a " + noun2;

	// Print.
	System.out.println (sentence);
    }

}
  
 

6.13 Exercise: Write up the above program. You will also need to download both WordTool.java and wordsWithPOSAndPron.txt into the same directory as your code. Execute the code at least 10 times if not more. What's your favorite sentence?
 

6.14 Exercise: Improve on the above program by writing your version of a random sentence in MyRandomSentence.java, remembering to change the class name to match the file name. You can call methods to give you random conjunctions, adverbs and other parts of speech.
 


6.4    Input from the terminal

 

Thus far we have printed (output) to the screen but have not taken in any input.

Thus, we haven't written any programs that interact with potential users of our programs.

There's a limited market for programs that only execute once with no input whatsoever, right?

We will now introduce another tool called IOTool, ("I" for input, "O" for output).

Here's an example:


public class Triangle {

    public static void main (String[] argv) 
    {
	// Use IOTool to prompt the user and get the integer 
	// typed in by the user:
	int size = IOTool.readIntFromTerminal ("How big would you like your triangle? Enter the size: ");

	// Now make the triangle.
	for (int i=1; i<=size; i++) {
	    for (int j=1; j<=i; j++) {
		System.out.print ("*");
	    }
	    System.out.println ();
	}
    }

}
 
 

6.15 Exercise: Type up the program, compile and execute. You will need to download IOTool.java into the same directory.
 

Now let's do something more interesting by asking the user to type in a string:


public class Conversation {

    public static void main (String[] argv) 
    {
	// Tell IOTool to prompt the user and then get the string
	// typed in by the user:
	String name = IOTool.readStringFromTerminal ("What is your name? Enter: ");

	// Now use this to respond:
	System.out.println ("Hi " + name + "!");
	String adv = WordTool.getRandomAdverb ();
	String adj = WordTool.getRandomAdjective ();
	String sentence = name + ", you are " + adv + " " + adj;
	System.out.println (sentence);
    }

}
  
 

6.16 Exercise: Improve on the above program by writing your version of a longer conversation MyConversation.java, Call IOTool.readStringFromTerminal(), several times to go back and forth. Unleash your guile and creativity.
 

6.17 Exercise: Try out a conversation with a chatbot. For example, one of the earliest chatbots in history was Eliza, which you can try out.
 

Lastly, let's point out something about input:

  • At the moment, we're using a convenient method in IOTool to extract user input typed into the terminal.

  • For example, in the Conversation example above, we had the line
    	// Tell IOTool to prompt the user and then get the string
    	// typed in by the user:
    	String name = IOTool.readStringFromTerminal ("What is your name? Enter: ");
        
    Here, the user types something and the entire string of characters gets put into our String, variable called name,

  • Similarly, in an earlier example, we read an integer:
    	// Use IOTool to prompt the user and get the integer 
    	// typed in by the user:
    	int size = IOTool.readIntFromTerminal ("How big would you like your triangle? Enter the size: ");
        
    Thus, when the user types in an integer, that integer values gets assigned to our integer variable size.

  • Let's take a peek inside IOTool to see how IOTool does this.

  • Here's the code in the readIntFromTerminal method:
        public static int readIntFromTerminal (String prompt)
        {
            // Notice: we're using print instead of println to write
            // out the prompt:
    	System.out.print (prompt);
        
            // Scanner is a special object (we'll learn about objects
            // later) in the Java library. You can skip over understanding
            // this for now.
    	Scanner console = new Scanner (System.in);
    
            // Once the Scanner object is activated (as above), it has 
            // methods to retrieve strings, int's and such from the terminal.
    	int i = console.nextInt ();
    
            // This is what IOTool returns.
    	return i;
        }
        
  • If you had wondered whether there was an equivalent to System.out now we have an answer: yes.

  • However, until we acquire an understanding of how objects (this is programming language jargon) work in Java, the line
     	Scanner console = new Scanner (System.in);
        
    will have to remain inscrutable for now.

  • This is the reason we created methods in IOTool, to hide some inexplicable detail at this time.

  • Note: if you are reading a textbook alongside, the textbook might use the Scanner object. Don't be alarmed. It's doing the work of acquiring user input.
 

6.18 Audio:
 

On to Module 7


© 2017, Rahul Simha