how to get a string input in java code example

Example 1: scanner in java

import java.util.Scanner;		//Import Scanner in java

class classname{
  public void methodname(){
    Scanner s_name = new Scanner(System.in);	//Scanner declaration
    //Use Scanner object to take input
    int val1    =  s_name.nextInt();			//int
    float val2  =  s_name.nextFloat();			//float
    double val3 =  s_name.nextDouble();			//double
    string name =  s_name.nextLine();			//string
    char ch     =  s_name.nextLine().charAt(0);	//character
  }}

Example 2: taking string input in java

Scanner in = new Scanner(System.in);
String s = in.nextLine();

Example 3: java read string input

import java.util.Scanner;
 
public class YourClass {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.nextLine();
        System.out.println("Your string: " + inputString);
    }
}

Example 4: how to read input in java

//For continues reading a line
import java.util.Scanner; 

Scanner in = new Scanner(System.in); 
while(in.hasNextLine()) {
   String line = in.nextLine();
   System.out.println("Next line is is: " + line); 
}

Tags:

Java Example