Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Java Lecture 11: Numbers and arrays, examples. Teach/learn online

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko


Bookmark and Share

Numbers and arrays

by: Anatoliy Malyarenko

Abstract

Contents of the lecture.

  • Formatting numbers.
  • Creating and using arrays.
  • Arrays of objects.
  • Arrays of arrays.
  • Copying arrays.
  • Summary of arrays.

Formatting numbers

Programs store and operate on numbers in a locale-independent way. Before displaying or printing a number, a program must convert it to a String that is in a locale-sensitive format. For example, in France the number 123456.78 should be formatted as 123456, 78, and in Germany it should appear as 123.456, 78.

You can use the NumberFormat methods to format primitive-type numbers, such as double, and their corresponding wrapper objects, such as Double.

The following code example formats a Double according to Locale. Invoking the getNumberInstance method returns a locale-specific instance of NumberFormat. The format method accepts the Double as an argument and returns the formatted number in a String.

Double amount = new Double(345987.246);

NumberFormat numberFormatter;
String amountOut;

numberFormatter =
    NumberFormat.getNumberInstance(currentLocale);
amountOut = numberFormatter.format(amount);
System.out.println(amountOut + " " +
                                    currentLocale.toString());

The output from this example shows how the format of the same number varies with Locale:

345 987,246 fr_FR
345.987,246 de_DE
345,987.246 en_US

Currencies

If you're writing business applications, you'll probably need to format and to display currencies. You format currencies in the same manner as numbers, except that you call getCurrencyInstance to create a formatter. When you invoke the format method, it returns a String that includes the formatted number and the appropriate currency sign.

This code example shows how to format currency in a locale-specific manner:

Double currency = new Double(9876543.21);

NumberFormat currencyFormatter;
String currencyOut;

currencyFormatter =
        NumberFormat.getCurrencyInstance(currentLocale);
currencyOut = currencyFormatter.format(currency);
System.out.println(currencyOut + " " +
                                currentLocale.toString());

The output generated by the preceding lines of code is as follows:

9 876 543,21 F fr_FR
9.876.543,21 DM de_DE
$9,876,543.21 en_US

At first glance this output may look wrong to you, because the numeric values are all the same. Of course, 9876543, 21 F is not equivalent to 9.876.543, 21 DM. However, bear in mind that the NumberFormat class is unaware of exchange rates. The methods belonging to the NumberFormat class format currencies but do not convert them.

Percentages

You can also use the methods of the NumberFormat class to format percentages. To get the locale-specific formatter, invoke the getPercentInstance method. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

The following code sample shows how to format a percentage.

Double percent = new Double(0.75);
NumberFormat percentFormatter;
String percentOut;

percentFormatter =
        NumberFormat.getPercentInstance(currentLocale);
percentOut = percentFormatter.format(percent);

Customising formats

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. If you want to change formatting symbols, such as the decimal separator, you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. These classes offer a great deal of flexibility in the formatting of numbers, but they can make your code more complex.

You specify the formatting properties of DecimalFormat with a pattern String. The pattern determines what the formatted number looks like.

The example that follows creates a formatter by passing a pattern String to the DecimalFormat constructor. The format method accepts a double value as an argument and returns the formatted number in a String:

DecimalFormat myFormatter = new DecimalFormat(pattern);

String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);

The output for the preceding lines of code is described in the following table. The value is the number, a double, that is to be formatted. The pattern is the String that specifies the formatting properties. The output, which is a String, represents the formatted number.

value pattern output
1 2 3
123456.789 ###,###.### 123, 456.789
The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
123456.789 ###.## 123456.79
The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up.
123.78 000000.000 000123.780
The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#).
12345.67 $###,###.### $12, 345.67
The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output.
12345.67 \u00A5###,###.### ¥12,345.67
The pattern specifies the currency sign for Japanese yen (¥) with the Unicode value 00A5.

Locale-sensitive formatting

The preceding example created a DecimalFormat object for the default Locale. If you want a DecimalFormat object for a non-default Locale, you instantiate a NumberFormat and then cast it to DecimalFormat. Here's an example:

NumberFormat nf = NumberFormat.getNumberInstance(loc);
DecimalFormat df = (DecimalFormat)nf;
        df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " "
        + output + " " + loc.toString());

Running the previous code example results in the output that follows. The formatted number, which is in the second column, varies with Locale:
###,###.### 123,456.789 en_US
###,###.### 123.456,789 de_DE
###,###.### 123 456,789 fr_FR

So far the formatting patterns discussed here follow the conventions of U.S. English. For example, in the pattern ###,###.## the comma is the thousands-separator and the period represents the decimal point. This convention is fine, provided that your end users aren't exposed to it. However, some applications, such as spreadsheets and report generators, allow the end users to define their own formatting patterns. For these applications the formatting patterns specified by the end users should use localised notation. In these cases you'll want to invoke the applyLocalizedPattern method on the DecimalFormat object.

