Working with Strings

Java's way of handling text

7 min read

A String in Java is a sequence of characters, essentially any piece of text, wrapped in double quotes. Names, sentences, messages, and even single letters can all be stored as Strings.

String greeting = "Hello there";
String city = "London";

Joining strings together

You can combine, or concatenate, Strings using the plus sign:

String firstName = "Sam";
String lastName = "Lee";
String fullName = firstName + " " + lastName;
System.out.println(fullName);

That code would print Sam Lee to the screen. Notice the small String containing just a space in the middle, which keeps the two names from running together.

You can even mix Strings with numbers using the plus sign, and Java will automatically turn the number into text for you:

int age = 16;
System.out.println("I am " + age + " years old");

A few handy String tools

  • fullName.length() tells you how many characters are in the String
  • fullName.toUpperCase() returns the text in all capital letters
  • fullName.toLowerCase() returns the text in all lowercase letters

These little built in tools are called methods, and Strings come packed with useful ones. You do not need to memorize them all today, just know that they exist and that you can look them up whenever you need them.

Careful: If you need a double quote character inside a String itself, you have to tell Java it is part of the text rather than the end of the String. That is a small detail you will run into eventually, but it will not slow you down while you are learning the basics.

Strings show up in almost every Java program you will ever write, from simple greetings to entire web pages, so getting comfortable with them now will pay off quickly.

Quick check

Q1 Which symbol is used to join, or concatenate, two Strings in Java?

Q2 What does fullName.length() tell you?

Want to save your progress? It's free.

Create a free account