Declaring String Variables and Using String Literals
Overview
In this lesson, students will use reference data by declaring and initializing String
objects.
Learning Objectives
- 1.1.B.2 Distinguish between primitive data types and non-primitive data types (objects), including
String
.
- 1.1.B.4 Declare and create variables of specific types.
- 1.1.B.5 Assign values to variables.
Skills
- S1.C Explain the impact design has on data storage.
- S2.A Write program code and implement algorithms.
Student Outcomes
Students will be able to:
- recognize when to use a
String
data.
- declare and initialize variables for
String
data.
Duration: 0.5 class period
Resources
Background
A very useful reference type is String
, which is a collection of characters. It is implemented using the String
class. Recall, a class is a blueprint that defines the data and behavior of this data type.
String
variables are assigned String literals. A literal is a fixed value. A String
literal is enclosed in double quotes. The following are examples of String
literals: "Hello"
, "The big brown dog jumped over the lazy orange cat"
, "!@#$%^&*()"
. When we use a String
literal we are creating a String
object.
An object is an instance of a class. We can declare and initialize many objects or instances of a class. Consider a blueprint for a house. A builder can construct that same house at various different addresses. The houses, aka objects, each have a distinct address, they might have a different color, different roof material, maybe a different number of bedrooms or bathrooms. But essentially it is the same house.
Declaring and Initializing String Variables
String
variables are declared similar to how we would create an int
or char
variables.
String name = "John";
In this case, the String
"John" is assigned to the variable name
.
Activities
Activity 1: Cookie Cutter Objects
As students are entering your classroom provide them with a cookie cutter and playdough. Or have a table at the front of the classroom with playdough of different colors and have students use a cookie cutter to stamp out different objects. There will be several cut out shapes. These would be instances or objects created by the cookie cutter blue print which would be considered a class. You can ask students to identify differences between the cut out shapes. They are maybe different thicknesses or colors. These attributes represent the data that defines the objects. You can revisit this activity when deepening the understanding of the relationship between classes and objects.