Altering the formatting symbols

You can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others.
The next example demonstrates the DecimalFormatSymbols class by applying a strange format to a number. The unusual format is the result of the calls to the setDecimalSeparator, setGroupingSeparator, and setGroupingSize methods.

DecimalFormatSymbols unusualSymbols =
        new DecimalFormatSymbols(currentLocale);
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');

String strange = "#,##0.###";
DecimalFormat weirdFormatter =
    new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);

String bizarre = weirdFormatter.format(12345.678);
System.out.println(bizarre);

When run, this example prints the number in a bizarre format:

1^2345|678

Summary of numbers

You use an instance of one of the Number classes -- Byte, Double, Float, Integer, Long, and Short -- to contain a number of primitive type. You can also use BigInteger and BigDecimal for arbitrary-precision numbers.

The Number classes include class methods and constants, which are useful in a variety of ways. The MIN VALUE and MAX VALUE constants contain the smallest and largest values that can be contained by an object of that type. The byteValue, shortValue, and similar methods convert one numeric type to another. The valueOf method converts a string to a number, and the toString method converts a number to a string.

To format a number to display to an end user, you use the NumberFormat class in the java.text package. When using NumberFormat, you can get a default format for decimal numbers, percentages, or currency. Or, you can design a custom format using patterns.

The Math class contains a variety of class methods for performing mathematical functions. This class includes the trigonometric functions, such as computing sine, cosine, and so on. Math also includes functions for logarithm calculations, as well as basic arithmetic functions, such as rounding. Finally, Math contains a method, random, for generating random numbers.

Arrays

An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime). After creation, an array is a fixed-length structure.

An array element is one of the values within an array and is accessed by its position within the array.

If you want to store data of different types in a single structure, or if you need a structure whose size can change dynamically, use a Collection implementation, such as Vector, instead of an array.

Creating and using arrays

Here's a simple program, called ArrayDemo, that creates the array, puts some values in it, and displays the values.

public class ArrayDemo {
    public static void main(String[] args) {
        int[] anArray; // declare an array of integers

        anArray = new int[10]; // create an array of integers

         // assign a value to each array element and print
        for (int i = 0; i < anArray.length; i++) {
            anArray[i] = i;
            System.out.print(anArray[i] + " ");
        }
        System.out.println();
    }
}

Declaring a variable to refer to an array

This line of code from the sample program declares an array variable:

int[] anArray; // declare an array of integers

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written type[], where type is the data type of the elements contained within the array, and [] indicates that this is an array. Remember that all of the elements within an array are of the same type. The sample program uses int[], so the array called anArray will be used to hold integer data. Here are declarations for arrays that hold other types of data:

float[] anArrayOfFloats; boolean[] anArrayOfBooleans;

Object[] anArrayOfObjects; String[] anArrayOfStrings;

As with declarations for variables of other types, the declaration for an array variable does not allocate any memory to contain the array elements. The sample program must assign a value to anArray before the name refers to an array.

Creating an array

You create an array explicitly using Java's new operator. The next statement in the sample program allocates an array with enough memory for ten integer elements and assigns the array to the variable anArray declared earlier.

anArray = new int[10]; // create an array of integers

In general, when creating an array, you use the new operator, plus the data type of the array elements, plus the number of elements desired enclosed within square brackets ('[' and ']').

new elementType[arraySize]

If the new statement were omitted from the sample program, the compiler would print an error like the following one and compilation would fail.

ArrayDemo.java:4: Variable anArray may not have been initialized.

Accessing an array element

Now that some memory has been allocated for the array, the program assign values to the array elements:

for (int i = 0; i < anArray.length; i++) {
    anArray[i] = i;
    System.out.print(anArray[i] + " ");
}

This part of the code shows that to reference an array element, either to assign a value to it, or to access the value, you append square brackets to the array name. The value between the square brackets indicates (either with a variable or some other expression) the index of the element to access. Note that in Java, array indices begin at 0 and end at the array length
minus 1.

Getting the size of an array

To get the size of an array, you write

arrayname.length

Be careful: Programmers new to the Java programming language are tempted to follow length with an empty set of parenthesis. This doesn't work because length is not a method. length is a property provided by the Java platform for all arrays.

The for loop in our sample program iterates over each element of anArray, assigning values to its elements. The for loop uses anArray.length to determine when to terminate the loop.

Array initialisers

The Java programming language provides a shortcut syntax for creating and initialising an array. Here's an example of this syntax:

boolean[] answers =
        true, false, true, true, false ;

The length of the array is determined by the number of values provided between { and }.

Arrays of objects

Arrays can hold reference types as well as primitive types. You create such an array in much the same way you create an array with primitive types. Here's a small program, ArrayOfStringsDemo that creates an array containing three string objects then prints the strings in all lower case letters.

public class ArrayOfStringsDemo {
    public static void main(String[] args) {
        String[] anArray = { "String One", "String Two",
                                    "String Three" };
        for (int i = 0; i < anArray.length; i++) {
            System.out.println(anArray[i].toLowerCase());
        }
    }
}

This program creates and populates the array in a single statement. However, you can create an array without putting any elements in it. This brings us to a potential stumbling block, often encountered by new programmers, when using arrays that contain objects. Consider this line of code:

String[] anArray = new String[5];

After this line of code is executed, the array called anArray exists and has enough room to hold 5 string objects. However, the array doesn't contain any strings yet. It is empty. The program must explicitly create strings and put them in the array. This might seem obvious, however, many beginners assume that the previous line of code creates the array and creates 5 empty strings in it. Thus they end up writing code like the following, which generates a NullPointerException:

String[] anArray = new String[5];

for (int i = 0; i < anArray.length; i++) {
    // ERROR: the following line gives a runtime error
    System.out.println(anArray[i].toLowerCase());
}

The problem is more likely to occur when the array is created in a constructor or other initialiser and then used somewhere else in the program.

Arrays of arrays

Arrays can contain arrays. ArrayOfArraysDemo creates an array and uses an initialiser to populate it with four sub-arrays.

public class ArrayOfArraysDemo {
    public static void main(String[] args) {
        String[][] cartoons = {
                { "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
                { "Rubbles", "Barney", "Betty", "Bam Bam" },
                { "Jetsons", "George", "Jane", "Elroy", "Judy",
                            "Rosie", "Astro" },
             { "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma",
                    "Fred", "Daphne" }
        };
        for (int i = 0; i < cartoons.length; i++) {
            System.out.print(cartoons[i][0] + ": ");
            for (int j = 1; j < cartoons[i].length; j++) {
                System.out.print(cartoons[i][j] + " ");
            }
        System.out.println();
        }
    }
}

Notice that the sub-arrays are all of different lengths. The names of the sub-arrays are cartoons[0], cartoons[1], and so on.

As with arrays of objects, you must explicitly create the sub-arrays within an array. So if you don't use an initialiser, you need to write code like the following, which you can find in ArrayOfArraysDemo2

public class ArrayOfArraysDemo2 {
    public static void main(String[] args) {
        int[][] aMatrix = new int[4][];
        //populate matrix
        for (int i = 0; i < aMatrix.length; i++) {
            aMatrix[i] = new int[5]; //create sub-array
            for (int j = 0; j < aMatrix[i].length; j++) {
                aMatrix[i][j] = i + j;
            }
        }
        //print matrix
        for (int i = 0; i < aMatrix.length; i++) {
            for (int j = 0; j < aMatrix[i].length; j++) {
                System.out.print(aMatrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

You must specify the length of the primary array when you create the array. You can leave the length of the sub-arrays unspecified until you create them.

Copying arrays

Use System's arraycopy method to efficiently copy data from one array into another. The arraycopy method requires five arguments:

public static void arraycopy(Object source,
                                            int srcIndex,
                                            Object dest,
                                            int destIndex,
                                            int length );

The two Object arguments indicate the array to copy from and the array to copy to. The three integer arguments indicate the starting location in each the source and the destination array, and the number of elements to copy. This diagram illustrates how the copy takes place:

The following program, ArrayCopyDemo, uses arraycopy to copy some elements from the copyFrom array to the copyTo array.

public class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom =
                'd', 'e', 'c', 'a', 'f', 'f', 'e',
                'i', 'n', 'a', 't', 'e', 'd' ;
                char[] copyTo = new char[7];
        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

The arraycopy method call in this example program begins the copy at element number 2 in the source array. Recall that array indices start at 0, so that the copy begins at the array element 'c'. The arraycopy method call puts the copied elements into the destination array beginning at the first element (element 0) in the destination array copyTo. The copy copies 7 elements: 'c', 'a', 'f', 'f', 'e', 'i', and 'n'. Effectively, the arraycopy method takes the "caffein" out of "decaffeinated", like this:

Note that the destination array must be allocated before you call arraycopy and must be large enough to contain the data being copied.

Summary of arrays

An array is a fixed-length data structure that can contain multiple objects of the same type. An array can contain any type of object, including arrays. To declare an array, you use the type of object that the array can contain and brackets.

The length of the array must be specified when it is created. You can use the new operator to create an array, or you can use an array initialiser. Once created, the size of the array cannot change. To get the length of the array, you use the length attribute.

An element within an array can be accessed by its index. Indices begin at 0 and end at the length of the array minus 1.

To copy an array, use the arraycopy method in the System class.


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy