Using Object Variables - Java eLearning Kit For Dummies (2014)

Java eLearning Kit For Dummies (2014)

Chapter 3. Using Object Variables

· Object data types make it possible to create complex data storage variables.

· Java makes it possible to process information that appears along with the application as command line arguments.

· It’s possible to convert primitive variables into object variables to use the additional features that objects provide for manipulating data.

· Using scope makes it possible to hide information from parts of the application that don’t need to see it.

· The new date and time API makes it possible to interact with date and time values with less code and effort.

· Using enumerations reduces the chance of someone providing an incorrect value to your code.

lingo_fmt.tif

1. What is the difference between a primitive type and a reference type?

A primitive type is simply a value, while a reference type is an object, as described on page 79

2. Is it possible to convert a primitive type to an object type?

Java uses boxing to place a primitive type into an object container, as described on page 86

3. How do I make two strings into one string?

Because strings are a reference type, you use a process called concatenation to put them together, as described on page 110

4. What is a command line argument?

A command line argument is information that the user can pass directly to your application as part of starting the application, as described on page 90

5. Why is scope important?

Hiding information that other parts of the application don’t need to see makes your code easier to understand, more reliable, and more secure, as described on page 95

6. How do I interact with date and time values effectively?

Using the new date and time API makes it possible to work with both date and time values in a number of new ways, as described on page 103

7. Is it possible to tell others that I need specific input values?

Enumerations make it possible to specify that you require specific values as input to your code, as shown on page 106

An object is different from a primitive type in that an object is actually a class, just like the many classes you‘ve been creating throughout this book. An object has methods, properties, and events associated with it. Objects can also contain a wealth of variable types that you can’t create using the primitive types described in the “Working with the Primitive Types” section of Chapter 2. The number of object types you can create is limited only by need and imagination. Objects can also contain complex data and have special behaviors.


LINGO

Every Java class produces an object, even the classes you’ve created throughout this book. An object can have methods that define how the object interacts with data. For example, an Add() method might define how an object can add information to existing data. In addition to methods, objects can have properties and events. A property is a characteristic of the data that the object contains. For example, an object that represents a car could have a color property. An event is Java’s way of allowing the object to listen to outside activities and react to them. For example, a pushbutton object in an application window could have a click event that occurs when the user presses the pushbutton using the keyboard or mouse. You’ve already used object methods, such asSystem.out.print() in the applications you created earlier in the book.


Every application you create has at least one variable — the args variable — which is provided as an argument to main(). This chapter tells how to use args to perform useful tasks in an application. Using args to change application behavior is called processing command line argumentsbecause the changes are made as part of what the user types after the application name at the command line.

It’s also possible to tell Java to make some variables accessible by everyone and to hide other variables from view. The visibility of a variable is its scope. A public variable is visible to everyone, while a private variable is hidden from view. (Scope also applies to methods, which can be hid from view as well.) This chapter discusses scope so you know how to give variables the right level of visibility.


LINGO

Scope determines which part of an application can see specific variables. You use scope to hide some kinds of information, but to make other sorts of information visible.


You want to store data in a primitive type most of the time to gain the speed and memory savings that primitive types provide. However, at some point you might need to convert that primitive type to an object in order to more easily change the information it contains using the methods the object form provides. Fortunately, Java makes it possible to convert primitive types to specific kinds of objects and specific kinds of objects back to primitive types. This chapter describes the process so that you can use this technique in the applications you create.

Java used to have problems with dates and times. In Java 8, you gain access to all sorts of interesting new date and time functionality. The new date and time objects are so numerous that it would actually take several chapters to cover them all. This chapter provides a good overview of some of the most commonly used date and time functionality.

This chapter also demonstrates the basic use of a special object — the enumeration. An enumeration is an object that provides access to a fixed set of values, such as the days of the week. Humans use enumerations all the time without thinking about it. Computers require a lot more help in the form of a special enumeration object. (Chapter 7 introduces you to some more advanced uses of enumerations.)

Working with Common Objects

Java places thousands of objects at your disposal, all of which manage data in some way. The number of available objects can be overwhelming at first. However, you’ll use some common objects quite often and it’s best to get introduced to the whole idea of objects by using them. The following sections describe the most common objects that you’ll work with when writing Java applications.

String

A String is essentially text. Think of it as a list of char variables placed in a class that treats them as a unit. Most applications have a multitude of String objects in them — perhaps because humans tend to communicate using text and are most comfortable using text. Of course, the computer sees numbers — it doesn’t understand text, but the String object lets you manipulate the text in a way that puts a computer at ease. Nearly every example in the book so far has had a string or two in it. You didn’t create the object, but merely sent the string directly to theSystem.out.print() method.

The String data type is extremely flexible so I can’t demonstrate everything it can do in a single chapter. The example in this section does show something important. You’ve tried several incarnations of the example in the “byte” section of Chapter 2, but in this exercise you finally see a version that works!

Files needed: StringObject.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;
import java.lang.String;

public class StringObject
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetString = new Scanner(System.in);

// Obtain a byte value.
System.out.print("Type any string: ");
String MyString = GetString.nextLine();

// Display the value on screen.
System.out.println("The value of MyString is: " + MyString);
}
}

This example works much like the example in the “byte” section of the Chapter 2. The difference is that you’re working with a String object this time. String objects are exceptionally flexible, so there isn’t just one Scanner object method for working with them. This example shows how to use the nextLine() method to fill the String object (labeled MyString here) with data, but you’ll see other methods as the book progresses.

3. Save the code to disk using the filename StringObject.java.

4. In your command prompt, type javac StringObject.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java StringObject and press Enter.

The application asks you to type any string. A string can consist of just about anything.

6. Type 3 and press Enter.

The application outputs the expected value of 3.

7. Type java StringObject and press Enter, then type –15 and press Enter.

The application outputs the expected value of –15.

8. Type java StringObject and press Enter, then type 128 and press Enter.

The application outputs the expected value of 128.

9. Type java StringObject and press Enter, then type C and press Enter.

The application outputs the expected value of C. The ShowByte version of the program stops here, but let’s try one last entry.

10. Type java StringObject and press Enter, then type Strings Work Great! and press Enter.

Not surprisingly, you see the expected output. Figure 3-1 shows that this amazing program can handle all the input you’ve provided to it! Strings aren’t the best object in the world for everything, but they’re extremely versatile and indispensable for most application development.

9781118098783-fg0301.tif

Figure 3-1:

Calendar

Believe it or not, you’ve already worked with the Calendar type. The example appears in the “int” section of Chapter 2. A Calendar provides access to both time and date values. You can obtain the current time and date, manipulate them for any time zone in the world, create new times and dates as needed, and generally perform any task that you might need to create a calendar within an application.

Java 8 provides access to new date and time classes. You can read about these classes in the “Using the New Date and Time API” section of this chapter. These classes will eventually replace the functionality provided by the Calendar type. However, for now you need to know about theCalendar type because it appears in a large number of existing applications. When you create new applications, rather than change existing applications, try to use the new date and time classes so that your application will continue to work well into the future.


GO ONLINE

Java has an even older class than Calendar called Date that you can also use to work with time and date values. Date objects work similarly to Calendar objects, but with less functionality. Generally, you’re better off using the Calendar object when working with date and time in existing applications. However, it’s helpful to know about both classes. You can read about the Date class at http://docs.oracle.com/javase/7/docs/api/java/util/Date.html. The site at http://www.java-forums.org/java-tutorials/2775-java-date.html provides some simple examples you can try.


BigDecimal

Creating a decimal number in Java is an approximation. I could give you a really long and complex explanation of what happens, but the simple answer is that the float and double data types are using base 2 values, which is what a computer understands. (We humans rely on base 10 values.) Some numbers simply don’t translate very well between the two bases. To overcome this problem, you can tell Java to use a special class called BigDecimal to represent decimal values in base 10, rather than base 2. The benefit of using BigDecimal is that your application becomes significantly more accurate — a requirement when performing financial calculations or a trip to Mars. The down side is that BigDecimal requires more processing cycles (making your program slower) and uses more memory. So, you use BigDecimal only when needed.


EXTRA INFO

The inability of Java to represent floating point numbers accurately doesn’t stem from some problem inherent to Java, so no amount of work you perform in Java will fix this problem. The problem exists in the way the processor in your machine works — which means every computer language has precisely the same problem. Just about every computer language in existence has a decimal type of some sort to handle situations where absolute accuracy is required and the decimal type has precisely the same benefits and limitations as its Java counterpart in every case. To see the actual math behind this inaccuracy, check out the article at http://en.wikipedia.org/wiki/Floating_point. You can find a Java-specific article about floating point numbers athttp://www.ibm.com/developerworks/java/library/j-math2/index.html.


It’s hard to understand precisely how inaccurate float and double are unless you see them in action for yourself. In the following exercise, you first create an application that demonstrates the inaccuracy of double and you then compare the inaccuracy of double to the accuracy ofBigDecimal.

Files needed: DecimalObject.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.math.BigDecimal;

public class DecimalObject
{
public static void main(String[] args)
{
// Create a decimal type from a float.
BigDecimal Value1 = new BigDecimal(4.395f);

// Because float relies on a base 2 

// representation
of the number, 

// the output isn't what you'd expect.
System.out.print("Using a float is inaccurate: ");
System.out.println(Value1);

// Create a decimal type from a double.
BigDecimal Value2 = new BigDecimal(4.395);

// Using a double is slightly more accurate.
System.out.print("Using a double is inaccurate: ");
System.out.println(Value2);

// Create a decimal using a String instead.
BigDecimal Value3 = new BigDecimal("4.395");

// The output is what you'd expect this time.
System.out.print("Using a String is accurate: ");
System.out.println(Value3);
}
}

This application answers the important question of just how accurate the float and double data types are. It converts these variables to the BigDecimal type to show what happens during the conversion. You’ll be surprised at the result.

remember.eps Notice that the application creates Value1 by calling new Big
Decimal(4.395f). The f after 4.395 tells the compiler to use a float, rather than a double. You can use the same notation any time you want to use a float, rather than a double, in your own applications.

3. Save the code to disk using the filename DecimalObject.java.

4. In your command prompt, type javac DecimalObject.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DecimalObject and press Enter.

The application outputs the actual result of converting a float, and then a double to a BigDecimal (and the accompanying inaccuracy) as shown in Figure 3-2. Compare this to the BigDecimal output created using a String input (where no conversion between numeric types occurs). The difference is tiny between a float and a double — about 0.0000000190734859017993585439398. The difference between a double and BigDecimal is even smaller — about 0.0000000000000004263256414560602. Even so, such incredibly small differences can quickly become a problem when working with really large numbers, such as those used by financial institutions and the space program.

9781118098783-fg0302.tif

Figure 3-2:

tip.eps You have one way to avoid using BigDecimal to perform accurate math operations. You can use an integer type, such as short, int, or long, to perform the math operations, convert the result to a string, and artificially place the decimal point in the right place. For example, let’s suppose you need to add 1.01 to 4.395. You’d convert 1.01 to 1010 and 4.395 to 4395, then you’d add the numbers together to produce 5405. Change the result to a string and then add a decimal point at the right place to produce a displayed output of 5.405. Using integer math is a time honored way to avoid decimals on a computer altogether. However, this solution can prove tricky at times and even with 64-bits of accuracy, some numbers are simply too large or too small for the long data type to represent. The “BigInteger” section has a solution to this problem.

BigInteger

Sometimes you need an integer value that can have more than 64-bits of accuracy. Programmers often need to create extremely large numbers. When that time comes for you, you can use a BigInteger to perform the required math. A BigInteger doesn’t have a boundary — you can make it as large as needed to hold any value (assuming you have the required computer memory). Of course, BigInteger also comes with speed and memory usage penalties, so you don’t want to use it all of the time — every choice you make when writing code has consequences, so you must make these choices carefully.

When a number grows too large for the variable container used to hold it, the container overflows. For example, if you try to store 33-bits of data in an int container, Java will retain 32-bits worth of data and let the remaining bit overflow without displaying an error. As with any container that overflows, you lose something when your number overflows — the number is no longer the same and it doesn’t accurately represent the value you want to save. Of course, you could always move up to a long to overcome problems with an int.

In this exercise, you see what happens when a long variable overflows and how you can correct the problem by using BigInteger.

Files needed: BigIntegerObject.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.math.BigInteger;

public class BigIntegerObject
{
public static void main(String[] args)
{
// Create a long that contains the maximum value.
long Overflow = 9223372036854775807l;

// Display the value so you can see 

// it works fine.
System.out.println("Initial Overflow value: "
+ Overflow);

// Create an overflow condition and display it.
Overflow = Overflow + 1;
System.out.println("Overflow + 1 value: " + Overflow);

// Create a BigInteger that contains a maximum
// long value.
BigInteger NoOverflow =
BigInteger.valueOf(9223372036854775807l);

// Display the value so you can see 

// it works fine.
System.out.println("Initial NoOverflow value: "
+ NoOverflow);

// Add 1 and see what happens.
NoOverflow = NoOverflow.add(BigInteger.ONE);
System.out.println("NoOverflow + 1 value: "
+ NoOverflow);

// Multiply the result by 3 to see what happens.
NoOverflow =
NoOverflow.multiply(BigInteger.valueOf(3));
System.out.println("NoOverflow * 3 value: "
+ NoOverflow);
}
}

This example begins with the largest long that you can create and then adds 1 to it. The variable overflows. It’ll be interesting to see what happens. The BigInteger type is supposed to overcome this limitation, so the example does precisely the same thing to a BigInteger variable. In fact, it then multiplies this result by 3. If BigInteger lives up to its billing, NoOverflow shouldn’t overflow despite the really large number it holds.

remember.eps As with the float and double, you can control whether Java creates an int or a long. This example creates a long by adding l to the end of the number. Otherwise, the compiler could assume that you meant to create an int and raise an error.

Because BigInteger is an object, it has special methods for performing math tasks. Assign values to a BigInteger by calling the valueOf() method with the desired value. This example shows two math operations: addition and multiplication. To add 1 to a variable, you must use theBigInteger.ONE constant, rather than add 1 directly. In addition, you can’t use the + sign. You must call the add() method instead. Likewise, multiplication is performed using the multiply() method.

3. Save the code to disk using the filename BigIntegerObject.java.

4. In your command prompt, type javac BigIntegerObject.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java BigIntegerObject and press Enter.

The application outputs the initial value of Overflow without any problem as shown in Figure 3-3. However, adding 1 to Overflow creates a problem — the number is now negative! In fact, it’s the maximum negative value that a long can contain — it’s not possible to go any more wrong than that. Imagine that you’re performing integer math on a large financial calculation. The huge deposit made by your favorite contributor becomes an equally huge withdrawal. Now look at the results for NoOverflow. Adding 1 to NoOverflow produces the correct value, as does multiplying it by 3. It’s theoretically possible to create a BigInteger object the size of available memory in your machine, but you probably wouldn’t ever need a number that huge.

9781118098783-fg0303.tif

Figure 3-3:

Changing Primitive Types into Objects

As described in Chapter 2, primitive types are simply containers that hold data. There is nothing else associated with them. Primitive types are small and fast. However, primitive types are also limited. You have to write a lot of code sometimes to get the simplest things done with primitive types because they don’t contain any sort of logic to perform tasks for you.

An object has intelligence that helps you perform tasks. Some objects have more intelligence than others do, but all objects have some level of functionality that you won’t find when working with a primitive type. So, when it comes to choosing between the two, what you’re really deciding is whether you need the smaller size and faster speed of primitive types or the greater flexibility of objects. Each primitive type has an object version, as described in the following sections.

Automatic boxing and unboxing

It’s important to understand that a primitive type is a pure value, whereas an object is a value plus code used to work with that value. The act of placing a value into an object is called boxing. The object acts as a box that holds the value and lets you perform tasks with it. When you need to access the value, you remove it from the box. This is called unboxing the value. Java automatically boxes and unboxes variables for you as needed; you don’t really have to think about it. However, it’s important to know that boxing and unboxing occurs.


LINGO

Boxing a primitive type places its value inside an object. Unboxing a value removes it from the object and places it in a primitive type. You box a value to gain access to the functionality that the object can provide and unbox a value to examine it.


Byte versus byte

The Byte object contains a byte primitive type. It also provides access to a number of interesting methods for working with byte values. Along with these methods, the Byte class provides a number of static methods. (A static method is a method that you can use without creating an instance of the class.) Many classes provide access to static methods that you use to work with the class in some way. It’s important to differentiate between the class (the set of instructions used to build an object) and the object (an instance of the constructed class).

In this exercise, you work with both static and object methods to interact with the Byte type.


LINGO

A static method lets you perform a task with a class, such as discovering the minimum value that the class supports. Static methods are part of the class and you can access them at any time without first creating an instance of the class. In fact, some static methods are used to create objects.


Files needed: ByteVersusByte.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.Byte;

public class ByteVersusByte
{
public static void main(String[] args)
{
// Display some Byte object statistics.
System.out.println("Byte Statistics:");
System.out.println("Size: " + Byte.SIZE);
System.out.println("Minimum value: "
+ Byte.MIN_VALUE);
System.out.println("Maximum value: "
+ Byte.MAX_VALUE);
System.out.println("Type: " + Byte.TYPE);

// Create a few Byte variables.
Byte Value1 = Byte.valueOf("15");
Byte Value2 = Byte.valueOf((byte)15);
Byte Value3 = Byte.valueOf("15", 16);

// Display their values.
System.out.println();
System.out.println("Byte Values:");
System.out.println("Value1 = " + Value1);
System.out.println("Value2 = " + Value2);
System.out.println("Value3 = " + Value3);

// Compare two values.
System.out.println("\nByte Related Tasks:");
System.out.println("Value1 compared to Value2? "
+ Value1.compareTo(Value2));
System.out.println("Value1 compared to Value3? "
+ Value1.compareTo(Value3));

// Convert Value1 to a float.
System.out.println("Value1 float value: "
+ Value1.floatValue());
}
}

This example begins by showing a number of static methods. Most data types provide methods to discover the size of the value contained within the object, the minimum and maximum value supported by the object, and the object’s unboxed type — the primitive type you’d end up with if you unboxed the object.

The static methods also include several different methods of creating the object. This example shows how to use the valueOf() method. In this case, you can create the object using a String or a byte value. When working with a String, you can provide a radix — the base of the value. The last valueOf() method call creates a Byte object with a value of 15, base 16 (hexadecimal). If you don’t provide a radix, Java assumes you want to use base 10 (decimal) numbers.

remember.eps When you create a Byte using a numeric value, you must add (byte) in front of the number. This is called casting — the process of converting an entity of one data type into another. Java assumes an int type whenever you provide numeric input. Casting tells Java that you really want to provide a byte type. Because valueOf() requires a byte as input, you must cast the int value that Java assumes you mean to a byte value.


LINGO

Casting converts one data type to another. For example, you can change an int into a byte when necessary. A cast is an important Java feature because it tells Java that it’s acceptable to perform a conversion. If you cast incorrectly, the result could be data loss and incorrect output from your application. For example, if you cast anint value of 200 to a byte value, the resulting byte value of –56 will be incorrect because a byte can’t hold a value of 200.


You can use objects directly as shown in the example. Java automatically unboxes the object to obtain the value and display it on screen. Objects also include special object-related methods, such as compareTo(), which lets you compare one value to another. The floatValue() method outputs the byte value in the Byte as a float. So you can also cast between types using a method call when such a method is provided.

This particular example also shows how to add a blank space between lines. You can either use System.out.println(); or add \n in front of the text that should appear with a space before it. The second form, \n, is called an escape character. When you use more than one pair of these characters, it’s called an escape sequence. The “Using Escape Sequences” section of Chapter 4 tells you a lot more about working with escape sequences.

3. Save the code to disk using the filename ByteVersusByte.java.

4. In your command prompt, type javac ByteVersusByte.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java ByteVersusByte and press Enter.

You see the application output shown in Figure 3-4. As you might expect, the byte value consumes 8 bits, it has a minimum value of –128 and a maximum value of 127, and it has a type of byte. Notice that Value3actually contains 21. That’s because the application creates it as a hexadecimal value of 15, which equates to a decimal value of 21. Value1 and Value2 are equal, so there is a 0 difference between them. However, there is a -6 difference between Value1 and Value3. Finally, notice that the floatValue() method actually does output Value1 as a float.

9781118098783-fg0304.tif

Figure 3-4:

Short versus short

The Short object contains all the same features that the Byte object does, so you can perform tasks such as obtaining the size, minimum value, and maximum value of the type. It also includes the same valueOf() methods.

In the following exercise, you discover a method for letting users enter numbers in octal (base 8), decimal (base 10), or hexadecimal (base 16) format.

Files needed: ShortVersusShort.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.Short;

public class ShortVersusShort
{
public static void main(String[] args)
{
// Obtain a Short value from the command line.
Short MyShort = Short.decode(args[0]);

// Display the value on screen.
System.out.println("The value of MyShort is: "
+ MyShort);
}
}

The code for this example looks and acts the same as the ShowByte example that you worked with in Chapter 2, but with a couple of important differences. Because this example works with a Short, you can use the Short.decode() method to obtain user input in octal, decimal, or hexadecimal format using specially formatted strings (as you’ll discover later in the exercise). After the user types a numeric value, the code decodes it into a Short object (labeled MyShort) and then displays the value of MyShort on screen.

In addition to the ability to work with multiple bases, this application also accepts input from the command line, rather than using a Scanner object. The difference means that you type the value you want to use at the command line, rather than separately after the program provides a prompt. This form of input is used when you need to automate an application in some way. Automation makes it possible to include the application in a script or use it in some other way that requires the application to work without user interaction.

3. Save the code to disk using the filename ShortVersusShort.java.

4. In your command prompt, type javac ShortVersusShort.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java ShortVersusShort 15 and press Enter.

The application outputs a value of 15 as expected. Notice that you don’t have to wait for a prompt. The application processes the information directly from the command line.

6. Repeat Step 5, but type a value of 015 (with a leading zero) this time.

The application outputs a value of 13. When you type a value of 015, the application sees it as octal input. In this case, octal means that the usual tens position actually equals 8. So, 8 + 5 = 13 (15 octal equals 13 decimal).

7. Repeat Step 5, but type a value of 0x15 this time.

The application outputs a value of 21, which is the decimal equivalent of the hexadecimal 15. Figure 3-5 shows the outputs of this example.

9781118098783-fg0305.tif

Figure 3-5:

practice_fmt.eps Try performing Step 5 with a value of 019. The application displays an error in this case because 9 doesn’t exist in octal — the highest value is 7. Perform Step 5 again with a value of 0x1A. You should see an output of 26. Hexadecimal values use the letters A through F to represent the decimal numbers 10 through 15. That’s right: A hexadecimal number can range from 0 through F. (That’s 0 through 15 decimal.) Try performing Step 5 with other values, both positive and negative. For example, what do you see when you type –022? Playing with this application helps you understand how different bases of numbers work on the computer.

Integer versus int

The Integer class is one of the most flexible used for data types. It includes more methods than either Byte or Short for interacting with values.

In the following example, you try out a few of the special Integer methods.

Files needed: IntegerVersusInt.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;
import java.lang.Integer;

public class IntegerVersusInt
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetInteger = new Scanner(System.in);

// Obtain an Integer value.
System.out.print("Type any number: ");
Integer MyInteger = Integer.valueOf(GetInteger.nextLine());

// Display some of the Integer outputs.
System.out.println("\nVarious Base Output:");
System.out.println("Binary MyInteger: "
+ Integer.toBinaryString(MyInteger));
System.out.println("Octal MyInteger: "
+ Integer.toOctalString(MyInteger));
System.out.println("Decimal MyInteger: "
+ MyInteger);
System.out.println("Hexadecimal MyInteger: "
+ Integer.toHexString(MyInteger));

// Display the bit information.
System.out.println("\nBit Information:");
System.out.println("Bit Count (1's): "
+ Integer.bitCount(MyInteger));
System.out.println("Highest 1 Bit: "
+ Integer.highestOneBit(MyInteger));
System.out.println("Lowest 1 Bit: "
+ Integer.lowestOneBit(MyInteger));
System.out.println("Number of Leading 0s: "
+ Integer.numberOfLeadingZeros(MyInteger));
System.out.println("Number of Trailing 0s: "
+ Integer.numberOfTrailingZeros(MyInteger));
}
}

As with some of the other examples in this chapter, this example asks the user for some numeric input and then manipulates that input in various ways. In this case, you get to see the output using various bases, and then you see some information about the actual bits used to create the value.

remember.eps Integer provides a number of other methods, but the methods shown in this example are the most useful for right now. You can also use Integer to change the position of the bits in the value. Programmers sometimes need to perform some odd tasks with numeric values andInteger is one of the most flexible classes for accomplishing such tasks.

3. Save the code to disk using the filename IntegerVersusInt.java.

4. In your command prompt, type javac IntegerVersusInt.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java IntegerVersusInt and press Enter.

The application asks you to type any number, but note that an int is limited to a range of –2,147,483,648 to 2,147,483,647.

6. Type 85 and press Enter.

You see the output shown in Figure 3-6. Notice the binary output of this application. If you really want to understand how bits work, trying various numbers out with this program will help.

Looking at the Binary MyInteger: line in Figure 3-6, you can see that there are indeed four 1s in the binary version of the output. The highest 1 is in the 64 position and the lowest is in the 1 position. There are seven digits in the binary output, which means there are 25 leading 0s, just as the application says. There aren’t any trailing 0s because the lowest position has a 1 in it.

9781118098783-fg0306.tif

Figure 3-6:

practice_fmt.eps Perform Steps 5 and 6 again to rerun the application. This time, try a value of 170. The output changes to show how this number differs from 85. More importantly, this is an example of what happens when you reverse the values of the bottom eight bits (01010101 or 85 versus 10101010 or 170). Try other values to see what happens to the output.

Long versus long

The Long class provides all of the interesting features of the Integer class, but as an added bonus has the extended storage capacity of the long type. (A long can hold numbers from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.) For example, you have access to the useful output methods such as toBinary(). The Long class also provides all of the bit manipulation features of the Integer class, so you can use it to create some really complex applications.

remember.eps Scope is an important element of application development. The scope of a variable determines which parts of the application can see it. There are many ways in which Java uses scope to control variable visibility. One of those ways is to differentiate between global and local variables. A global variable is visible to every method within the class, while a local variable is visible only to the part of the application in which the variable is defined (such as a method).

It’s time to see your first use of scope in action. In the following example, you use the Long class to learn how global and local scope works in a Java application.

Files needed: LongVersusLong.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.Long;

public class LongVersusLong
{
// Create a global variable.
public static Long MyLong;

public static void main(String[] args)
{
// Assign a value to the global variable
// and display its value on screen.
MyLong = Long.valueOf(500);
System.out.println("MyLong = " + MyLong);

// Call function1 to modify the value of
// MyLong and display the result on screen.
function1();
System.out.println("MyLong in main() = " 
+ MyLong);

// Call function2 to modify the value of
// MyLong and display the result on screen.
function2();
System.out.println("MyLong in main() = " 
+ MyLong);
}

public static void function1()
{
// Assign a value to the global variable
// and display its value on screen.
MyLong = Long.valueOf(700);
System.out.println("MyLong in function1() = " 
+ MyLong);
}

public static void function2()
{
// Create a local MyLong, assign it a value
// and display its value on screen.
Long MyLong;
MyLong = Long.valueOf(900);
System.out.println("MyLong in function2()= " 
+ MyLong);
}
}

This application demonstrates two Java features you haven’t yet had a chance to use in this book. First, it shows how to create and use methods other than main() in an application — in this particular case, two additional methods known as function1() and function2(). You’ll see a lot more examples of how methods work throughout the book, but this is the simplest way to work with them. The main() method calls function1() and function2() as needed to perform tasks. Working with methods this way helps keep your code readable by preventing methods from getting too large.

The second feature is the use of a global variable. Notice that the declaration of MyLong appears outside of the methods. All of the methods can see the global version of MyLong so it has a global scope. The function2() method also has a variable named MyLong defined in it. This is a local variable. Only function2() can see this variable, so any changes you make to it only appear in function2(). When a method has a choice between a global variable and a local variable of the same name, it always uses the local variable by default.

3. Save the code to disk using the filename LongVersusLong.java.

4. In your command prompt, type javac LongVersusLong.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java LongVersusLong and press Enter.

The application displays a sequence of outputs that demonstrate one way in which scope works in a Java application, as shown in Figure 3-7. Notice that function1() modifies the global variable, MyLong, so that main() also sees the change it makes. Meanwhile, function2()modifies alocal variable, MyLong, which means that main() doesn’t see this change. The local copy of MyLong in function2() is invisible to main().

9781118098783-fg0307.tif

Figure 3-7:

practice_fmt.eps Create a Long version of the IntegerVersusInt example described in the “Integer versus int” section of the chapter and name it LongVersusLong. Everywhere you see the word Integer, replace it with the word Long. Now run the new application to see what happens. Most of the output is the same if you use the same input values. However, there is at least one important difference. (Hint: Look at the Number of Leading 0s: output.) Try typing a really large value that you can’t use with the IntegerVersusInt program, such as 5,700,000,000 (without the commas). If you were to try a number this large with the IntegerVersusInt application, you’d see an error.

Float versus float

The Float class definitely makes working with float values easier, especially if the math you perform falls into the more esoteric range. For example, you can use the Float class to create a float value that contains either positive or negative infinity. There are concepts associated withfloat values that are well outside the scope of this book and if you’re not working with that sort of math, you’ll never need to worry about them. However, it’s nice to know that the Float class makes it possible to do some amazing things with float values.

Floating point values approximate real numbers. In the following example, you see how the Float class can interact with floating point numbers and make them easier to work with.

Files needed: FloatVersusFloat.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.Float;

public class FloatVersusFloat
{
public static void main(String[] args)
{
// Create some variables to work with.
Float Value1 = Float.valueOf(11.55f);
Float Value2 = Float.valueOf("11.55");
Float Value3 = Float.parseFloat("0.1155e2");
Float Value4 = Float.POSITIVE_INFINITY;

// Show the actual values.
System.out.println("Value1 = " + Value1);
System.out.println("Value2 = " + Value2);
System.out.println("Value3 = " + Value3);
System.out.println("Value4 = " + Value4);

// Determine some information about the values.
System.out.println("\nValue1 Compared to Value2: " +
Value1.compareTo(Value2));
System.out.println("Value1 Compared to Value3: " +
Value1.compareTo(Value3));
System.out.println("Value1 Compared to Value4: " +
Value1.compareTo(Value4));
System.out.println("Value1 Infinite? "
+ Value1.isInfinite());
System.out.println("Value4 Infinite? "
+ Value4.isInfinite());
System.out.println("Value1 Integer Portion: "
+ Value1.intValue());
System.out.println("Value3 as a String: "
+ Value3.toString());
System.out.println("Value4 as a String: "
+ Value4.toString());
}
}

The example begins by creating four Float objects, Value1, Value2, Value3, and Value4. When working with floating point values, you can assign a value using the valueOf() method, the parseFloat() method, or a constant, such as Float.POSITIVE_INFINITY. When you assign a numeric value, you either have to perform a cast, or you can simply add an f after the number to ensure Java knows that you mean to create a float, and not a double. The parseFloat() method is nice because you can use scientific notation with it. The value after the e is the exponent, so this method actually contains 0.1144 * 102.

After creating the variables, the application begins working with them. When you want to compare two values, you must use the compareTo() method, just as you do with integer-based objects. Because floating point values can be infinite, the Float class provides the isInfinite()method. You can also work with just the integer portion of a floating point number, which means that you have full access to the features provided by integer-based values such as the Integer class. The example also shows what happens when you convert a floating point value to a string.

3. Save the code to disk using the filename FloatVersusFloat.java.

4. In your command prompt, type javac FloatVersusFloat.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java FloatVersusFloat and press Enter.

The application outputs the results of the various floating point operations as shown in Figure 3-8.

9781118098783-fg0308.tif

Figure 3-8:

You should notice a few special things about the output in Figure 3-8. First of all, even if you provide input to the Float type in scientific notation, the number is stored as a standard float, so "0.1155e2" becomes 11.55. Second, any object that contains an infinite value outputsInfinity as its value. Third, you’re seeing your first Java inconsistency. When you worked with the Byte version of compareTo(), it output the actual difference between the two numbers. The Float version of compareTo() outputs a 0 when the numbers are the same, a –-1 when the first number is less than the second number (infinity is definitely greater than 11.55), and a 1 when the first number is more than the second number.

remember.eps Most programming languages contain inconsistencies because the language develops over time and is the product of many developers’ input. Always read the documentation to ensure you understand how a method works. In this case of compareTo(), the Byte and Float versions work differently, so you need to consider this difference when you write an application.

Double versus double

The Double type provides the same functionality as Float, except that it offers 64-bit precision. Consequently, you can perform the same sorts of tasks that you would with a Float. The differences between Float and Double are the same as those between float and double. A Floatconsumes less memory and could potentially offer slightly better speed, while a Double offers better precision (less error).

practice_fmt.eps Create a Double version of the FloatVersusFloat example shown in the “Float versus float” section of the chapter. Replace every instance of the word Float with the word Double. If you run the application at this point, you’ll run into something odd, as shown in Figure 3-9.

9781118098783-fg0309.tif

Figure 3-9:

Notice that Value1 doesn’t contain the value you expected. That’s because the code still assigns it the value of 11.55f (for float). The example illustrates the inaccuracies that exist when using both float and double. To fix this problem, you must remove the f after 11.55 in your code so that Java uses a double to create Value1. The results will precisely match the FloatVersusFloat example at this point.

Boolean versus boolean

There really isn’t much to say about the Boolean object type. It does offer some methods, such as valueOf(), but none of them are particularly compelling. You can’t even offer an alternative output. About the only time where you might use the Boolean object type is when working with system information. The Boolean object type includes a getBoolean() method that lets you do things like access environment variables. This is one situation where you’ll end up using the primitive type in your application in favor of the object type in most situations.

Character versus char

It may not seem as though you can do a lot with a single character, but the Character type really can do quite a lot. When you work with Character, you obtain a lot more than the value that char provides. For example, you can determine whether a character is of a particular type. This type also provides a number of ways to output the value.

remember.eps Some of the Character methods and properties are beyond the scope of this book. For example, it’s unlikely that you’re going to want to modify individual bits within a Character, but the Character type provides the means for doing so.

In this exercise, you explore some of the more common ways to work with the Character type. Just be aware that you can do more.

Files needed: CharacterVersusChar.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.Character;

public class CharacterVersusChar
{
public static void main(String[] args)
{
// Create some Characters.

Character Char1 = Character.valueOf('$');
Character Char2 = Character.valueOf('a');
Character Char3 = Character.valueOf('1');

// Determine some characteristics about the
// Characters.
boolean IsChar1Currency =
(Character.getType(Char1) ==
Character.CURRENCY_SYMBOL);

boolean IsChar2Lowercase =
(Character.getType(Char2) ==
Character.LOWERCASE_LETTER);

// Describe Char1.
System.out.println("It's " +
IsChar1Currency
+ " that the " + Char1 +
" is a currency symbol and its name is: " +
Character.getName(Char1) + ".");

// Describe Char2.
System.out.println("It's " + IsChar2Lowercase +
" that Char2 is lowercase and that " +
Character.toUpperCase(Char2) +
" is the uppercase version and " +
Character.toTitleCase(Char2) +
" is the title case version.");

// Describe Char3.
System.out.println("Char3 has a value of " +
Character.getNumericValue(Char3) +
". It's " + Character.isDigit(Char3) +
" that Char3 is a digit.");
}
}

This example doesn’t begin to show you everything the Character class can do with individual characters, but it does give you some ideas. To begin, there isn’t anything fancy about creating a Character. The only option you have is the valueOf() method.

After you have a character to work with, you can start learning all sorts of things about it. For example, you can determine whether the character is a currency symbol or whether it’s a lowercase letter. Whenever you want to learn about the kind of character you’re working with, you call the getType() method and then compare the output against Character constants such as CURRENCY_SYMBOL.

Use the getName() method to obtain the official Unicode name for any character. Because these names are constant and unique, you can check the precise input the user has provided. Character also provides methods such as isDigit() that let you perform additional checks on the character value.

You have access to a number of output features. The toUpperCase(), toLowerCase(), and toTitleCase() methods are the ones that you’ll use most often.

3. Save the code to disk using the filename CharacterVersusChar.java.

4. In your command prompt, type javac CharacterVersusChar.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java CharacterVersusChar and press Enter.

Figure 3-10 shows the output of the Character class features used in this exercise.

9781118098783-fg0310.tif

Figure 3-10:

Using the New Date and Time API

In the past, Java lacked a good way to work with date and time values. Yes, there were two attempts to address the problem using the Date class first and then the Calendar class, but they proved clunky. Java 8 fixes this problem by creating an entire API devoted to date and time with special classes for each. The following sections describe the date and time API from an overview perspective.

Viewing the date and time API

Java developers have been asking for better date and time management functionality for a long time. Working with the older Date and Calendar classes was difficult, and you couldn’t easily do things such as compare two time values. The new date and time API is immense, but it contains most of the features that developers have requested.

There are a lot of classes that you could use to interact with the date and time. However, you use the following classes most often:


GO ONLINE

The Java 8 date and time API is so large that it would be impossible to cover in a single chapter, much less a section of a chapter. However, you can see the various classes used for the date and time API in detail athttp://download.java.net/jdk8/docs/api/.



EXTRA INFO

A time zone shows the offset from Universal Time Coordinated (UTC). For example, Central Time in the United States has a UTC offset of –06:00, which means that it’s six hours behind the International Atomic Time (TAI) that is maintained by the world time server. You can see the current world time server time at http://www.worldtimeserver.com/current_time_in_UTC.aspx.


· Instant: A specific point in time. The time value is defined as the number of nanoseconds that have passed since 1 January 1970.

· LocalDate: The date as it appears on the host system in a year, month, and day format. The output doesn’t include the time zone or the time value.

· LocalDateTime: The date and time as it appears on the host system in a year, month, day, hours, minutes, and seconds format. The output doesn’t include the time zone.

· LocalTime: The time as it appears on the host system in a format of hours, minutes, and seconds. The output doesn’t include the time zone or date value.

· MonthDay: A month and day value without any corresponding year. You can use this value to represent recurring date values, such as anniversaries and birthdays.

· OffsetDateTime: The date and time as it appears on the host system in a year, month, day, hours, minutes, and seconds format. The output includes a time zone value.

· OffsetTime: The time as it appears on the host system in a format of hours, minutes, and seconds. The output includes a time zone value.

· Year: A year value without any other information. You could use this value for elements such as headings on a calendar.

· YearMonth: A year and month value without any corresponding day. You can use this value to represent recurring monthly events where the day of the event isn’t important.

· ZonedDateTime: The date and time as it appears on the host system in a year, month, day, hours, minutes, and seconds format. The output includes an enumerated time zone value, such as America/Chicago. You can see a listing of the human-readable time zones at http://joda-time.sourceforge.net/timezones.html.

Creating and using dates and times

The new date and time API provides considerable flexibility for working with both date and time values in your application. More important, you gain access to a number of new methods that make working with dates and times easier. The following example can’t show everything that the date and time API is capable of doing, but it gives you a basic idea of what you can expect.

Files needed: Java8DateTime.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen:

// Import the required API classes.
import java.time.*;

public class Java8DateTime
{
public static void main(String[] args)
{
// Display a time value.
System.out.println("Local Values");
System.out.println("Local Time: "
+ LocalTime.now().toString());

// Display a date value.
System.out.println("Local Date: "
+ LocalDate.now().toString());

// Display both the time and the date.
System.out.println("Local Date and Time: "
+ LocalDateTime.now().toString());

// Display the date and time with time zone.
System.out.println("\nTime Zone Values");
System.out.println("Numeric Time Zone: "
+ OffsetDateTime.now().toString());
System.out.println("Enumerated Time Zone: "
+ ZonedDateTime.now().toString());
}
}

remember.eps The classes you use most often when working with the date and time API are found in the java.time package. There are other packages that you may need from time to time, but when working with just date and time values, this is the only package you need.

This example shows how to obtain local time or date without regard to time zone and time or date with time zone included. You use time zone information when working with applications that could span a wide area. The time zone makes it possible to calculate the difference in time between New York and San Diego, as an example.

3. Save the code to disk using the filename Java8DateTime.java.

4. In your command prompt, type javac Java8DateTime.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java Java8DateTime and press Enter.

Figure 3-11 shows the output of the various date and time classes used in this exercise. Notice that when you output either a date or a time alone, the value appears without special formatting. However, when you output date and time together, the output appears with a T between the date and the time to indicate the start of the time information.

9781118098783-fg0311.tif

Figure 3-11:

Working with Enumerations

In some cases, you want to create a list of specific values to use within an application. For example, you might want to create a list of month values from January to December so that it’s not possible to select any other value. A list of values like this is called an enumeration.

remember.eps Using this approach makes your application more reliable and reduces the chances of security risks because it isn’t possible to supply a value that the developer didn’t expect. People who want to break into your application (for any reason — not just as part of an intrusion) often look for ways to supply values that will cause the application to crash, which can cause data damage and potentially open the data to unauthorized viewing (among other issues). In addition, using enumerations can make your code easier to use. The following example demonstrates how to use a simple enumeration. You see a more complex example of enumerated values in Chapter 7.

Files needed: Enumerations.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen:

public class Enumerations
{
// Create an enumeration.
public enum Colors
{
Yellow,
Blue,
Red,
Green,
Purple
}

public static void main(String[] args)
{
}
}

This enumeration exists outside of the main() function within the class as a separate entity. You can also define enumerated values within separate files so that you can use them throughout one or more applications. All enumerations are public and use the enum keyword, followed by the name of the enumeration, which is Colors in this case. You then define a list of colors separated by commas.

3. Type the following code into the main() function:

// Display an enumerated color by name.
System.out.println("The color is: " + Colors.Blue);

// Display an enumerated color by value.
System.out.println("The color is: " + Colors.values()[2]);

There are two common techniques for accessing enumerations. The first is directly by name, as shown in the first System.out.println() statement. This approach makes your code more readable and reduces any chance that someone will misinterpret the code.

The second technique is to access the enumeration by numeric value. Enumerated values begin at 0, so a value of 2 would point to the color Red in the list.

4. Save the code to disk using the filename Enumerations.java.

5. In your command prompt, type javac Enumerations.java and press Enter.

The compiler compiles your application and creates a .class file from it.

6. Type java Enumerations and press Enter.

Figure 3-12 shows the output of the enumeration you created.

9781118098783-fg0312.tif

Figure 3-12:

summingup_fmt.eps Summing Up

Here are the key points you learned about in this chapter:

· The BigDecimal data type helps you perform extremely accurate calculations using real numbers (those with both an integer and decimal portion).

· The BigInteger data type lets you perform huge calculations using integer numbers. It doesn’t theoretically have a limit in size, other than the availability of memory in a system.

· Object versions of primitive types provide additional flexibility that makes it easy to manipulate the value the object contains.

· Application developers commonly use the binary (base 2), octal (base 8), decimal (base 10), and hexadecimal (base 16) numbering systems to create applications.

· The Character data type provides the means for detecting precisely what sort of character the variable contains.

· The new date and time API includes a number of date and time classes that you can use to work with date and time values.

· Enumerations provide a method for listing specific values that a user can’t change.

Try-it-yourself lab

For more practice with the features covered in this chapter, try the following exercise on your own.

1. Open the LongVersusLong application.

2. Add the code shown in bold to the function2() method.

public static void function2()
{
// Create a local MyLong, assign it a value
// and display its value on screen.
Long MyLong;
MyLong = Long.valueOf(900);
System.out.println("MyLong in function2()= " + MyLong);

// Change the global MyLong, assign it a value,
// and display its value on screen.
LongVersusLong.MyLong = Long.valueOf(1000);
System.out.println("Global MyLong in function2()= " +
LongVersusLong.MyLong);
}

The new code lets function2() modify the global MyLong by providing a specific reference to it. Using LongVersusLong.MyLong forces function2() to ignore the default scope and use the global variable instead.

3. Compile the application.

4. Run the application.

The application provides output based on the new code you’ve added.

5. Compare this output to the output you see in Figure 3-7.

This version of the application demonstrates another feature of scoping rules in Java. It’s possible to override the scoping rules in some cases, as long as the required variable isn’t hidden from view (as in the case of the global MyLong).

Know this tech talk

· boxing: The act of placing a value into an object for the purpose of manipulating the value with the help of the object’s features.

· casting: The act of converting one type into another type.

· concatenation: The act of adding two strings together to create a single string. For example, if String1 contains Hello (note the space after the word Hello) and String2 contains World, concatenating the two strings would produce Hello World.

· data: A series of 1s and 0s assigned to a specific location in memory.

· escape character: A single special control character used to modify the output of an application. For example, the /n escape character adds an additional line between two lines of output.

· escape sequence: Two or more escape characters used to modify the appearance of information on screen. For example, the /t/t escape sequence would add two tabs to the output, which would control the position of text on screen.

· floating point number: An approximation of a real number, which is a number that has both an integer and a decimal portion, such as 5.1.

· information: Data that has been assigned a type in order to give it meaning and make it possible to interpret what the data means.

· object: A class used to hold a specific kind of data that has methods, properties, and events. An object can have special behaviors that let it interact with the data in unique ways.

· overflow: An overflow occurs when an application attempts to create a value larger than the type is designed to hold. Java gets rid of the extra information and keeps just the bits that the type can successfully hold. Unfortunately, Java doesn’t display an error message when this happens, so your application blissfully continues to run with the error in place. Use the BigInteger data type to prevent errors from occurring when performing integer math.

· real number: A number that has both an integer and a decimal portion, such as 5.1. Some developers also call real numbers floating point numbers, but this isn’t precisely true. A floating point number is merely an approximation of a real number.

· scope: The visibility of a variable or method to other parts of an application.

· unboxing: The act of removing a value from an object and placing it into the corresponding primitive type.