String Literals

The String class represents text as a string of characters. Since programs usually communicate with their users through the written word, the ability to manipulate strings of text is quite important in any programming language. In some languages, strings are a primitive type, on a par with integers and characters. In Java, however, strings are objects; the data type used to represent text is the String class.
Because strings are such a fundamental data type, Java allows you to include text literally in programs by placing it between double-quote (") characters.
For example:

String name = "David";
System.out.println("Hello, " + name);

The Java Swing Classes
Java’s Swing classes create graphical objects on a computer screen. The objects can include buttons, icons, text fields, check boxes, and other good things that make windows so useful.
The name “Swing” isn’t an acronym. When the people at Sun Microsystems were first creating the code for these classes, one of the developers named it “Swing” because swing music was enjoying a nostalgic revival. And yes, in addition to String and Swing, the standard Java API has a Spring class.

Dialog Boxes

A dialog box is a small graphical window that displays a message to the user or requests input. You can quickly display dialog boxes with the JOptionPane class.

Message Dialog – A dialog box that displays a message; an OK button is also displayed.
Input Dialog – A dialog box that prompts the user for input and provides a text field where input is typed; and OK button and Cancel button are also displayed.

To display message dialogs the showMessageDialog method is used. The following statement calls that method:

JOptionPane.showMessageDialog(null, “Hello Class”);

Example:

String name;
name = JOptionPane.showInputDialog(“Enter your name”);

Converting String Input to Numbers

The JOptionPane class does not have different methods for reading values of different data types. The showInputDialog method always returns the user’s input as String, even if the user enters numeric data. For example if the user enters the number 72 into an input dialog, the showInputDialog method will return the string “72”. This can be a problem if you wish to use the user’s input in a math operation because you can not perform math on strings. In such a case, you must convert the input to a numeric value. To convert a string value to a numeric value, you use one of the methods listed below.

Examples:

1)
int number;
String str;

str = JOptionPane.showInputDialog(“Enter a number.”);
number = Integer.parseInt (str);

2)
double price;
String str;
str = JOptionPane.showInputDialog(“Enter the retail price.”);
price = Double.parseDouble (str);

_____________________________________________________

No comments: