Strings
Programming Languages · Java Basics · 12 min
Join, measure, slice and compare text.
Joining strings
Use + to glue Strings together. Java doesn't add spaces for you, so put them in yourself.
String pet = "cat";
String msg = "My " + pet; // "My cat"
Create a
Stringcalledfullthat joinsfirst, a space" ", andlast.Print
full.
Length and letters
.length() tells you how many characters a String has. .charAt(i) gives you the character at position i.
Positions start at 0, not 1: in "cat", c is at 0 and t is at 2.
String s = "cat";
s.length(); // 3
s.charAt(0); // 'c'
Print the length of
word.Print the first letter of
wordwithcharAt.
Slicing with substring
.substring(start, end) cuts out a piece of a String. It includes start but stops just before end. With only start, it goes to the end.
String s = "rainbow";
s.substring(0, 4); // "rain"
s.substring(4); // "bow"
Print
word.substring(0, 3).Print the rest of the word, from position 3 to the end.
UPPER and lower case
.toUpperCase() and .toLowerCase() give you a new String in capitals or small letters.
They don't change the original. Strings in Java never change; methods hand back a new one.
String s = "Hi";
s.toUpperCase(); // "HI"
// s is still "Hi"
Print
shoutin capitals.Then print
shoutitself, to see it didn't change.
Comparing text: equals, not ==
To check whether two Strings hold the same text, use .equals(). Don't use ==: it checks whether they're the very same object in memory, so it can say false even when the letters match.
Run the starter and see for yourself.
a.equals(b) // true if the text matches
Change the print so it uses
guess.equals(password)instead of==. It should printtrue.Below it, print
guess.equals("OPEN SESAME"). Capitals count, so it'sfalse.
Put it together: a username
Build a username from a first and last name: the first letter of the first name, then the whole last name. grace and hopper become ghopper.
Create a
Stringcalledusernamefromfirst.substring(0, 1)andlast, then print it.Print
usernamein capitals.Print how many characters
usernamehas.
More in Java Basics
Previous: Variables · Next: Conditionals