Saving input means you:

Store the input that you obtained from a user/file/database/.. to a variable in Java

save input Java

how it works?

  1. create a standard main-program setup
    package SaveInput;
    
    public class Basic {
    
    	void start () {
    		
    	}
    	
    	public static void main(String[] args) {
    		new Basic().start();
    
    	}
    
    }
  2. let’s say we’ve got our data from an user input.
    String inputByUser = "This input was given by a user";
  3.  In this example we will read the data from the user with the Scanner.
    1. import the Scanner class
      import java.util.Scanner;
    2. create a Scanner object, which contains the input
      Scanner in = new Scanner(inputByUser);
  4. What kind of input do you except ? a line / a word / etc.. For all options go to this page.
    I expect a line therefore, do I choose for the nextLine() method
    String savedInput = in.nextLine();

Additional

If you want to see what data you saved, print the variable:

  1. import the PrintStream class
    import java.io.PrintStream;
  2. Create a PrintStream object
    PrintStream out = new PrintStream(System.out);
  3. use one of the print methods in the class PrintStream (e.g. println | printf | print)
    void start () {
    	// rest of start method
    	out.println(savedInput);
    }

program

package SaveInput;

import java.io.PrintStream;
import java.util.Scanner;

public class Basic {
	String inputByUser = "This input was given by a user";
	PrintStream out = new PrintStream(System.out);
	
	void start () {
		Scanner in = new Scanner(inputByUser);
		String savedInput = in.nextLine();
		out.println(savedInput);
	}
	
	public static void main(String[] args) {
		new Basic().start();

	}

}

output

This input was given by a user

synonym

  • save variable
  • save InputStream
  • save String
  • save Scanner Object
  • read Input