Lesson Overview

Welcome! In this lesson, we'll delve into the basic string manipulation features of Java, which include string tokenization, string concatenation, trimming of whitespace from strings, and type conversion operations.

Tokenizing a String in Java

In Java, we can use the split method from the String class or the StringTokenizer class to tokenize a string, essentially splitting it into smaller parts or 'tokens'.

Using split method:

class Solution {
    public static void main(String[] args) {
        String sentence = "Java is an amazing language!";
        String[] tokens = sentence.split(" ");
        
        for (String token : tokens) {
            System.out.println(token);
        }
    }
}

In the example above, we use a space as a delimiter to split the sentence into words. This operation will print each word in the sentence on a new line.

Using StringTokenizer:

import java.util.StringTokenizer;

class Solution {
    public static void main(String[] args) {
        String sentence = "Java is an amazing language!";
        StringTokenizer tokenizer = new StringTokenizer(sentence, " ");
        
        while (tokenizer.hasMoreTokens()) {
            System.out.println(tokenizer.nextToken());
        }
    }
}

In the example above, StringTokenizer is used to split the sentence into tokens using space as the delimiter.

Exploring String Concatenation

In Java, the + operator, the StringBuilder.append method, or streams can be used to concatenate strings into a larger string:

Using the + Operator:

class Solution {
    public static void main(String[] args) {
        String str1 = "Hello,";
        String str2 = " World!";
        String greeting = str1 + str2;
        System.out.println(greeting);  // Output: "Hello, World!"
    }
}

Using StringBuilder.append:

class Solution {
    public static void main(String[] args) {
        String str1 = "Hello,";
        String str2 = " World!";
        StringBuilder sb = new StringBuilder(str1);
        sb.append(str2);
        System.out.println(sb.toString());  // Output: "Hello, World!"
    }
}

Using Streams (Java 8+):

Streams in Java provide a powerful way to perform operations on collections, such as filtering, mapping, and reducing. In this context, we can use streams to concatenate strings in an ArrayList. Here’s how:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<>(Arrays.asList("Hello", " World!", " Java", " Streams!"));
        String result = strings.stream().collect(Collectors.joining());
        System.out.println(result);  // Output: "Hello World! Java Streams!"
    }
}

In the example above:

  1. ArrayList Initialization: We initialize an ArrayList with several strings.
  2. Creating a Stream: We call the stream() method on the ArrayList to create a stream of its elements. It converts the collection into a sequence of elements that supports various methods to perform computations.
  3. Collecting the Stream: We use the Collectors.joining() method to concatenate all the elements of the stream into a single string. The Collectors.joining() method can also take an optional delimiter as an argument if you need to insert characters (like commas or spaces) between the elements.
Trimming Whitespaces from Strings

In Java, the trim method can remove both leading and trailing whitespaces from a string:

class Solution {
    public static void main(String[] args) {
        String str = "    Hello, World!    "; // string with leading and trailing spaces
        str = str.trim(); // remove leading and trailing spaces
        System.out.println(str); // Output: "Hello, World!"
    }
}

In this example, trim is used to remove leading and trailing whitespaces from a string.

Java Type Conversions

We can convert strings to numbers using methods like Integer.parseInt (string to integer) and Float.parseFloat (string to float), and other data types to strings using String.valueOf:

class Solution {
    public static void main(String[] args) {
        String numStr = "123";
        int num = Integer.parseInt(numStr);
        System.out.println(num);  // Output: 123

        String floatStr = "3.14";
        float pi = Float.parseFloat(floatStr);
        System.out.println(pi);  // Output: 3.14

        int age = 20;
        String ageStr = String.valueOf(age);
        System.out.println("I am " + ageStr + " years old."); // Output: I am 20 years old.
    }
}

In this code, we use Integer.parseInt, Float.parseFloat, and String.valueOf for type conversions.

Integrating String Tokenization and Type Conversions

In some cases, we may need to combine all the methods discussed:

class Solution {
    public static void main(String[] args) {
        String numbers = "1,2,3,4,6";
        String[] numArray = numbers.split(",");
        int sum = 0;
        
        for (String numStr : numArray) {
            sum += Integer.parseInt(numStr);
        }
        
        float average = (float) sum / numArray.length;
        System.out.println("The average is " + average);  // Output: The average is 3.2
    }
}

By integrating these methods, we can transform the string "1,2,3,4,6" into an array of integers, calculate their average, and display the result.

Quick Recap and Next Steps

Great job! You've gained an overview of Java's string manipulation features, including string concatenation, string tokenization, trimming whitespace from strings, and type conversions. Now, it's time to get hands-on with these concepts in the exercises that follow. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal