Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Strings of characters

In this section, we take a closer look at strings of characters in Java, which are called Strings. We have already used variables of String type when printing, and learned how to compare Strings. Comparing two strings is performed by calling the equals() method of the string.

String animal = "Dog";

if( animal.equals("Dog") ) {
    System.out.println(animal + " says bow-wow");
} else if ( animal.equals("Cat") ) {
    System.out.println(cat + " says meow meow");
}

It is possible to ask the string how many characters long it is by writing .length() after it’s name. In other words, we are calling its length() method.

String banana = "banana";
String cucumber = "cucumber";
String together = banana + cucumber;

System.out.println("The length of banana is " + banana.length());
System.out.println("The length of  cucumber is " + cucumber.length());
System.out.println("The word " + together + " length is " + together.length());

In the above code, the method length() is called for three different strings. The call banana.length() calls only the method that gives the length of the string banana, while cucumber.length() calls the method that gives the length of the string cucumber etc. The left part before the dot says whose method is called.

Java has a special data type, called char, to be used for characters. A char variable can store only one character. A string variable can return a character from a specific location in itself with the method charAt() that uses the index of the location as a parameter. Note that counting the index of the character starts from zero!

String word = "Supercalifragilisticexpialidocious";

char character = word.charAt(3);
System.out.println("The 4th character of the word is " + character); //prints "e"

The characters in a string are numbered (indexed) starting from 0. This means that we can reach the last character in a string with number (or index) “the length of the word minus one”, or word.charAt(word.length()-1). The following example will make the program crash, because we are trying to get a character from an index that does not exist.

char character = word.charAt(word.length());

Exercise string-1: The length of a name

Create a program that asks for the user’s name and says how many characters the name contains.

Type your name: ~~Paul~~
Number of characters: 4
Type your name: ~~Catherine~~
Number of characters: 9

Note! Your program should be structured so that you put the calculating of the name length in it’s own method: public static int calculateCharacters(String text). The tests will be testing both the method calculateCharacters and the program overall.

Exercise string-2: First character

Create a program that asks for the user’s name and gives the first character.

Type your name: ~~Paul~~
First character: P
Type your name: ~~Catherine~~
First character: C

Note! Your program should be structured so that you put the search for the first character in its own method: public static char firstCharacter(String text). The tests will be testing both the method firstCharacter and the program overall

Exercise string-3: Last character

Create a program that asks for the user’s name and gives the last character.

Type your name: Paul
Last character: l
Type your name: Catherine
Last character: e

Note! Your program should be structured so that you put the search for the last character in its own method: public static char lastCharacter(String text). The tests will be testing both the method lastCharacter and the program overall.

Exercise string-4: Separating first characters

Create a program that asks for the user’s name and gives its first, second and third characters separately. If the name length is less than three, the program prints nothing. You do not need to create methods in this exercise.

Type your name: ~~Paul~~
1. character: P
2. character: a
3. character: u
Type your name: ~~me~~

Note: watch closely at the output in this and the following exercise. The print needs to contain a space after the dot and the colon!

Exercise string-5: Separating characters

Create a program that asks for the user’s name and gives its characters separately. You do not need to create methods in this exercise.

Type your name: ~~Paul~~
1. character: P
2. character: a
3. character: u
4. character: l

Hint: using a while loop helps in this exercise!

Type your name: ~~Catherine~~
1. character: C
2. character: a
3. character: t
4. character: h
5. character: e
6. character: r
7. character: i
8. character: n
9. character: e

Exercise string-6: Reversing a name

Create a program that asks for the user’s name and prints it in reverse order. You do not need to create a separate method for this.

Type your name: ~~Paul~~
In reverse order: luaP
Type your name: ~~Catherine~~
In reverse order: enirehtaC

Hint: You can print one character using the command System.out.print()

Other methods for strings

We often want to read only a specific part of a string. A method in the String class called substring makes this possible. It can be used in two ways:

String word = "Supercalifragilisticexpialidocious";
System.out.println(word.substring(14)); //prints "listicexpialidocious"
System.out.println(word.substring(9,20)); //prints "fragilistic"

We can store the return value in a variable, because the return value of the substring method is of type String.

String book = "Mary Poppins";
String endpart = book.substring(5);
System.out.println("Harry " + endpart); // prints "Harry Poppins"

Methods in the String class also make it possible to search for a specific word in text. For example, the word “or” can be found in the word “Horse”. A method called indexOf() searches for the word given as a parameter in a string. If the word is found, it returns the starting index (location), remember that the numbering starts from 0 of the word. If the word is not found, the method returns the value -1.

String word = "aesthetically";

int index = word.indexOf("tic"); // index value will be 6
System.out.println(word.substring(index)); //prints "tically"

index = word.indexOf("ally"); //index value will be 9
System.out.println(word.substring(index)); //prints "ally"

index = word.indexOf("book"); // string "aesthetically" does not include "book"
System.out.println(index); //prints -1
System.out.println(word.substring(index)); //error!

Exercise string-7: First part

Create a program that prints the first part of a word. The program asks the user for the word and the length of the first part. Use the substring method in your program.

Type a word: ~~example~~
Length of the first part: 4
Result: exam
Type a word: ~~example~~
Length of the first part: 6
Result: exampl

Exercise string-8: The end part

Create a program that prints the end part of a word. The program asks the user for the word and the length of the end part. Use the substring method in your program.

Type a word: ~~example~~
Length of the end part: 4
Result: mple
Type a word: ~~example~~
Length of the end part: 6
Result: xample

Exercise string-9: A word inside a word

Create a program that asks the user for two words. Then the program tells if the second word is included in the first word. Use String method indexOf in your program.

Type the first word: ~~glitter~~
Type the second word: ~~litter~~
The word 'litter' is found in the word 'glitter'.
Type the first word: ~~glitter~~
Type the second word: ~~clean~~
The word 'clean' is not found in the word 'glitter'.

Note: Make your program outputs (prints) match exactly the example above!

Exercise string-10: Reversing text

Create the method reverse that puts the given string in reversed order. Use the following program body for the method:

public static String reverse(String text) {
    // write your code here
}

public static void main(String[] args) {
    System.out.print("Type in your text: ");
    String text = reader.nextLine();
    System.out.println("In reverse order: " + reverse(text));
}

Hint: you probably need to build the reversed string character by character in your method. You can use a String-type variable as a helper during the building process. In the beginning, the helper variable should have an empty string of characters as a value. After this, new characters are added to the string one by one.

String help = "";

// ...
// adding a character to the help variable
help = help + character;

Program output:

Type a text: ~~example~~
elpmaxe