Java Strings
Explains how to declare, create, compare, and use Strings in a Java program.
Prerequisites
- Know and understand the eight Java primitive variable types, especially char and int.
- Understand Java classes, objects, and methods
Objectives
- Understand key concepts about Strings of text in Java
- Write Java code to declare, create, initialize, concatenate and output Strings
- Write Java code to determine the length of a String and retrieve a single character from a String
- Write Java code to process each character in a String
- Write Java code to compare the contents of two Strings
- Write Java code to convert a single character or an entire string to upper case or lower case
- Write Java code to find a substring within a string and to split a string into substrings
Key Concepts
- Java includes a class named
String
in the packagejava.lang
. - An object created from the
String
class contains a string of text. - Java Strings are immutable (cannot be changed after they are created).
- Strings have a
.length()
method that returns the number of characters in aString
. - Each character in a
String
is located at a specific index just like each element in an array. In fact, aString
can be thought of as an array ofchar
. - To retrieve a single
char
from aString
use the.charAt(index)
method.
Declaring a String
- Before using any variable in a Java program, including a String, you must declare that variable.
- Syntax:
String name1, name2, ..., nameN;
- Examples:
String s; String text, result;
Creating a String
- Java Strings are objects, and objects in Java must be declared and created. This is different from the Java primitive types which must be declared but not created. To create any object in Java, include a String, you can use the new
keyword
. - Syntax:
String name = new String("characters");
- Example:
String greeting = new String("Hello");
- Although you can create a String in Java using the
new
keyword, there is a shorter way. It is almost always better to use the shorter way to create a Java String. - Syntax:
String name = "characters";
- Example:
String greeting = "Hello";
String Concatenation
- The term string concatenation means to combine two or more strings together to form a longer string. The string concatenation operator in Java is the plus symbol (+).
- Example:
String firstName = getFirstName(); String greeting = "Hello " + firstName + "! How are you?"; System.out.println(greeting);
Getting the Length of a String
- Every Java String has a
.length()
method that returns the number of characters in a string. - Examples:
String greeting = "Hello"; System.out.println(greeting.length()); // Prints the number 5 String word1 = "health"; String word2 = "strength"; if (word1.length() > word2.length()) { System.out.println(word1 + " is longer than " + word2); } else if (word1.length() < word2.length()) { System.out.println(word2 + " is longer than " + word1); } else { System.out.println(word1 + " and " + word2 + " are the same length"); }
Retrieving a Character from a String
- To retrieve a single character from a string, use the
.charAt(index)
method. - Examples:
String greeting = "Good morning"; char c = greeting.charAt(3); System.out.println(c); // Prints the character 'd' // Process each character one at a time. for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); System.out.println(c); }
Comparing Strings
- In Java, Strings are objects and not primitive types, and in Java, all object variables are references to an object. This means that for all object variables there are two meanings to equality: 1) two varaibles refer to the same object, 2) the contents of two objects are the same.
- If you want the computer to check if two variables refer to the same object, use the equality operator (==).
String s = … String t = … if (s == t) { System.out.println("s and t refer to the same object."); } else { System.out.println("s and t do NOT refer to the same object.") // Even though s and t don't refer to the same object, // the contents of the two objects may still be the same. }
- If you want the computer to check if two contents of two objects are the same, use the
.equals()
method.String s = … String t = … if (s.equals(t)) { System.out.println("The contents of s and t are the same.") // Because the contents of s and t are the same, it // is possible that s and t refer to the same object. } else { System.out.println("The contents of s and t are NOT the same.") // Because the contents of s and t are NOT the same, it // is impossible that s and t refer to the same object. }
- The following code example will help you check your understanding of comparing objects with
==
and.equals()
String s = "Welcome"; String t = s; String u = new String("Welcome"); System.out.println(s == t); // Prints true System.out.println(s == u); // Prints false System.out.println(s.equals(t)); // Prints true System.out.println(s.equals(u)); // Prints true
- You can use the four other comparison operators (<, <=, >, >=) with strings. If String a is less than String b, then the contents of String a would come before the contents of String b in alphabetical order.
String a = "renew"; String b = "cheer"; System.out.println(a < b); // Prints false System.out.println(a <= b); // Prints false System.out.println(a > b); // Prints true System.out.println(a >= b); // Prints true
Other String Methods
There are many other useful String methods, including the following:
- .indexOf()
- .lastIndexOf()
- .isEmpty()
- .repeat()
- .replace()
- .split()
- .startsWith()
- .endsWith
- .strip()
- .substring()
- .toLowerCase()
- .toUpperCase()