How do I split a string into words in Java?

You can use the split() method to divide a string into smaller parts. The method accepts a regular expression that defines where to split and returns an array of strings.

In this example, you will split a sentence into words using whitespace as the separator.

Source code

Save the following code as SplitStringExample.java:

public class SplitStringExample {
    void main() {
        String text = "  Learn Java   one snippet\tat a time.  ";

        if (text.isBlank()) {
            IO.println("The text contains no words.");
            return;
        }

        String[] words = text.strip().split("\\p{javaWhitespace}+");

        for (String word : words) {
            IO.println(word);
        }

        IO.println("Total words: " + words.length);
    }
}

Explanation

The input contains spaces at both ends, multiple spaces between some words, and a tab character:

String text = "  Learn Java   one snippet\tat a time.  ";

The escape sequence \t represents a tab.

Checking for blank text

Before splitting, the program checks whether the text is empty or contains only whitespace:

if (text.isBlank()) {
    IO.println("The text contains no words.");
    return;
}

This avoids treating an empty string as a word. The return statement ends the method when there is no text to process.

Removing surrounding whitespace

The strip() method removes leading and trailing whitespace:

text.strip()

It returns a string without changing the original string, because strings are immutable.

Splitting on whitespace

The following statement splits the cleaned text:

String[] words = text.strip().split("\\p{javaWhitespace}+");

The regular expression has two parts:

Part Meaning
\p{javaWhitespace} Matches whitespace recognized by Character.isWhitespace()
+ Matches one or more consecutive whitespace characters

The backslash is written twice in the Java string literal so the regular expression receives a single backslash.

Using + treats consecutive spaces or tabs as one separator. This prevents empty elements between words when several whitespace characters appear together.

Reading the results

The enhanced for loop prints each element:

for (String word : words) {
    IO.println(word);
}

The array’s length field gives the number of resulting words.

Run the example

Compile and run the file:

javac SplitStringExample.java
java SplitStringExample

Output

Learn
Java
one
snippet
at
a
time.
Total words: 7

This example treats each whitespace-separated token as a word. Punctuation remains attached, so the last token is "time.". For language-aware word boundaries, use a text-processing tool such as BreakIterator.

How do I compare two strings in Java?

Use the equals() method to check whether two strings contain the same text. Use equalsIgnoreCase() when capitalization should not affect the comparison.

In this example, you will compare strings with identical text and strings with different capitalization.

Source code

Save the following code as StringComparisonExample.java:

public class StringComparisonExample {
    void main() {
        String first = "Java";
        String second = new String("Java");
        String third = "java";

        IO.println("Same text: " + first.equals(second));
        IO.println("Same object: " + (first == second));
        IO.println("Same case-sensitive text: " + first.equals(third));
        IO.println("Same text ignoring case: "
                + first.equalsIgnoreCase(third));
    }
}

Explanation

The example creates three string variables:

String first = "Java";
String second = new String("Java");
String third = "java";

The first two strings contain identical text. The third starts with a lowercase letter.

The explicit new String("Java") creates a separate object to demonstrate the difference between comparing text and comparing references. In ordinary code, prefer a string literal when you do not need a separate object.

Comparing text with equals()

The equals() method compares the contents of strings:

first.equals(second)

This returns true because both strings contain "Java".

The comparison is case-sensitive:

first.equals(third)

This returns false because "Java" and "java" have different capitalization.

Comparing references with ==

For strings, the == operator checks whether two references point to the same object:

first == second

This returns false because second refers to a separately created string object, even though the text is identical.

String literals may share an object, so == can sometimes return true for strings containing the same text. Always use equals() when your intention is to compare their contents.

Ignoring capitalization

Use equalsIgnoreCase() when letter case should not affect the result:

first.equalsIgnoreCase(third)

This returns true for "Java" and "java".

Run the example

Compile and run the file:

javac StringComparisonExample.java
java StringComparisonExample

Output

Same text: true
Same object: false
Same case-sensitive text: false
Same text ignoring case: true

Handling null values

Calling equals() on a variable containing null throws a NullPointerException.

When comparing a variable with a known string literal, put the literal first:

"Java".equals(value)

This returns false if value is null.

If either of two variables may be null, use Objects.equals():

Objects.equals(firstValue, secondValue)

Import java.util.Objects to use this method. It returns true when both arguments are null, and otherwise compares their values safely.

How do I use a method reference in Java?

A method reference lets you use an existing method as the implementation of a functional interface. It can make a lambda expression shorter when the lambda only calls that method.

In this example, you will use a method reference to print each language in a list.

Source code

Save the following code as MethodReferenceExample.java:

import java.util.List;

public class MethodReferenceExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "JavaScript");

        languages.forEach(IO::println);
    }
}

Explanation

The example creates a list containing three language names:

List<String> languages = List.of(
        "Java", "Python", "JavaScript");

The forEach() method performs an action for each element in the list:

languages.forEach(IO::println);

It accepts a Consumer, a functional interface whose abstract method takes one argument and returns no value.

Referring to an existing method

The expression IO::println is a reference to the static println() method in java.lang.IO.

The double colon (::) separates the class name from the method name. The method reference does not call the method immediately. It supplies the action that forEach() invokes for each element.

This method reference can replace the following lambda expression:

languages.forEach(language -> IO.println(language));

Both versions print each language on a separate line, in list order.

Matching the functional interface

For this list, forEach() needs an action that accepts a string and returns no value.

IO.println(Object) is compatible because it accepts a String as an Object and returns void.

You do not add parentheses after the method name in a method reference:

IO::println

Parentheses belong to a method call, such as:

IO.println("Java");

Run the example

Compile and run the file:

javac MethodReferenceExample.java
java MethodReferenceExample

Output

Java
Python
JavaScript

Use a method reference when an existing method already performs the required action. Keep a lambda expression when you need additional logic, such as adding a prefix before printing each value.

How do I write a lambda expression in Java?

A lambda expression provides a concise implementation of a functional interface. A functional interface has one abstract method.

In this example, you will use a lambda expression to greet someone by name.

Source code

Save the following code as LambdaExample.java:

public class LambdaExample {
    void main() {
        Greeting greeting = name -> "Hello, " + name + "!";

        IO.println(greeting.greet("Alice"));
        IO.println(greeting.greet("Bob"));
    }
}

@FunctionalInterface
interface Greeting {
    String greet(String name);
}

Explanation

The Greeting interface declares one abstract method:

@FunctionalInterface
interface Greeting {
    String greet(String name);
}

The method accepts a name and returns a greeting.

The @FunctionalInterface annotation lets the compiler check that the interface meets the requirements of a functional interface.

Creating the lambda expression

The following statement assigns a lambda expression to a Greeting variable:

Greeting greeting = name -> "Hello, " + name + "!";

Each part has a purpose:

Part Purpose
name Receives the method argument
-> Separates the parameter from the body
"Hello, " + name + "!" Produces the returned value

The compiler knows that name is a String because the greet() method declares a String parameter.

For a single parameter with an inferred type, parentheses are optional. You can also write:

Greeting greeting = (name) -> "Hello, " + name + "!";

Returning a value

This lambda has an expression body:

name -> "Hello, " + name + "!"

The expression’s result is returned automatically. You do not need braces or a return statement.

If you use a block body instead, you must return the value explicitly:

Greeting greeting = name -> {
    return "Hello, " + name + "!";
};

Both forms provide the same behavior.

Calling the implementation

Call the interface method through the variable:

greeting.greet("Alice")

This passes "Alice" to the lambda and returns "Hello, Alice!". The program then prints the returned string using IO.println().

Run the example

Compile and run the file:

javac LambdaExample.java
java LambdaExample

Output

Hello, Alice!
Hello, Bob!

A lambda expression needs a target functional interface, such as Greeting in this example. You can also use lambdas with standard functional interfaces from java.util.function, including Predicate, Function, and Consumer.

How do I create a generic method in Java?

A generic method uses a type parameter to work with different reference types. This lets you reuse the same method without writing a separate version for each type.

In this example, you will create a method that prints the elements of an array. The same method will handle arrays of strings and integers.

Source code

Save the following code as GenericMethodExample.java:

public class GenericMethodExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};
        Integer[] numbers = {10, 20, 30};

        IO.println("Languages:");
        printElements(languages);

        IO.println();
        IO.println("Numbers:");
        printElements(numbers);
    }

    <T> void printElements(T[] elements) {
        for (T element : elements) {
            IO.println(element);
        }
    }
}

Explanation

The printElements() method declares a type parameter named T:

<T> void printElements(T[] elements) {
    for (T element : elements) {
        IO.println(element);
    }
}

The <T> declaration appears before the return type, void. It makes T available as a type within the method declaration and body.

Each part has a purpose:

Part Purpose
<T> Declares the type parameter
void Indicates that the method does not return a value
T[] elements Accepts an array whose element type is T
T element Holds each element during iteration

T is a conventional name. You can use a more descriptive name when it makes the code easier to understand.

Calling the method with different types

The first call passes an array of strings:

String[] languages = {"Java", "Python", "JavaScript"};
printElements(languages);

The compiler infers T as String for this call.

The second call passes an array of integers:

Integer[] numbers = {10, 20, 30};
printElements(numbers);

For this call, the compiler infers T as Integer.

You do not need to specify the type argument explicitly because the compiler can infer it from the array argument.

Using wrapper types

Java generic type arguments must be reference types. You cannot use a primitive type such as int as the type argument for T.

That is why this example uses Integer[] rather than int[]. Autoboxing converts the integer literals into Integer objects when the array is initialized.

Passing an int[] directly to this method would cause a compilation error.

Run the example

Compile and run the file:

javac GenericMethodExample.java
java GenericMethodExample

Output

Languages:
Java
Python
JavaScript

Numbers:
10
20
30

The type parameter belongs to the method, so the containing class does not need to be generic. Use a generic method when the same operation can work with multiple types while keeping compile-time type checking.