eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

The Scanner class comes with a set of methods that simplify the process of parsing inputs by breaking them into multiple tokens. In code, it commonly reads input data from different sources, such as consoles and files.

In this short tutorial, we’ll highlight the difference between its next() and nextLine() methods.

Even though these two methods may appear quite similar at first, they’re quite different.

2. next() Method

Typically, Scanner breaks the input into tokens using a delimiter pattern, which is, by default, any whitespace.

With that being said, next(), as the name implies, reads only the next token from the input until it encounters the delimiter.

2.1. Using the Default Delimiter

As mentioned earlier, the Scanner class uses whitespace as the default delimiter.

For instance, if we enter Hello world as the input, next() reads only the value Hello. The remaining word, world, is available for the next call of the next() method.

So, let’s exemplify the use of next() with a test case:

@Test
void givenInput_whenUsingNextMethod_thenReturnToken() {
    String input = "Hello world";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello", scanner.next());
        assertEquals("world", scanner.next());
    }
}

Here, Scanner uses the space character to parse the input.

Consequently, the first call of the next() method reads only the value Hello. On the other hand, the second call reads the value world.

Multiple whitespace characters are also treated as one single whitespace, and the result is the same:

@Test
void givenInput_whenUsingNextMethodWithMultipleWhiteSpaces_thenReturnToken() {
    String input = "Hello        world";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello", scanner.next());
        assertEquals("world", scanner.next());
    }
}

Multiple whitespace, like tabs and new lines, also result in the same output:

@Test
void givenInput_whenUsingNextMethodWithTabAndNewLine_thenReturnToken() {
    String input = "Hello    \t\n world";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello", scanner.next());
        assertEquals("world", scanner.next());
    }
}

Notably, the whitespace includes several characters, not only space, such as tab (\t), return line (\n), and more characters.

2.2. Using a Custom Delimiter

The Scanner class provides a convenient way to override the default delimiter through the useDelimiter() method.

So, let’s see how the next() method behaves with a custom delimiter.

For example, we can use the : colon character as the delimiter:

@Test
void givenInput_whenUsingNextMethodWithCustomDelimiter_thenReturnToken() {
    String input = "Hello :world";
    try (Scanner scanner = new Scanner(input)) {
        scanner.useDelimiter(":");

        assertEquals("Hello ", scanner.next());
        assertEquals("world", scanner.next());
    }
}

As shown above, next() reads Hello, followed by the space character this time. The reason is that Scanner uses : to break the input into tokens instead of a space.

3. nextLine() Method

On the other hand, nextLine() consumes the whole line of the input, including whitespace characters, until it reaches the \n newline character.

In other words, we can use this method to read inputs that contain default delimiters, such as a space. It stops reading just after receiving \n (such as when hitting Return).

So, let’s see it in practice:

@Test
void givenInput_whenUsingNextLineMethod_thenReturnEntireLine() {
    String input = "Hello world\nWelcome to baeldung.com";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello world", scanner.nextLine());
        assertEquals("Welcome to baeldung.com", scanner.nextLine());
    }
}

As we can see, the first scanner.nextLine() reads the entire value Hello world, and the second one consumes the rest of the input.

Unlike next(), which places the cursor in the same line, nextLine() points the cursor to the next line after reading the input.

Importantly, unlike next(), defining a custom delimiter won’t change the behavior of nextLine().

Let’s confirm this using a test case:

@Test
void givenInput_whenUsingNextLineWithCustomDelimiter_thenIgnoreDelimiter() {
    String input = "Hello:world\nWelcome:to baeldung.com";
    try (Scanner scanner = new Scanner(input)) {
        scanner.useDelimiter(":");

        assertEquals("Hello:world", scanner.nextLine());
        assertEquals("Welcome:to baeldung.com", scanner.nextLine());
    }
}

Unsurprisingly, the nextLine() method ignores the custom delimiter and continues reading the input until it finds the \n character.

Carriage Return (\r) and Carriage Return Line Feed (\r\n) are also treated as new line delimiters by nextLine():

@Test
void givenInput_whenUsingNextLineMethodWithCR_thenReturnEntireLine() {
    String input = "Hello world\rWelcome to baeldung.com";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello world", scanner.nextLine());
        assertEquals("Welcome to baeldung.com", scanner.nextLine());
    }
}

Both function the same way:

@Test
void givenInput_whenUsingNextLineMethodWithCRLF_thenReturnEntireLine() {
    String input = "Hello world\r\nWelcome to baeldung.com";
    try (Scanner scanner = new Scanner(input)) {
        assertEquals("Hello world", scanner.nextLine());
        assertEquals("Welcome to baeldung.com", scanner.nextLine());
    }
}

Thus, we can be sure that the nextLine() method works similarly on different platforms and

In a nutshell, let’s understand the key points to keep in mind when comparing the next() and nextLine() methods:

  • nextLine() returns the entire text up to the return line, next() reads a tokenized text based on a given delimiter (whitespace by default)
  • nextLine() places the scanner position on the next line after reading the input, next() keeps the cursor in the same line

This way, both serve a purpose, but one is more specific.

4. Other Ways to Tokenize a String

Alternatively, we can use tokenization methods like String.split(). In particular, several variations of the split can be used depending on the requirements.

There are two main split methods with different parameters:

  • split(String regex, int limit): splits the string based on the provided regular expression (first argument), while ensuring that a limit (second argument) is placed on the number of times it’s applied
  • split(String regex): splits the string based on the provided regular expression (first argument) an unlimited number of times

Care should be taken with the latter, as we might get unexpected results.

5. Key Differences

Let’s summarize the key differences when comparing the next() and nextLine() methods in Scanner:

Feature next() nextLine()
Reads Next token Entire line
Default delimiter Whitespace Newline
Custom delimiter Affects behavior Ignored
Cursor position Stays on the same line Moves to the next line
Suitable for Tokenized input Sentences or full text

Thus, we should be able to pick between these two options easily.

6. Conclusion

In this article, we explained in detail the difference between Scanner.next() and Scanner.nextLine() methods.

In detail, we understood that both serve a similar purpose, but they are useful in different situations. This way, they are a readable way to consume data.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments