Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

New-to-Java Programming Center Supplement

 

New-to-Java Programming Center
Programming Center Supplement

Welcome to the Java Developer ConnectionSM New to Java Programming Center Supplement!

This monthly supplement provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to JavaTM Programming Center.

CONTENTS

1. Java Programming Language Basics

    Converting a String to a Numerical Value

2. Making Sense of the Java Class Libraries

    The NumberFormat Class

3. Program Challenges

    Numbers Application

4. Java Bits

    AWT versus Project Swings

5. New to the New to Java Programming Center

    Building an Application

6. For More Information

    Links to articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

7. Program Challenge Solution and Explanation

    Possible solution to the Numbers Conversion Application

Java Programming Language Basics

Converting a String to a Numerical Value

A common need of the Java technology developer is to convert strings to numerical values. Once converted, you can manipulate that value like any other data primitive (for instance, an int, float, or double). The problem is, when you read from a file, get a command line argument, get an applet parameter, or just prompt for input from a text field on a form, you always start with a String object. Treating that String as a primitive requires an extra step, the conversion.

To convert a String to a primitive, you must understand how to use a wrapper class. Every primitive has an associated wrapper class. These wrapper classes allow you to treat primitives as objects. In addition, these classes contain methods that permit manipulation of these objects, appropriate for the data type.

The following list shows the mapping from primitive type to wrapper class. In almost all cases, the wrapper class has the same name as the primitive data type, with the first letter capitalized.

Primitive to Wrapper Class

byte - Byte
short - Short
int - Integer
long - Long
char - Character
float - Float
double - Double
boolean - Boolean

Each of these wrapper classes (except the Character class) has a method that allows you to convert from a String to the specific primitive type.

Simply call the method from the appropriate wrapper class, and your String is converted to a primitive type.

For instance:

String myString = "12345";
int myInt = Integer.parseInt(myString);

converts the contents of the String variable myString to an int object myInt. The conversion is that easy. The only trick is that the conversion for each data type involves a uniquely named method in each wrapper class.

All but the boolean conversions are done by similarly named methods, but still all the method names are different:

byte - Byte.parseByte(aString)
short - Short.parseShort(aString)
int - Integer.parseInt(aString)
long - Long.parseLong(aString)
float - Float.parseFloat(aString)
double - Double.parseDouble(aString)
boolean - Boolean.valueOf(aString).booleanValue();

There is one exception: The Character class has no such method, so you have to ask String for the character with the charAt method:

// The variable e is the character e in the string Hello
     String hello = "Hello";
     char e = hello.charAt(1);

If the String contents cannot be converted to the requested primitive type, then a NumberFormatException is thrown. This is a runtime exception, so the conversion code does not have to be in a try-catch block.

Making Sense of the Java Class Libraries

The NumberFormat Class

Printing numbers to the screen can produce some odd or undesired results.

For instance:

public class PrintNum {
    public static void main(String args[]) {
      double amount = 400000.00;
      System.out.println("He paid " + amount 
                           + " for the house.");
        }
}

results in:

He paid 400000.0 for the house.

Adding the symbol $ in the string won't improve these results because primitives print with the maximum number of non-zero digits for that type, and commas are not included in the result.

You can control display format and arrange input into the needed output format by using the NumberFormat abstract class in the java.text package.

This class provides the interface to format and parse numbers, and includes methods to determine which locales have number formats and what their names are.

The class has methods for three standard formats:

  • getInstance or getNumberInstance gets a format for the normal number format, such as 600,000
  • getCurrencyInstance gets a format for the currency number format, such as $600,000.00
  • getPercentInstance gets a format for displaying percentages, such as 56%

To format a primitive, start by returning an object of type NumberFormat by calling on one of the above methods. To use the previous example, to display $400,000, you call:

NumberFormat nf = NumberFormat.getCurrencyInstance();

To be certain the amount is formatting correctly for a specific country, you specify the locale with:

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

Now, the program above can be rewritten as follows:

import java.text.*;
import java.util.Locale;

public class PrintNum {
  public static void main(String args[]) {
    // Amount to be formatted
    double amount = 400000.00; 
    // Returns an object of type NumberFormat
    NumberFormat nf = 
       NumberFormat.getCurrencyInstance(Locale.US);
    // Calls the format method on the NumberFormat object
    // to format the amount as desired and prints the 
    // results to the screen
     System.out.println("He paid " +  nf.format(amount)
                           + " for the house.");
        }
}

Results in:

He paid $400,000.00 for the house.

Program Challenge

Numbers Conversion

Use what you learned to create an application that reads arguments from the command-line. The rules for handling command line arguments are as follows:

  • If the argument is an integer, add the value to the answer.
  • If the argument is a floating point number, multiply the answer by the value.
  • If the argument is neither, display the invalid argument.

Once the arguments are processed, display the resulting value as currency, with the currency symbol, commas between thousands (assuming US locale), decimal point, and two digits after the decimal point.

When executed with the following command line:

java Numbers 1 2 3 4 5 2.3 3 4 4444.4 a

Your program should produce results similar to the following:

Arg: 10 invalid (a)
The answer is $184,442.60

Java Bits:

AWT Versus Project Swing

A common misconception is that Project Swing is a replacement for the Abstract Window Toolkit (AWT). In fact, Swing is a set of mostly lightweight components built on top of the AWT.

Originally AWT was designed to create simple interfaces for applets. Swing provides replacements for AWT's heavyweight components and also includes components and tools commonly used in more complex user interfaces.

A heavyweight component relies on the local platform's windowing system to determine the look and feel of components. Each heavyweight component has a peer class from the package java.awt.peer that is responsible for the interactions between the component and the local platform, such as Mac, Windows, and Solaris to display and manipulate the object.

A lightweight component, on the other hand, is written completely in the Java programming language and does not have a native peer. To accomplish the look and feel of a specific platform, you can use Swing's Pluggable Look and Feel architecture and API.

In application programming, the AWT layout managers provide a

  • Layout for organizing components within a pane
  • Event handling mechanisms to manage the functionality of AWT or Swing components like buttons, text fields, or text areas.

To complete a complex application written in the Java programming language, you'll need to understand a little about AWT, and a lot about Project Swing.

New to the New to Java Programming Center

Building an Application: Part 1

Learn about classes, objects, and methods in the first part of this tutorial that teaches Java technolgies and how they fit together in a dive log application. In addition, you'll learn about packages and compiling files.

For More Information

For More Information

Using Predefined Formats

Numbers

Essentials Part 2, Lesson 2: Converting Strings to Numbers and Back

Internationalize Numbers

Lightweight Components

Overview of the Swing API

Program Challenge Solution

This is one possible solution to the Program Challenge:

import java.text.*;
import java.util.Locale;

public class Numbers {
    public static void main(String args[]) {

      // Initialize total
      double answer = 0;

      // Working variable
      double number;

      // Loop through all the command line args
      for (int i=0; i < args.length; i++) {

        try {

          // First try to convert arg to an int
          number = Integer.parseInt(args[i]);
          // Add to total if int
          answer += number;

        } catch (NumberFormatException intTry) {

          try {

            // Next try to convert arg to a double
            number = Double.parseDouble(args[i]);
            // Multiple to total if double
            answer *= number;

          } catch (NumberFormatException doubleTry) {

            // Display message if neither int nor double
            System.err.println("Arg: " + (i+1) +
              " invalid (" + args[i] + ")");

          }
        }
      }

      // Create a currency display format with Local included
      NumberFormat nf =
                  NumberFormat.getCurrencyInstance(Locale.US);

      // Display output as US currency format
      System.out.println("The answer is " + nf.format(answer));
    }
}

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and run-time environment provided with the Java 2, Standard Edition development kit.

IMPORTANT: Please read our Terms of Use and Privacy policies:

Have a question about programming? Use Java Online Support.

- Note -

Sun respects your online time and privacy. The Java Developer Connection mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.

- Unsubscribe -

To unsubscribe to this newsletter, go to the subscriptions page uncheck the "JDC New-to-Java Supplement" checkbox, and click "Update".

- Subscribe -

To subscribe to other JDC mailings, go to the subscriptions page choose the newsletters you want to subscribe, and click "Update".

- Feedback -

Comments? Send your feedback on the JDC Newsletter to: jdc-webmaster

- Copyright -

Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA

This document is protected by copyright.

JDC New-to-Java Programming Center Supplement
October 2001


1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform. -->