The String class in Java is designed to work with strings in Java. All string literals defined in a Java program (for example, "abc") are instances of the String class. Let's look at its key characteristics:
- The class implements the
Serializable
and interfacesCharSequence
. Since it is included in the packagejava.lang
, it does not need to be imported. - The String class in Java is a final class and cannot have children.
- The String class is an immutable class, meaning its objects cannot be changed after they are created. Any operations on a String object that would result in an object of the String class will result in the creation of a new object.
- Due to their immutability, String class objects are thread safe and can be used in a multi-threaded environment.
- Every object in Java can be converted to a string through a method
toString
that all Java classes inherit from the classObject
.
Working with Java String
This is one of the most commonly used classes in Java. It has methods for analyzing certain characters in a string, for comparing and searching strings, extracting substrings, creating a copy of a string with all characters converted to lower and upper case, and others. A list of all methods of the String class can be found in the official documentation . Java also implements a simple mechanism for concatenation (connecting strings), converting primitives into a string and vice versa. Let's look at some examples of working with the String class in Java.Creating Strings
The easiest way to create an instance of the String class is to assign it the value of a string literal:String s = "I love movies";
However, the String class has many constructors that allow you to:
- create an object containing an empty string
- create a copy of a string variable
- create a string based on a character array
- create a string based on a byte array (taking into account encodings)
- etc.
String addition
Adding two strings in Java is quite simple using the+
. Java allows you to add both variables and string literals to each other:
public static void main(String[] args) {
String day = "Day";
String and = "And";
String night = "Night";
String dayAndNight = day + " " + and + " " + night;
}
By adding objects of the String class with objects of other classes, we reduce the latter to string form. Conversion of objects of other classes to a string representation is performed through an implicit method call toString
on the object. Let's demonstrate this with the following example:
public class StringExamples {
public static void main(String[] args) {
Human max = new Human("Max");
String out = "java object: " + max;
System.out.println(out);
// Output: Java object: Person named Max
}
static class Human {
private String name;
public Human(String name) {
this.name = name;
}
@Override
public String toString() {
return "The Man with the Name" + name;
}
}
}
String comparison
To compare strings, you can use the methodequals()
:
public static void main(String[] args) {
String x = "Test String";
System.out.println("Test String".equals(x)); // true
}
When case is not important to us when comparing strings, we need to use the method equalsIgnoreCase()
:
public static void main(String[] args) {
String x = "Test String";
System.out.println("test string".equalsIgnoreCase(x)); // true
}
Converting an object/primitive to a string
To convert an instance of any Java class or any primitive data type to a string representation, you can use the methodString.valueOf()
:
public class StringExamples {
public static void main(String[] args) {
String a = String.valueOf(1);
String b = String.valueOf(12.0D);
String c = String.valueOf(123.4F);
String d = String.valueOf(123456L);
String s = String.valueOf(true);
String human = String.valueOf(new Human("Alex"));
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(s);
System.out.println(human);
/*
Output:
1
12.0
123.4
123456
true
Person named Alex
*/
}
static class Human {
private String name;
public Human(String name) {
this.name = name;
}
@Override
public String toString() {
return "The Man with the Name" + name;
}
}
}
Converting a string to a number
Often you need to convert a string to a number. Primitive type wrapper classes have methods that serve exactly this purpose. All of these methods begin with the word parse. Consider the translation of a string into integer (Integer
) and fractional ( Double
) numbers below:
public static void main(String[] args) {
Integer i = Integer.parseInt("12");
Double d = Double.parseDouble("12.65D");
System.out.println(i); // 12
System.out.println(d); // 12.65
}
Converting a collection of strings to a string representation
If you need to convert all the elements of some collection of strings to a string representation through an arbitrary delimiter, you can use the following methods of the Java String class:join(CharSequence delimiter, CharSequence... elements)
join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
delimiter
is the element separator, and elements
is a string array / string collection instance. Let's look at an example where we convert a list of strings to a string, separating each with a semicolon:
public static void main(String[] args) {
List<String> people = Arrays.asList(
"Philip J. Fry",
"Turanga Leela",
"Bender Bending Rodriguez",
"Hubert Farnsworth",
"Hermes Conrad",
"John D. Zoidberg",
"Amy Wong"
);
String peopleString = String.join("; ", people);
System.out.println(peopleString);
/*
Output:
Philip J. Fry; Turanga Leela; Bender Bending Rodriguez; Hubert Farnsworth; Hermes Conrad; John D. Zoidberg; Amy Wong
*/
}
Splitting a string into an array of strings
This operation is performed by the methodsplit(String regex)
The separator is a string regular expression regex
. In the example below, we will perform the opposite operation to what we performed in the previous example:
public static void main(String[] args) {
String people = "Philip J. Fry; Turanga Leela; Bender Bending Rodriguez; Hubert Farnsworth; Hermes Conrad; John D. Zoidberg; Amy Wong";
String[] peopleArray = people.split("; ");
for (String human : peopleArray) {
System.out.println(human);
}
/*
Output:
Philip J. Fry
Turanga Leela
Bender Bending Rodriguez
Hubert Farnsworth
Hermes Conrad
John D. Zoidberg
Amy Wong
*/
}
Determining the position of an element in a line
In the Java language, String provides a set of methods to determine the position of a character/substring in a string:indexOf(int ch)
indexOf(int ch, int fromIndex)
indexOf(String str)
indexOf(String str, int fromIndex)
lastIndexOf(int ch)
lastIndexOf(int ch, int fromIndex)
lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
ch
— the symbol you are looking for (char
)str
- search stringfromIndex
— the position from which to search for the element- methods
indexOf
- return the position of the first element found - methods
lastIndexOf
- return the position of the last element found
A
, K
, Z
, Я
in the English alphabet, but keep in mind that the indexing of characters in a string in Java starts from zero:
public static void main(String[] args) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(alphabet.indexOf('A')); // 0
System.out.println(alphabet.indexOf('K')); // 10
System.out.println(alphabet.indexOf('Z')); // 25
System.out.println(alphabet.indexOf('Я')); // -1
}
Extracting a substring from a string
To extract a substring from a string, the String class in Java provides methods:substring(int beginIndex)
substring(int beginIndex, int endIndex)
public static void main(String[] args) {
String filePath = "D:\\Movies\\Futurama.mp4";
int lastFileSeparatorIndex = filePath.lastIndexOf('\\');
String fileName = filePath.substring(lastFileSeparatorIndex + 1);
System.out.println(fileName); //9
}
Convert string to upper/lower case:
The String class provides methods for converting a string to upper and lower case:toLowerCase()
toUpperCase()
public static void main(String[] args) {
String fry = "Philip J. Fry";
String lowerCaseFry = fry.toLowerCase();
String upperCaseFry = fry.toUpperCase();
System.out.println(lowerCaseFry); // philip j. fry
System.out.println(upperCaseFry); // PHILIP J. FRY
}
Working with this Java class is studied at the initial levels of the JavaRush online course:
- An introduction to String is given at level 1, lecture 4 of the Java Syntax quest
- The internal structure of String, the substring method are studied at the 2nd level, 3rd lecture of the Java Multithreading quest
- Finding, getting, deleting a substring in a String is studied at the 2nd level, 4th lecture of the Java Multithreading quest
- The String.format method is covered at level 2, lecture 6 of the Java Multithreading quest
Additional sources
Information about the String class is also provided in other articles in the JavaRush community:- Strings in Java - This article covers some basics on working with strings in Java.
- Java String. Interview questions and answers, part 1 - this article discusses interview questions on the topic
String
, and also provides answers to questions with explanations and code examples. - Strings in Java (class java.lang.String) - this article provides a deeper analysis of the String class, and also discusses the intricacies of working with this class.
GO TO FULL VERSION