Length Method of Input in Java

Length Method of Input in Java thumbnail
Methods like "length()" reduce the work a programmer needs to do.

After Java programmers go beyond writing simple programs that only display pre-configured text, they should learn how to accept and manipulate user input to create truly useful programs. Java makes it easy for programmers to discover certain characteristics of user input, such as the length of a user's input. Programmers can accomplish this task by calling a string's "length()" method.

  1. Standard Input Interfaces

    • Java programmers have two standard options for taking user input: they can use a "console" object to read in information that the user types into the terminal screen on which the program is running, or they can use one of the Java Swing library's many textual input objects. The programmer then discover the length of the user's input by assigning the object to a string. Console objects assign input directly to a string, but Swing objects require the programmer to perform an additional step.

    String Method

    • In the Java programming language, a string is an instance of a String object. The string object contains several methods that are useful to programmers, one of which is the "length()" method. Invoking this method on a particular string will cause the object to return the string's length in the form of an integer. If a string is named "userInput," then the syntax "userInput.length();" will give the programmer the number of characters "userInput" is storing.

    Swing Components

    • Swing components that take text input, such as "JTextField" and "JTextArea," are just container objects. They can hold the data which the user types into them, but their methods do not have the ability to perform any operations on the actual data. Users can make an object return the data which they hold by invoking its "getText()" method. By setting a string to this output, the programmer can then invoke the sting's "length()" method to discern the length of the data the user typed into a field.

    Numerical Entries

    • While the "length()" method returns the length of text based data, Java does not have similar methods for dealing with numerical data. If a user types in the number 100 and the programmer stores it as an integer, then the programmer cannot call a method to directly discover the length of an integer. However, the programmer can cast the numerical data as a string. If a programmer has the number 100 stored in the variable "myInt," then the syntax "String.valueOf(myInt);" will produce a string that treats the numbers as text instead of integers. The programmer can then invoke that string's "length()" method.

Related Searches:

References

  • Photo Credit Comstock/Comstock/Getty Images

Comments

Related Ads

Featured