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
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:
- Java program to check if a number is a happy number or not
- Java program to print the Neon numbers from 0 to 10000
- How to remove the first character of a string in Java
- How to remove the last character of a string in Java
- Java program to convert string characters lowercase to uppercase without using any library function
- How to convert miles to kilometers and kilometers to miles in Java
- Java program to check if a number is valid IMEI or not