IB Computer Science Unit 1
IB Computer Science Unit 2
IB Computer Science Unit 3
IB Computer Science Unit 4
IB Computer Science Unit 5
IB Computer Science Unit 6

IB Computer Science Strings and Characters in Java

IB Computer Science Learning Goals

In this IB Computer Science lesson you will be learning about:

  • How to use String and character values in a program

String Basics

A String is not a basic data type, it is an object of the String Class, sometimes we just treat it as a primitive data type. Since it is an object it has methods that let the programmer manipulate strings in different ways. You have already used one of those methods (The equals method to compare two strings together)

A string is a collection of characters

Each string has a length (The number of characters in a String)

“Hello” has a length of 5
“Come on down” has a length of 12

Each character in the String has an index number

The first letter in a string is always given the index 0

The last index number of the string is always 1 less than the length of the string

Strings can be created in one of two ways in Java
String name = “Mr. Rogers”;
String name2 = new String(“Mr. Rogers”);

There is an internal difference on how Java is handling these statements that is very complicated. You usually won’t see any weird things going on if you stick to the first Method. The second method uses standard object creation format, which we will learn about later and can give you unexpected results especially when comparing Strings together.

Back in the previous notes you were told to compare Strings using the .equals method. This is because Strings are objects. It is NOT advised to use == when comparing Strings together.

Character Basics

A char value in java is really represented by an integer, thus each character has an associated integer value. The integer value associated with the character is based upon a code, in particular an ASCII code, part of which is shown below

IB Computer Science ASCII Table

Example:

The integer value of the character ‘A’ is 65, The integer value of the character ‘Z’ is 90
The integer value of the character ‘a’ is 97, The integer value of the character ‘z’ is 122

Comparing characters is done based on their integer representation. Does the following comparison return a true or false?

‘b’ < ‘e’ is True since 98 is less than 101

You can convert an integer into a character by typecasting. The following example would store the character ‘x’ in the variable letter

char letter = (char)120;

You can convert a character into its integer value by typecasting. The following example would store the value 120 in the variable num

int num = (int)’x’;

Useful String Methods

Just google “Java String Class”, to see all the methods that can be used with a String object.

Length Methods

The method int length () returns the number of characters in a the calling String s1

len = s1.length()

Comparison Methods

You have learned how to test if two strings are equal to each other using the boolean equals (String s) method, which takes into account the case of the characters in the two strings. Returns a true or false value.

s1.equals (s2)

The method boolean equalsIgnoreCase (String s) compares equality between two strings without taking into the case of the characters in the two strings. Returns a true or false value.

s1.equalsIgnoreCase (s2)

The method boolean compareTo (String s) compares strings alphabetically taking into consideration the case of the characters in the two strings.

s1.compareTo (s2)

The method boolean compareToIgnoreCase (String s) compares strings alphabetically taking into consideration the case of the characters in the two strings

s1.compareToIgnoreCase (s2)

Both compareTo and compareToIgnoreCase return an integer value
▪ returns a 0 if the two strings are alphabetically equal
▪ returns a negative number if s1 is alphabetically before s2
▪ returns a positive number if s1 is alphabetically after s2

The method boolean startsWith (String s) returns true if the calling string starts with the specified substring s

s1.startsWith (s)

The method boolean startsWith (String s, int offset) returns true if the calling string starts with the specified substring s starting from the index offset

s1.startsWith (s, #)

The method boolean endsWith (String s) returns true if the calling string ends with the specified substring s

s1.endsWith (s)

Conversion Methods

Sometimes it is useful for a string to be modified in some manner. You cannot change the original string object with any of the methods outlined below, but they will create a new string or array that you can use to overwrite the original if need be.

The method String copyValueOf (char data ) returns a new String the represents the characters in the character array data.
String s1 = String.copyValueOf (charArray );

The method String copyValueOf (char data, int start, int stop) returns a new String the represents the characters in the character array data starting at position start and ending at position stop

s1 = String.copyValueOf (charArray );

The method String toLowerCase ( ) returns a new String with all the characters of the original string in lower case. The original string is not altered.

s2 = s1.toLowerCase ( );

The method String toUpperCase ( ) returns a new String with all the character of the original string in upper case. The original string is not altered.
s2 = s1.toUpperCase ( );

The method String replace (char oldChar, char newChar) returns a new string resulting from replacing all occurrences of oldChar in the original string with newChar. The original string is not altered

s2 = s1.replace(old,new);

The method String replaceAll (String s, String r) returns a new string resulting from replacing all occurrences of the substring s in the original string with the substring r. The original string is not altered

s2 = s1.replaceAll (s,r);

The method String replaceFirst(String s, String r) returns a new string resulting from replacing the first occurrence of the substring s in the original string with the substring r. The original string is not altered

s2 = s1.replaceFirst (s,r);

 

Index Methods

There are several methods in the String class that will return the index of a particular character or substring within another string

The method int indexOf (char ch) returns the index within the string of the first occurrence of the character ch.

location = s1.indexOf (‘A’);

The method int indexOf (char ch, int fromIndex) returns the index within the string of the first occurrence of the character ch after the index value fromIndex.

location = s1.indexOf (‘A’, 4);

The method int indexOf (String s) returns the index within the string of the first occurrence of the substring s.

location = s1.indexOf (“ell”);

The method int indexOf (String s, int fromIndex) returns the index within the string of the first occurrence of the substring s after the index value fromIndex.

location = s1.indexOf (“ell”, 4);

The method int lastIndexOf (char ch) returns the index within the string of the first occurrence of the character ch.

location = s1.lastIndexOf (‘A’);

The method int lastIndexOf (char ch, int fromIndex) returns the index within the string of the last occurrence of the character ch after the index value fromIndex.

location = s1. lastIndexOf (‘A’, 4);

The method int lastIndexOf (String s) returns the index within the string of the last occurrence of the substring s.

location = s1. lastIndexOf (“ell”);

The method int lastIndexOf (String s, int fromIndex) returns the index within the string of the last occurrence of the substring s after the index value fromIndex.

location = s1. lastIndexOf (“ell”, 4);

Substring Methods

There are several methods in the String class that will return part of a particular string

The char charAt (int index ) method returns the specific character at the specified index

c = s1.charAt (3);

The String substring (int start) method returns a segment of the string from index start to the end of the string

s2 = s1.substring (3);

The String substring (int start, int stop) method returns a segment of the string from index start to index stop – 1

s2 = s1.substring (1,5);

Examples

Length of a String Example

IB Computer Science Java Length of String

CharAt Example:

Accepts an integer argument representing the index number of a string.  Returns the character representing the given index .  

Loops Example

Write a program that will ask the user for an integer. The program will then print out that many characters from the string “Wow, Java programming is really fun and exciting”. If the user enters a number bigger than the length of the string then display an appropriate message

Loops Example

The students of your class are to be subdivided into 3 teams according to their first name. Names starting with A – I belong to team 1. Names starting with J – P belong to team 2. Names starting with Q – Z belong to team 3. Write a program that lets you enter 5 names and that will print out which team they belong to. Enter names in all capital letters.

IB Computer Science More Strings and Loops

String Concatenation Example

You can create new String from other Strings or from characters using the addition operator +

String Parsing Example

Parsing refers to extracting different parts of information from a single String. For example, suppose you had a String, time, that contains a time such as “9:23AM” or “12:45PM”. Let’s say you wanted to extract the hour, minute, and AM or PM from that String

IB Computer Science String Parsing Substrings

IB Computer Science Practice Questions

1. Write a program that allows the user to enter a sentence. Ask the user for a range of numbers and then display all the characters between that range in the sentence.

2. Ask the user for one letter at a time. For each new letter add it to the previous and build a word. Output the word as they are building it. Stop when they enter a period.

IB Computer Science String Building Java

3. Write a program that asks the user to enter a sentence and a letter.
a. Output how many times that program appears in the sentence.
b. Output the location in the sentence of the last occurrence of that letter? First occurrence?

4. Write a program that asks for a word. Output the sentence in an increasing sequence of letters and a decreasing sequence of letters

IB Computer Science Java String Wedge

5. Repeat the above question but put dashes between the letters (No Dash at the end of the word)

6. Write a program that asks the user for a word and outputs if it is a palindrome

7. Write a program that gets any number from the user and displays the sum of the digits. The number can be any size…. Even a really really really big number like 383973917398473849832973984932749749280503277234892383

Looking to Learn More about Computer Science and Coding?

Check out our programing in python courses that focus on high school level coding.  

  • Grade 11 Computer Science ICS3U
  • Grade 12 Computer Science ICS4U

These courses are complete with interactive coding lessons, teacher led videos, and more practice questions with complete solutions

Return To International Baccalaureate Computer Science Main Page