Download presentation
Presentation is loading. Please wait.
2
Introduction to Computers and Programming Strings Professor: Evan Korth New York University
3
Road map Strings –String variables –Concatenation –length() –charAt() –Strings and methods
4
review What does scope refer to in Java? What is method overloading? What does it mean when we say "pass by value"?
5
Characters and Strings We have studied the char data type with can hold one character. The String is another data type (it is actually a Class) we can use in Java. –A String is a series of chars. –We can treat the series as one unit –There are methods in the Java API we can use on strings –We can pass Strings to methods and return Strings from methods.
6
String variables String variables are unlike other variables we have used in this class. String variables are called reference variables because they hold a reference to where the string is stored in memory. –The rest of the variables we discussed in this class are called primitive variables Java hides the details from us. Example: String s = "A string of characters";
7
String concatenation In Java, we can add two Strings together using the + operator. That process is called concatenation. The following statements: String s1 = "This looks "; String s2 = "familiar"; String s3 = s1 + s2; assigns the String "This looks familiar" to the variable s3.
8
String's charAt() method String also has a method called charAt() which can be used to return any single character in a String. –Note: The first letter in a string is considered to be in position zero. For example, if we have: –String s = "Hello"; –s.charAt (0) will return 'H' –s.charAt (4) will return 'o' –s.charAt (5) will return StringIndexOutOfBoundsException
9
String's length() method All Strings know their own length. To find out the length of a string, we use String's length() method. For example: String s = "Hello"; int length = s.length(); Will place the value 5 in variable length.
10
Passing Strings to methods We can also pass a string to a method by using String types in a parameter list. For example, the following method header would represent a method which accepts a String as a parameter and does not return a value: public static void printVertical (String s)
11
Returning Strings from methods It is possible to write a method that creates and returns a String. For example, the following method header would represent a method which accepts no parameters and returns a String: –public static String getMonth(int month)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.