20
The Java String The Java String Type Type CSC 1401 CSC 1401 : Introduction to Programming : Introduction to Programming with Java with Java Week 7 – Lecture 1 Week 7 – Lecture 1 Wanda M. Kunkle Wanda M. Kunkle

The Java String Type

Embed Size (px)

DESCRIPTION

The Java String Type. CSC 1401 : Introduction to Programming with Java Week 7 – Lecture 1 Wanda M. Kunkle. Data Types in Java. Recall from week 2 that there are two main kinds of types in Java: Primitive type Stores a single piece of data of a specific type - PowerPoint PPT Presentation

Citation preview

Page 1: The Java String Type

The Java String TypeThe Java String TypeCSC 1401CSC 1401: Introduction to Programming with : Introduction to Programming with

JavaJavaWeek 7 – Lecture 1Week 7 – Lecture 1

Wanda M. KunkleWanda M. Kunkle

Page 2: The Java String Type

22

Data Types in JavaData Types in Java

Recall from week 2 that there are Recall from week 2 that there are two main kinds of types in Java:two main kinds of types in Java:– Primitive typePrimitive type

Stores a single piece of data of a specific Stores a single piece of data of a specific typetype

Some primitive types and the kinds of data Some primitive types and the kinds of data they store are:they store are:

– int – a 32-bit integer (A int – a 32-bit integer (A bitbit is a 0 or 1.) is a 0 or 1.)– float – a 32-bit floating point (decimal) numberfloat – a 32-bit floating point (decimal) number– double – a 64-bit floating point (decimal) numberdouble – a 64-bit floating point (decimal) number– char – a single character (e.g., ‘Y’)char – a single character (e.g., ‘Y’)

Page 3: The Java String Type

33

Data Types in JavaData Types in Java

Class typeClass type– Stores multiple pieces of data and provides Stores multiple pieces of data and provides

methods for manipulating that datamethods for manipulating that data– Some class types are:Some class types are:

String – stores and manipulates a string of characters String – stores and manipulates a string of characters contained between double quotation marks, e.g., contained between double quotation marks, e.g., “Susan”“Susan”

input – stores and manipulates text entered at the input – stores and manipulates text entered at the keyboardkeyboard

– Variables that are class types are called Variables that are class types are called objectsobjects..

Page 4: The Java String Type

44

Declaring String ObjectsDeclaring String Objects We declare String variables (technically, We declare String variables (technically,

objects ) basically the same way that we objects ) basically the same way that we declare variables of other types.declare variables of other types.– ExamplesExamples::

String first_name, last_name, full_name;String first_name, last_name, full_name; We assign values to String objects basically We assign values to String objects basically

the same way that we assign values to the same way that we assign values to variables of other types.variables of other types.– ExamplesExamples::

first_name = “Darth”;first_name = “Darth”; last_name = “Vader”;last_name = “Vader”; full_name = first_name + “ ” + last_name ;full_name = first_name + “ ” + last_name ;

Page 5: The Java String Type

55

Inputting StringsInputting Strings StringsStrings

– Use the Use the readname()readname() method to input a string consisting method to input a string consisting of letters, digits, and underscores.of letters, digits, and underscores. The method reads until it encounters a character that is not The method reads until it encounters a character that is not

a letter, digit, or underscore.a letter, digit, or underscore. For example, given the input “Ah! I see.” the statement:For example, given the input “Ah! I see.” the statement:String name = in.readname();String name = in.readname();would store “Ah” in would store “Ah” in namename..

– Use the Use the readword()readword() method to input a string consisting method to input a string consisting of nonblank characters.of nonblank characters. The method reads until it encounters a blank character The method reads until it encounters a blank character

(Blank characters include the space and newline (Blank characters include the space and newline characters.).characters.).

For example, given the input “Ah! I see.” the statement:For example, given the input “Ah! I see.” the statement:String word = in.readword();String word = in.readword();would store “Ah!” in would store “Ah!” in wordword..

Page 6: The Java String Type

66

Inputting StringsInputting Strings StringsStrings

– Use the Use the readline()readline() method to input a string method to input a string consisting of nonblank as well as blank consisting of nonblank as well as blank characters.characters. The method reads until it encounters the newline The method reads until it encounters the newline

character (which it reads but does not store).character (which it reads but does not store). For example, given the input “Ah! I see.” the statement:For example, given the input “Ah! I see.” the statement:String line = in.readline();String line = in.readline();would store “Ah! I see.” in would store “Ah! I see.” in lineline..

– Use the Use the readln()readln() method to input a string and method to input a string and skipskip it. it. The method reads until it encounters the newline The method reads until it encounters the newline

character; it skips all characters, including the newline.character; it skips all characters, including the newline. For example, the statement:For example, the statement:in.readln();in.readln();would read and skip any input string ending in newline.would read and skip any input string ending in newline.

Page 7: The Java String Type

77

String MethodsString Methods

String methods can be used to String methods can be used to manipulate the values stored in String manipulate the values stored in String objects.objects.

Java’s creators at Sun Microsystems Java’s creators at Sun Microsystems provided many such methods, viewable provided many such methods, viewable at:at:– http://java.sun.com/javase/6/docs/api/index.hthttp://java.sun.com/javase/6/docs/api/index.ht

mlml We will look at a small subset of these We will look at a small subset of these

methods.methods.

Page 8: The Java String Type

88

String MethodsString Methods

length()length()– Returns the length of the String objectReturns the length of the String object– ExampleExample::

output out = new output();output out = new output();String first_name = “Darth”;String first_name = “Darth”;int name_length = first_name.length();int name_length = first_name.length();

out.writeln(name_length); // Displays 5out.writeln(name_length); // Displays 5

Page 9: The Java String Type

99

String MethodsString Methods

toUpperCase()toUpperCase()– Returns a string with same characters as Returns a string with same characters as

the calling String object, but converted to the calling String object, but converted to uppercaseuppercase

– ExampleExample:: output out = new output();output out = new output();

String first_name = “Darth”;String first_name = “Darth”;

out.writeln(first_name.toUpperCase()); // Displaysout.writeln(first_name.toUpperCase()); // Displays // DARTH // DARTH

Page 10: The Java String Type

1010

String MethodsString Methods

toLowerCase()toLowerCase()– Returns a string with same characters as the Returns a string with same characters as the

calling String object, but converted to lowercasecalling String object, but converted to lowercase– ExampleExample::

output out = new output();output out = new output();String first_name = “Darth”;String first_name = “Darth”;

out.writeln(first_name.toLowerCase());out.writeln(first_name.toLowerCase()); // Displays// Displays // darth// darth

– QuestionQuestion:: Do you think the original string has been altered?Do you think the original string has been altered?

– How could we go about checking this?How could we go about checking this?

Page 11: The Java String Type

1111

Sample ProgramSample Program

Now let’s look at a sample program Now let’s look at a sample program that demonstrates using these 3 that demonstrates using these 3 methods:methods:– StringTypeDemo1.javaStringTypeDemo1.java

Page 12: The Java String Type

1212

String MethodsString Methods

equals(equals(otherStringotherString))– Returns true if the calling String object and Returns true if the calling String object and otherStringotherString are equal; otherwise, returns false are equal; otherwise, returns false

– ExampleExample:: output out = new output();output out = new output();

String response = “yes”;String response = “yes”;

if (response.equals(“Yes”))if (response.equals(“Yes”)) out.writeln(“The responses are equivalent.”); out.writeln(“The responses are equivalent.”);elseelse out.writeln(“The responses are NOT equivalent.”); out.writeln(“The responses are NOT equivalent.”);

// What do you think is displayed?// What do you think is displayed?

Page 13: The Java String Type

1313

String MethodsString Methods

equalsIgnoreCase(equalsIgnoreCase(otherStringotherString))– Returns true if the calling String object and Returns true if the calling String object and otherStringotherString are equal when case is ignored; are equal when case is ignored; otherwise, returns falseotherwise, returns false

