Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

CMP 202- COMPUTER PROGRAMMING

II
LECTURE SERIES
OVERVIEW OF THE COURSE OUTLINE
Principles of Good programming
Structured programming concepts
Errors and Debugging
Testing
Text Files and IO
Strings Processing
Strings Processing
• What is a String?
• A String is a sequence of characters enclosed in double quotes such as
“Salaam Alaikum””. Typically, “A” is a string but ‘A’ is a character. String
processing is a very frequent application. Thus, Java provides special
support for strings. A string is an instance of Java’s built in String class.

• How to create a string object?


• Strings are objects. Like any object, a string object can be created in
two ways as follows:
• By string literal
• By new keyword
Creating String Object by String Literal
• Java String literal is created by using double quotes. For Example:
String s="Salaam Shabaab";
• Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool. For
example:
String s1="Welcome";

String s2="Welcome";//It doesn't create a new instance


• Note: String objects are stored in a special memory area known as the
"string constant pool".
Creating String Object by new keyword

• Java String can also be created by using the new operator as in:
String greeting = new String(“Salaam Shabaab”);
//creates two objects and one reference variable
• In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Salaam Shabaab" will be placed in the string constant
pool. The variable greeting will refer to the object in a heap (non-pool).
Internal Representation of Strings
• Internally, String objects are represented as a sequence of characters
indexed from 0. For example, the string object created by the statement:
String greeting = “Salaam Shabaab”; is represented as follows:

Many string methods return results based on this indexing:


char charAt(int index) Returns the char value for the particular index
• For example, the statement:
char letter = greeting.charAt(5);
• stores the character ‘m’ in the character variable letter.
---- Internal Representation of Strings
We can also ask a string object its length by calling its length()
method:
int length() Returns the length of this string.

• For example, the statement:


int charCount = greeting.length();
• stores 14 in the integer variable charCount.
Getting Substring from a String
A common operation on Strings is extracting a substring from a given string.
String substring(int start) Returns the substring from start to the end of the string
String substring(int start, int end) Returns the substring from start to end but not
including the character at end.

For example, the statement:


String sub2 = greeting.substring(7)
• Creates the substring “Shabaab” that is referred to by sub2.

• For example, the statement:


String sub1 = greeting.substring(0, 6);
• Creates the substring “Salaam” that is referred to by sub1.
Concatenating Strings
• Concatenation means joining two or more strings together. Java
allows two strings to be concatenated using the ‘+’ operator.
• For Example:
String firstName = “Amr”;
String lastName = “Al-Ibrahim”;
String fullName = lastName+” “+firstName;
fullName “Al-Ibrahim Amr”

• If one of the operands in an expression a string, Java automatically


converts the other to a string and concatenates them.
• For Example:
String course = “CMP”;
int code = 202;
------ Concatenating Strings
• We frequently use the concatenation operator in println statements:
System.out.println(“The area =“+area);
• You need to be careful with concatenation operator. For example, what is the output of the
following statement?
System.out.println(“Sum =“+5+6);
• Example: The two strings can also be join in Java using the concat() method as follows:
Comparing Strings
• Strings are compared by comparing their characters left to right. Unicode codes
are used in the comparison.
• Note that lowercase letters are different from uppercase letters.
• The String class has the following methods for checking whether two strings are
equal:
Comparing Strings
The following table shows some examples of applying these methods. Assuming
the following declarations:
String s1 = “Salaam”;
String s2 = “Shabaab”;
String s3 = “SALAAM”;

Exercise: What is the result of s1.equalsIgnoreCase(s3) ?


Comparing Strings
Sometimes we need to know if a string is less than another. Accordingly, the
String class has the following additional comparison methods:
Comparing Strings
• Assuming the following declarations:
String s1 = “Salaam”;
String s2 = “Shabaab”;
String s3 = “SALAAM”;
• We have:

• Execercise: What is the result of s1.compareToIgnoreCase(s3)?


Comparing Strings
• Example: Consider the following program that compares 3 strings as follows
Finding the index of a character or substring
The following methods return an index given a character or substring:
Finding the index of a character or substring
Example 1: The program below finds the index of some strings
Finding the index of a character or substring
Example 2: The program below finds the substring of the “0123456789”string
Case conversion and Trimming of Strings
It can be useful to convert a string to upper or lower case

• For example, the statements:


String greeting = “Salaam Shabaab”;
String greeting2 = greeting.toUpperCase();
• Create two string objects. The object referenced by greeting2 stores “SALAAM
SHABAAB”
Case conversion and Trimming of Strings
• Example: The following program change “ABCDEF” to lower case

• Another useful method of String is trim():

• For example, the statement:


String s = “ Salaam “.trim();

Stores “Salaam” in the string referenced by s.


Case conversion and Trimming of Strings
• Note that, return ‘\r’, tab ‘\t’, new line ‘\n’ and space ‘ ’ are all white space
characters.
• All the methods of the String class can also be applied to anonymous string
objects (also called string literals) as shown in the above example.

• Example: This program returns a string whereby any leading and trailing
whitespaces will be removed.
Replace method in Strings
• Another useful String method is also replace() which replaces occurrences of
character with a specified new character.

• Example: Write a program that replaces ‘m’ and ‘M’.


Strings are Immutable!
• Another special feature of Strings is that they are immutable. That is, once a
string object is created, its content cannot be changed.
• Thus, all methods that appear to be modifying string objects are actually
creating and returning new string objects.
• For example, consider the following:
Strings are Immutable!
Instead of changing the greeting object, another object is created. The former is
garbage collected.

The fact that Strings are immutable makes string processing very efficiently in
Java.
More String Methods
We have discussed some of the most important methods of the string class.
For a complete list, check the Java SDK documentation.

You might also like