Welcome to Lesson 6!

Learning Objectives
By the end of today's class, you should know...
  • What is Unicode?
  • What is a String?
  • What is the difference between a char and a String?
  • What is String concatenation?
  • What are two ways to do console input with a String?
  • What is String concatenation
  • What is the String length method and how do you "call" it?
  • What is the String equals method and how do you "call" it?
  • What is the String toUpperCase method and how do you "call" it?
  • What is the String toLowerCase method and how do you "call" it?
  • What is the String charAt method and how do you "call" it?

Announcements

  • Quiz 2 after our break!
  • Don't forget about Lab 3 due Friday!

Review Activities

Q1: What Gets Printed to the Screen?

//assume below statement are part of a main function

int oranges = 5;

int apples = 3;

int numFruit = apples + oranges;

System.out.println("Total Fruit: " + numFruit);

apples = apples - 2;

oranges = apples;

System.out.println("Apples: " + apples);

    System.out.println("Oranges: " + oranges);

Q2: Write a complete user interaction as follows (3-4 lines of code only!):
  • Declare a new Scanner variable named input, and connect it to the console keyboard.
  • Declare a double variable named height.
  • Prompt the user to enter his or her height with a message like Enter your height:
  • Read in the user input and store it as the height variable

Q3: Write one statement to import the class to use Scanner in your program

Q4: What will the following statements output to the console

1. System.out.println(7 / 2.0);

2. System.out.println(7 / 2);

3. System.out.println(7 % 2);

4. System.out.println(9 + 3 * 5 / 2 - 3);