– ExampleExample:: output out = new output();output out = new output();

String response = “yes”;String response = “yes”;

if (response.equals(“YES”))if (response.equals(“YES”)) out.writeln(“The responses are equivalent.”); out.writeln(“The responses are equivalent.”);elseelse out.writeln(“The responses are NOT equivalent.”); out.writeln(“The responses are NOT equivalent.”);

// What do you think is displayed?// What do you think is displayed?

Page 14: The Java String Type

1414

Sample ProgramSample Program

Now let’s look at a sample program Now let’s look at a sample program that demonstrates using one of these that demonstrates using one of these methods (Aside: You’ve seen it methods (Aside: You’ve seen it before.):before.):– examAverager.javaexamAverager.java

Page 15: The Java String Type

1515

String MethodsString Methods

substring(substring(startstart))– Returns the substring of the calling String Returns the substring of the calling String

object from position object from position startstart to the end of the to the end of the calling objectcalling object

– ExampleExample:: String street_name, street_address;String street_name, street_address;

street_address = “3141 Chestnut Street”;street_address = “3141 Chestnut Street”;

street_name = street_address.substring(5);street_name = street_address.substring(5);

Page 16: The Java String Type

1616

String MethodsString Methods

substring(substring(startstart, , endend))– Returns the substring of the calling String Returns the substring of the calling String

object from position object from position startstart through, but not through, but not including, position including, position endend of the calling object of the calling object

– ExampleExample:: String street_number, street_address;String street_number, street_address;

street_address = “3141 Chestnut Street”;street_address = “3141 Chestnut Street”;

street_number = street_address.substring(0, 4); street_number = street_address.substring(0, 4);

Page 17: The Java String Type

1717

String MethodsString Methods indexOf(indexOf(aStringaString))

– Returns the position of the first occurrence of Returns the position of the first occurrence of aStringaString in the calling String object; if in the calling String object; if aStringaString is not found, is not found, returns -1returns -1

– ExampleExample:: String street_number, street_name, street_address;String street_number, street_name, street_address;

int spacePosition;int spacePosition;

street_address = “3141 Chestnut Street”;street_address = “3141 Chestnut Street”;

// Use the location of the space to break apart the street // Use the location of the space to break apart the street addressaddressspacePosition = street_address.indexOf(" ");spacePosition = street_address.indexOf(" ");street_name = street_address.substring(spacePosition + 1);street_name = street_address.substring(spacePosition + 1);street_number = street_address.substring(0, spacePosition); street_number = street_address.substring(0, spacePosition);

Page 18: The Java String Type

1818

String MethodsString Methods indexOf(indexOf(aStringaString, , startstart))

– Returns the position of the first occurrence of Returns the position of the first occurrence of aStringaString in the calling String object that occurs at or in the calling String object that occurs at or after position after position startstart; if ; if aStringaString is not found, returns -1 is not found, returns -1

– ExampleExample:: String street_address;String street_address;

int periodPosition;int periodPosition;

street_address = “3141 Chestnut Street”;street_address = “3141 Chestnut Street”;

// Locate a period, if present// Locate a period, if presentperiodPosition = street_address.indexOf(“.”, 0);periodPosition = street_address.indexOf(“.”, 0);

// What value does the above code return?// What value does the above code return?

Page 19: The Java String Type

1919

Sample ProgramSample Program

Now let’s look at a sample program Now let’s look at a sample program that demonstrates using at least 3 of that demonstrates using at least 3 of these methods:these methods:– StringTypeDemo2.javaStringTypeDemo2.java

Page 20: The Java String Type

2020

String MethodsString Methods

charAt(charAt(positionposition))– Returns the character in the calling String Returns the character in the calling String

object at object at positionposition– ExampleExample::

String street_address;String street_address;char spaceChar;char spaceChar;

street_address = “3141 Chestnut Street”;street_address = “3141 Chestnut Street”;

spaceChar = street_address.charAt(4);spaceChar = street_address.charAt(4);