Java Working with Strings

A string is a sequence of characters. As programmers, we will come across many situations in which we need to deal with strings. In this unit, we will learn some of the most popular methods for dealing with strings.

1. String Class

In Java, strings are objects of a class called String. All string variables we declare are instances of the 'String' class. This String class provides a lot of methods to perform operations on strings. We will look at some of the commonly used string methods.

  • concat()

  • length()

  • charAt()

  • substring()

  • repeat()

 

2. String Concatenation

The concatenation of strings involves joining two or more strings together to create a new string In Java, we can perform string concatenation in two ways,

  1. Using string method concat()

  2. Using + operator

 

2.1 Using concat() method

The concat() method appends (concatenates) one string to the end of another string. Using this method we can concatenate only two strings.

Syntax

str1.concat(str2);

Example

class Main {

    public static void main(String[] args) {

        String str1 = "Hello ";

        String str2 = "World";

        String concatenatedString = str1.concat(str2);

 

        System.out.println(concatenatedString);

    }

}

 

Output

Hello World

 

What if we try to concatenate string with any other primitive type using concat()? Let's take an example of a string concatenation with an integer,

Example

class Main {

    public static void main(String[] args) {

        String str1 = "Hello ";

        int value = 10;

        String concatenatedString = str1.concat(value);

 

        System.out.println(concatenatedString);

    }

}

 

Output

file.java:5: error: incompatible types: int cannot be converted to String

      String concatenatedString = str1.concat(value);

                                 ^

An error will be thrown. The concat() methods expect only a single argument of string data type

 

2.2 Using + Operator

We can also use the + operator to concatenate strings. Multiple values of any primitive data type can be concatenated with a string using + operator, the resultant data type will be a string. The Java compiler automatically converts the other primitive values to strings while concatenating. We will learn more about Type Conversions later in the course.

Example

class Main {

    public static void main(String[] args) {

        String str1 = "Hello ";

        String str2 = "World ";

        int value = 3;

        String concatenatedString = str1 + str2 + value;

 

        System.out.println(concatenatedString);

    }

}

 

Output

Hello World 3

 

 

3. Length of String

Unlike Python, where you can use the built-in function len() to find the length of a string, in Java, the string object has a length() method that returns the number of characters in a given string.

Syntax

str.length();

 

Code

class Main {

    public static void main(String[] args) {

        String name = "RRTutors";

        int stringLength = name.length();

 

        System.out.println(stringLength);

    }

}

 

Output

8

 

4. String Indexing

We can access an individual character in a string using their positions (which start from 0). These positions are also called indexes. The charAt() method is used to get the character at a specified index in a string.

Syntax

str.charAt(index);

 

Example

class Main {

    public static void main(String[] args) {

        String name = "Rahul";

        char firstLetter = name.charAt(0);

 

        System.out.println(firstLetter);

    }

}

 

Output

R

 

4.1 Index Error

Attempting to use an index that is too large will result in an error:

Example

class Main {

   public static void main(String[] args) {

      String name = "Rahul";

      System.out.println(name.charAt(6));

   }

}

 

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6

 

5. String Slicing

Obtaining a part of a string is called string slicing. The substring() method can be used to access a part of the string.

Syntax

str.substring(startIndex, endIndex);

The substring begins with the character from the startIndex and extends up to endIndex-1. It means endIndex character is not included in the slice.

Example

class Main {

    public static void main(String[] args) {

        String message = "Welcome to RRtutors";

        String part = message.substring(0, 5);

 

        System.out.println(part);

    }

}

 

Output

Welco

 

5.1 Slicing to End

If the second argument is not provided (i.e., endIndex), slicing stops at the end of the string.

Example 

class Main {

    public static void main(String[] args) {

        String message = "Welcome to RRTutors";

        String part = message.substring(11);

 

        System.out.println(part);

    }

}

 

Output

RRTutors

 

6. String Repetition

The repeat() method returns a string whose value is the concatenation of the given string repeated N times. If the string is empty or the count is zero then the empty string is returned.

Syntax

str.repeat(count);

count accepts an integer that specifies how many times the string has to be repeated.

Example

class Main {

    public static void main(String[] args) {

        String str = "RRtutors";

 

        System.out.println(str.repeat(2));

    }

}

 

Output

RRtutorsRRtutors

Conclusion

String methods:

  • concat(): Used to concatenate two strings.

  • length(): Used to get the characters count of a string.

  • charAt(): Used to get the character at a specific index.

  • substring(): Used to get a slice of a string.

  • repeat(): Used to get a concatenated string repeated n times