The int type is only one kind of simple variable you can use. Mentioned below are the various possibilities:
Integers—Refer to the types byte, short, int, and long that hold signed, whole-value numbers.
Floating-point numbers—Refer to the types float and double that hold signed floating-point numbers.
Character—Refers to the char type that holds characters such as letters and numbers.
Boolean—Refers to the type that holds only two types of values: true and false.
We’ll take a closer look at all these in the “Immediate Solutions” section, including what range of values each can hold. Together, these types make up what are called simple data types in Java. Each of these types represents a single data value, not a compound data value (as opposed to an array, which is also discussed in this chapter).
You can store one data item in a variable made up of any simple data type, and that data item must fit in the range allowed for that data type.
Data Typing
Java puts considerable emphasis on its data types. It’s a strongly-typed language, which means it insists that the simple variables you declare and use must fit in the listed types.
Every simple variable must have a type (and in fact, every expression—every combination of terms that Java can evaluate to get a value—has a type as well). Also, Java is very particular about maintaining the integrity of those types, especially if you try to assign a value of one type to a variable of another type. In fact, Java is more strongly typed than a language such as C++. In C++, for example, you can assign a floating-point number to an integer, and C++ will handle the type conversion for you, but you cannot do that in Java. You can, however, convert between certain data types in Java such as between the integer types. We’ll take a look at that later in this chapter.
When working with variables, you might find the Java compiler issuing a lot of errors and warnings about data types, which can take some time getting used to; bear in mind that the inspiration for making Java very particular about adhering to data types and not mixing them easily is to prevent errors in your code.
That’s an overview of what’s going on in Java with simple data types and variables; it’s now time to take a look at compound data storage in depth, which as far as this chapter is concerned means arrays.
Arrays
Simple types are good only for storing single data items. However, sometimes the data that needs to be stored is a lot more complex. For instance, you want to start a new bank, say, JP Bank (short for Java Programming Bank) and keep a track of the amount in each account indexed by account number. This situation presents the need to work with compound data. The usage of arrays is appropriate in such a scenario.
An array allows grouping of simple data to form a compound data structure that can be referred to by using a single name. Every data item stored in that compound data structure is stored at a particular position in the array and can be referred by the numeric index (or position) of the data in the data structure. It is vital to store the data in indexed form with the index sorted numerically because computers perform millions of operations in a second and data stored in indexed form can be referenced using the numerical value. This way the entire data structure can be traversed by simply incrementing the index’s value, and the values can be accessed with ease.
Here’s an example. In this case, we’ll start the Java Programming Bank out with 100 new accounts, and each one will have its own entry in an array named accounts[]. The square braces at the end of the accounts[]
represent that it is an array and the value of the index can be placed enclosed in those braces to refer to the value stored at a particular position. Here’s how we create the accounts[] array, making each entry in it of the floating-point type double for extra precision. First, we declare the array; then, we create it with the new operator, which is what Java uses to actually allocate memory:
public class App {
In Depth public static void main(String[] args) {
double accounts[];
accounts = new double[100];
. . .
Now that we have created an array with 100 items, we can refer to those items numerically, like this (note that we are storing $43.95 in account 3 and printing that amount out):
public class App {
public static void main(String[] args) { double accounts[];
accounts = new double[100];
accounts[2] = 43.95;
System.out.println("Account 3 has $" + accounts[2]); } }
Here’s the result of this program:
C:\>java App
Account 3 has $43.95
As you can see, you can now refer to the items in the array by using a numeric index, which organizes them in an easy way. In Java, the lower bound of an array you declare this way is 0, so the statement accounts = new double[100] creates an array whose first item is accounts[0] and last item is accounts[99].
You can combine the declaration and creation steps into one step, as shown below:
public class App {
public static void main(String[] args) { double accounts[] = new double[100];
accounts[2] = 43.95;
System.out.println("Account 3 has $" + accounts[2]); } }
You can also initialize an array with values when you declare it if you enclose the list of values you want to use in curly braces, as you’ll see in this chapter. For example, this code creates four accounts and stores 43.95 in single list of numbers that you can index with one number. However, arrays can have multiple dimensions in Java, which means you can have multiple array indexes. In this next example, we’ll extend accounts[] into a two-dimensional array—accounts[][]—to handle both a savings account and a checking account. The first index of accounts[][] will be 0 for savings accounts and 1 for checking accounts, and the second index will be the account number as before. Here’s how this works in code:
public class App {
public static void main(String[] args) { double accounts[][] = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" + accounts[1][2]); } }
After creating a two-dimensional array, values in it can be referenced using two index values. For example, here we are assuming the value 0 for savings account and 1 for checking account. The savings account details in the account number 3 can now be referenced as accounts[0][2] and that in the checking account can be referenced as accounts[1][2]. Shown here are the results when you run this application:
C:\>java App
Savings account 3 has $43.95
Checking account 3 has $2.38548938206E9
Note that we have given account 3 a checking balance of $2,385,489,382.06 (wishful thinking) and that Java has printed that out as 2.38548938206E9. This is Java’s shorthand for 2.38548938206X109—not an inconsiderable bank balance by any means.
You’ll see a lot of arrays in this chapter, but you should know that Java now supports much more complex data structures than arrays. These data structures are built into the language. Java now supports hashes and maps as well as other types of data structure, and as you’ll see all that when we take a look at the collection classes in the forthcoming chapter.
Strings
You may have noticed that we have been using the + operator to create the text to print in the previous examples like this:
public class App {
public static void main(String[] args) { double accounts[][] = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" + accounts[1][2]); } }
That’s because their own class in Java—the String class—supports text strings and you can think of the String class as defining a new data type.
For example, here’s how we create a string named greeting that holds the text “Hello from Java!”:
public class App {
public static void main(String[] args) { String greeting = "Hello from Java!";
. . .
Now we can treat this string as we would other types of variables, including printing it out:
public class App {
public static void main(String[] args) { String greeting = "Hello from Java!";
System.out.println(greeting); } }
Here’s the result of this application:
C:\>java App Hello from Java!
Although strings are not one of the simple data types in Java, yet they deserve a place in this chapter because most programmers treat them as they would any other data type. In fact, many programmers would argue that strings should be a simple data type in Java as they are in other languages. The reason they are not has to do with Java lineage, which stretches back to C. C has no string simple data type; in C, you handle strings as one-dimensional arrays of characters, which is pretty awkward. One of the things that made programmers happy about C++ was that most implementations included a String class that you could use much as you would any other data type. Java follows this usage, implementing strings as a class, not as an intrinsic data type, but string handling is so fundamental to programming that it makes sense to start looking at string variables in this chapter.
There are two string classes in Java—String and StringBuffer. You use the String class to create text strings that cannot change, and you can use StringBuffer to create strings you can modify. As you can see in the preceding code, you can use strings much as you would any simple data type in Java. We’ll take a look at using strings in this chapter as well as in the next chapter (which is on using operators such as + and –). We’ll also take a look at using operators on strings.
That’s enough overview for now—it’s now time to start creating and using variables, arrays, and strings.
Immediate Solutions