Java Notes Prev: Java Example: Dialog: Hello Earthling | Next: Java Example: Dialog: Captitalize

Java Example: Dialog: Take me to your leader

This is similar to the previous program, but it also gets input from the user.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
// Description: This program gets a string from a dialog box, prints message.
// File  : examples/introductory/dialog/ToLeader.java
// Author: Fred Swartz - 2006-December-03 - Placed in public domain.

import javax.swing.*;

public class ToLeader {

    public static void main(String[] args) {
        String name;               // A local variable to hold the name.

        name = JOptionPane.showInputDialog(null, "What's your name, Earthling");

        JOptionPane.showMessageDialog(null, "Take me to your leader, " + name);
    }
}
Line 11 - Declaring a local variable.
This tells the compiler to reserve some memory to hold a String. It's going to hold a name, so we called the variable (a place in the computer's memory) "name". The syntax for a simple declaration is to write the type of thing that a variable will hold (String in this case), followed by the variable name (name in this case).
Line 13 - Asking the user for a String.
JOptionPane's showInputDialog method displays a message in a dialog box that also accepts user input. It returns a string that can be stored into a variable.

This is an assignment statement. The part to the right of the "=" must produce a value, and this value is then stored in the variable on the left (name).

Line 15 - Putting two strings together (concatenation)
Concantenation, indicated by the plus sign (+), puts two strings together to build a bigger string, which is then passed as a parameter. The plus sign (+) is also used for addition of numbers.

Console version

See Java Example: Console: Take me to your leader for how this program would be written using console output.