How to take a string with blank spaces as input in Java

How to take a string with blank spaces as input in Java:

In this post, we will learn how to take a string with blank spaces as inputs in Java. I will also show you one example program to make it clear to you.

Scanner class and next() and nextLine() methods:

We can use the methods of Scanner class, namely next and nextLine. These methods are used to read user inputs.

But there is a difference between next() and nextLine() methods. next() method can read strings up to the space. For example, if you use next() to read Hello World, it will read only the Hello word. But, we can use nextLine to read a string with blank spaces. It will read the whole Hello World string.

nextLine stops if it reads a newline character \n or if the user press the enter key.

So, if you want to take a string with blank spaces as input, you have to use newLine() method.

Example of newLine:

Let’s take a look at the below example:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str;

        System.out.println("Enter a string: ");
        str = sc.nextLine();

        System.out.println("You have entered: " + str);
    }
}

If you run this program, it will print output as like below:

Enter a string: 
Hello World
You have entered: Hello World

Java read strings with spaces

Example with next():

Let’s try with the next() method. If you use this method, it will not read the blank spaces.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str;

        System.out.println("Enter a string: ");
        str = sc.next();

        System.out.println("You have entered: " + str);
    }
}

If you run this, it will print:

Enter a string: 
Hello World
You have entered: Hello

You might also like: