How to Input a String in Java

How to Input a String in Java thumbnail
Taking simple string input is where every programmer needs to start.

In the Java programming language beginners quickly encounter one of the limits of Java primitive data types: The basic character variable can store only one letter at a time. This is why Java uses "string" objects to store a sequence, or string, of letters, numbers or symbols. To make a command line, Java stores lines of user input in such a string, you can use the "readLine" method of the handy "Console" object.

Instructions

    • 1

      Click on the first line of your source code file to set the cursor there. Import the code for the "console" class by typing "import java.io.Console;" at the top of your source code.

    • 2

      Create a new console object by typing the code "Console myConsole = new System.console();"

    • 3

      Write the text you want to use to prompt the user to input his string by typing "String prompt = 'my prompt';" where "my prompt" is the prompt text you wish to use.

    • 4

      Type the line "String userString = myConsole.readLine(prompt);" to make your program accept a user's string input, and write it to the string object "userString."

Tips & Warnings

  • If you want to make your program hide the individual characters your user will be typing in, as in the case of entering passwords, use "readPassword" instead of "readLine." You can also opt to directly set the prompt text, instead of first writing it to a string object, by typing the text in between quotation marks in the parenthesis after "readLine" instead of simply putting in the predefined string object.

Related Searches:

References

Resources

  • Photo Credit Stockbyte/Stockbyte/Getty Images

Comments

You May Also Like

  • How to Set Up Java Classpath on Windows

    Java developers use the "classpath" to tell Java applications where to find specialized software components, called "classes." The classpath can be set...

  • What Is Java Console?

    The Java Console is a special program used to assist developers in finding and correcting bugs in their applications. It is not...

  • How to Make Java Games

    Java games are computer games written in the computer programming language "Java." Java games can be as complex as the shoot-'em-up three...

Related Ads

Featured