First Steps in Java — Part 5
Strings
1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input | 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays
After spending some time with numbers in our last lesson, today’s focus is on strings. A string is a collection of characters that are enclosed in double quotation marks, it can be any character that can be printed on the screen, i.e. letters, numbers, symbols, punctuation marks, etc.
Java strings are objects. They are of the data type String.
Since String is a data type, there exists a class String, which is built into the library java.lang and does not to be imported. This class offers many methods for handling strings.
Strings are immutable.
To change a string in some way, you have to assign it to a new string, i.e. make a copy of it.
The Backslash with Strings
If you want to add double or single quotation marks within a string, they need to be distinguished from the outer double quotation marks that define the start and endpoint of a string. The backslash ‘\’ allows to escape the string and add a separated quotation mark, as demonstrated in this example: “Bob said: \“Joe said \’Hello!\’\” ”
.
With a backslash you can also escape: \b
backspace
\t
tab
\0
empty space (Null)
\n
newline
\r
carriage return
\\
backslash
The class String offers some methods for string modification. We look at a few of them. Create a new file called Strings.java and code along with the examples.
Concatenate
We can combine two strings into one. For this merge, we use the +
operator.String greeting = “Hello!”;
String question = “How are you?”;
String greet = greeting + “ ” + question;
Note: if you concatenate a string with a number, the number will be automatically converted into a string.
code:
int number = 8;String greetEight = 8 +", " + question;
10 will be converted into a string before concatenation
Check for Equality
Compare two strings with equals(). It returns false/true. String one = “Hello“;
//returns false
String two = “hello“;
one.equals(two);
code:
compare the string greeting with the string question.
Split
Use split() to separate a string according to a pattern into an array of split-elements. String offerCoffee = “Do you want a coffee?“;
String[] offerCoffeeArray = offerCoffee.split(" ");
Returns an array of type String with the name txtArray with two elements. Consider that the array is zero-indexed. offerCoffeeArray[0];
// returns “Do“;
offerCoffeeArray[1];
// returns “you“;
…offerCoffeeArray[4];
// returns “coffee?“;
To split every single word, use a whitespace as an argument (“ ”), to split every character, use no space (“).
Create a substring
Extract a substring from the existing string. This method can be used with either one or two parameters.String longestWord = “pneumonoultramicroscopicsilicovolcanoconiosis”;
One Argument
Set the starting point of the substring by selecting the index number. Consider that Java is zero-based. String endOfWord = longestWord.substring(30);
Output : volcanoconiosis
Two arguments
Set the start and endpoint of the substring. Note that arrays in Java are zero-indexed and that the end-point is not included. String partOfWord = longestWord.substring(8, 24);
Output : ultramicroscopic
Convert To Upper Case Letters
For converting a string into upper case letters, the class String offers the method toUpperCase(). Apply the method on the string object. String upperCase = longestWord.toUpperCase();
Convert To Lower Case Letters
For converting a string to lower case letters only, use the toLowerCase().String lowerCase = longestWord.toLowerCase();
Length of A String
Get the length of a string as a return from the method length().int lengthString = longestWord.length();
Trim Whitespace
Delete whitespaces at the beginning and the end of the string with the method trim().String needsToBeTrimmed = “ text “;
String trimmed = needsToBeTrimmed.trim() ;
The string class contains many more useful methods, go to https://docs.oracle.com/javase/9/docs/api/java/lang/String.html and check it out. For example: charAt(), concat(), startsWith(), endsWith(), hashCode(), indexOf(), replace(), etc.
Get the code for this lesson at GitHub.
Tomorrow, we dive into conditionals. So long.