Review of Char

  • In addition to numbers, computers can manipulate text and other non-numerical types
  • Values of type char (short for character) are a single letter, number or special symbol
  • You specify a character by enclosing it in single quotes (')
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • When you use a char data type, you store the character using a Unicode code.


Java and Unicode

  • Unicode is a coding method that assigns a number to every character in every language in the world.
  • Unicode assigns a numeric value to 1,112,064 different characters.
  • Java's char type was designed to work with Unicode.
  • However, Java uses only 2 bytes to store each character - which is not sufficient to store the Unicode value for all characters. Any additional characters that Java cannot store as a char are known as supplementary characters.


Char Variables - Declaring and Assigning

  • As with other data types, you must declare char variables before use:
    char letter;
  • You assign values to a char variable using the equals sign:
    letter = 'A';
  • Just like numerical types, you can combine declaration and assignment into one statement:
    char letter = 'A';
  • Also like numerical types, you can declare multiple variables on one line:
    char letter, letterA = 'A', letterB = 'B';

Introduction to Strings

  • In addition to single characters, computers can work with text strings
  • For example, in the following the characters between the double quotes are displayed as text:
    System.out.println("Hello World!");
  • Programmers refer to text like this as a String because it is composed of a sequence of characters that we string together
  • Java provides the String type so we can work with text
  • Strings are enclosed in double quotes, which are not part of the String
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Fred"
  • Notice that the String "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    "3.14159" * 2; // NO!
    3.14159 * 2; // allowed 


String Variables and Simple I/O

  • We declare and assign values to String variables like numeric types
  • For example:
    String firstName;             // declaration
    firstName = "Jennifer";       // assignment
    String lastName = "Parrish";  // declaration + assignment
    System.out.println(firstName + " " + lastName);

Simple I/O with Strings Using next():

  • Like numbers, you can output type String using System.out.println()
  • To read in a String value we can use the next() method:

    firstName = input.next(); //note that this is not nextString()!

  • For example:
    String firstName;
    System.out.print("Enter your name: ");
    firstName = input.next();
    System.out.println("You entered: " + firstName);
    
  • The input.next() statement assigns the user input to the String variable fname
  • Note that only a single word can be entered using input.next()
  • This is because input.next() works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Reading Data Line-By-Line Using nextLine():

  • Another Scanner method called nextLine() allows us to read an entire line of text into a String variable.
  • For example, if we want to take in the user's whole name, we would choose nextLine() instead of next().
  • For example:
    String fullName;
    System.out.print("Enter your name: ");
    fullName = input.nextLine();
    System.out.println("You entered: " + fullName);
  • input.nextLine() works differently from input.next() 
    • It reads until it finds a newline character.

The Problem with Newlines

  • When you press the Enter key, a newline character ('\n') is inserted as part of the input
  • The newline character can cause problems when you mix input.next(), input.nextInt() or input.nextDouble() with input.nexLine()
  • Recall that input.next(), as well as nextInt() and nextDouble():
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found
  • Since whitespace includes newline characters, using input.next() will leave a newline character in the input stream
  • However, input.nextLine() just stops reading when it first finds a newline character
  • This can lead to mysterious results in code like the following:
    System.out.print("Enter your age: ");
    int age = input.nextInt();
    System.out.print("Enter your full name: ");
    String name = input.nextLine();
    System.out.println("Your age: " + age + "\n"
         + "Your full name: " + name);
    
  • To correct this problem we add an additional input.nextLine() just before input.nextLine()

System.out.print("Enter your full name: "); 
input.nextLine(); //clear out the \n
String name = input.nextLine();

  • We can see how to use this fix in the following example

Example Using an additional input.nextLine()


public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter your age: ");
    int age = input.nextInt();

    System.out.print("Enter your full name: ");
    input.nextLine(); //clear out the \n
    String name = input.nextLine();     System.out.println("Your age: " + age + "\n"     + "Your full name: " + name);

Joining Strings (Concatenation)

  • You can join two Strings together using the '+' operator
  • The join operation is called concatenation
  • We have seen concatenation before in our System.out.print statements:

System.out.println("Your age is: " + age);

  • Another concatenation example:
    String s1 = "Hello", s2 = "World!";
    String s3 = s1 + s2;
    System.out.println(s3);
    
  • The String s3 now has the contents of both s1 and s2
  • You can also mix String variables and literal Strings:
    String s1 = "Hello", s2 = "World!";
    String s3 = s1 + ", " + s2;
    System.out.println(s3);
    
  • We can also join numbers and Strings using concatenation.
  • Note that concatenation between a number and a String will cause the number to be converted automatically to a String.
  • For instance:
String address = 124 + " East Ave";
System.out.println(address);
  • In addition, we can concatenate Strings and characters:
    char letter = 'A';
    String s1 = "BC";
    s1 = letter + s1 + 'D';

Activity 6.1
: Working with Strings (10 pts)

  • Find a partner for pair programming and open a new Java project named MyName in Eclipse
  • We will create a program to greet the user by name.
  • Add a block comment at the top of your program with your names and section information.
/*
* Name of partner 1
* Name of partner 2
* Section info
*/
  • At the top of the main method, let's declare our first String variable - to store the first name of our user:
String first_name;
  • Declare a second String variable to store the last name of our user in the same _ style.
  • Declare a third String variable to store the user's full name:
String full_name;
  • Finally, declare a new Scanner variable named input and connect it to the console keyboard.
  • Welcome the user with a statement like this one:
System.out.println("Hi! I want to learn your name!");
  • Now, prompt the user to enter their first name.
System.out.print("Please enter your first name: ");
  • Follow this prompt with a input.next() statement to capture the user input.
first_name = input.next();
  • Now prompt the user to enter his or her last name and store the input in the last_name variable.
  • We want to assign the full_name variable the value of the user's first and last name combined. Let's do so now using concatenation:
full_name = first_name + " " + last_name;
  • Finally, let's greet the user by his or her full name.
System.out.println("Nice to meet you " + full_name + "!");

  • Lastly, close your Scanner
input.close();
  • Run your program to ensure it is giving you the output you expect.
  • Then, hold onto it as we are going to use complete this program in the next activity.


String Methods

  • Strings are a special type of variable called objects, which you will study in more detail in CIS 36B.
  • An object is a data type that can have methods associated with it
  • These methods are called member functions and are called using dot notation
  • The syntax for calling a member function of a String object is:
    StringName.methodName(arguments)
    
  • Where:
    • StringName: the name of the String variable
    • methodName: the name of the member function
    • arguments: the input values, if any
  • Once you create a String variable, you can call (use) its member functions

Some Commonly-Used String Methods

  • length(): Returns the number of characters in a String
    String str = "Hello";
    System.out.println("The number of characters is " + str.length());
  • equals(): Compares two Strings and tells you whether they are equal to each other (true) or not equal to each other (false).
         String cat1 = "Cat";
    String cat2 = "Kat";
    System.out.println("Cat equals Kat: " + cat1.equals(cat2));
    System.out.println("Car equals Car: " + "Car".equals("Car"));
  • toLowerCase() and toUpperCase(): Converts a String to all lower case characters or all upper case characters, respectively

    System.out.println("Capitalize".toUpperCase());
    System.out.println("LowerCase".toLowerCase());        
      

  • charAt: Returns a character at a specific index of the String.
    String greeting = "Hello, World!";
    char ohMy = greeting.charAt(4);
    System.out.println(ohMy);
    
  • The position numbers in a String start at 0. The last character is always one less than the length of the String
    Hello,
    World!
    0123456789101112
  • char w = greeting.charAt(7);
    Hello,
    World!
    0123456789101112

  • These are just some examples. There are many more things you can do with Strings!


Example Using String Methods

  • Consider the problem of extracting the initials from a person's name
  • What would be an algorithm for solving this problem?
  • To implement this algorithm, we can use the String method charAt()
  • The following program implements an algorithm for extracting the initials from a person's name


Activity 6.2: My Name Part 2 (10pts) 

  • Find a partner for pair programming.
  • Open up your MyName project from last class, and let's add to it.
  • Don't forget to include your partner's name in the comments at the top of the program.
  • Let's calculate the length of the user's first and last names and output the result to the console
System.out.println("The length of your first name is " + first_name.length() + " letters");
  • Now add a similar System.out.println statement to display the length of the user's last name AND full name (remember the full_name variable)
  • Next, let's return the user's initial's to them.
  • Let's declare a new String variable called initials that you place at the top of your program with the other variable declarations.
String initials;

  • Next, we are going to use the charAt() function to extract the initials from the user's first and last names.
  • A person's initials are composed of the first letters of their first and last names.
  • Therefore, we need the letters at position 0 in the first_name and last_name variables.
initials = "" + first_name.charAt(???) + ?????????;
  • Note that "" is called the empty String.
  • Next, print the results to the console to display for the user.
System.out.println("Your initials are: " + initials);
  • Let's compare their first and last names to see if they are the same using the equals method.
  • Add a statement like the following after the last System.out.println:

System.out.println("Your first and last name are the same: " + first_name.equals(last_name));

  • Finally, let's print out the full name in all upper case and all lower case. Add two System.out.println statements:

System.out.println("Your name in all capitals is: " + full_name.toUpperCase());

//Now add a similar statement to print out the name in all lower case characters

  • When you are finished, the output of your program should look like below.
  • However, look closely and you will see a mistake in my output below.
  • Please correct the mistake before you turn it in (there are a couple of different approaches you can take to this problem).
  • Submit your MyName.java program to Canvas.
  • Remember that both partners need to submit for full credit.

The output of your program should look like this (except user input will vary):

Hi! I want to learn your name.
Please enter your first name: Jennifer
Please enter your last name: Parrish
Nice to meet you Jennifer Parrish!
The length of your first name is 8 letters
The length of your last name is 7 letters
The length of your full name is 16 letters
Your initials are: JP
Your first name and last name are the same: false
Your name in all capitals is: JENNIFER PARRISH
Your name in all lower case letters is: jennifer parrish


Wrap up
  • Answer the questions from today's learning objectives
Assignment 6 due Tuesday at 11:20am
Lab 4 due Friday at Midnight
~See You Thursday!~