JavaRush /Java Blog /Random EN /String class in Java

String class in Java

Published in the Random EN group
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:
  1. The class implements the Serializableand interfaces CharSequence. Since it is included in the package java.lang, it does not need to be imported.
  2. The String class in Java is a final class and cannot have children.
  3. 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.
  4. Due to their immutability, String class objects are thread safe and can be used in a multi-threaded environment.
  5. Every object in Java can be converted to a string through a method toStringthat all Java classes inherit from the class Object.
String class in Java - 1

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 toStringon 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 method equals():
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 method String.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)
Where delimiteris the element separator, and elementsis 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 method split(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:
  1. indexOf(int ch)
  2. indexOf(int ch, int fromIndex)
  3. indexOf(String str)
  4. indexOf(String str, int fromIndex)
  5. lastIndexOf(int ch)
  6. lastIndexOf(int ch, int fromIndex)
  7. lastIndexOf(String str)
  8. lastIndexOf(String str, int fromIndex)
Where:
  1. ch— the symbol you are looking for ( char)
  2. str- search string
  3. fromIndex— the position from which to search for the element
  4. methods indexOf- return the position of the first element found
  5. methods lastIndexOf- return the position of the last element found
If the element you are looking for is not found, the methods will return line -1. Let's try to find the serial number of the letters 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)
Let's look at how we can use the element positioning and substring extraction methods to get the file name from its path:
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()
Let's look at how these methods work using an example:
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:

Additional sources

Information about the String class is also provided in other articles in the JavaRush community:
  1. Strings in Java - This article covers some basics on working with strings in Java.
  2. 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.
  3. 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.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION