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

Java eLearning Kit For Dummies (2014)

Chapter 2. Using Primitive Variables

· Different variable types make it possible to store specific kinds of information.

· Each variable type requires a different amount of storage space in computer memory.

· Constant values store a specific value for the life of the application.

lingo_fmt.tif

1. How does the computer know the difference between a number and text?

The computer doesn’t actually understand the difference, but your application defines the difference, as described on page 50

2. Why do variables have different sizes?

A smaller variable uses less memory and enhances speed, while a larger variable allows storage of larger values, as described on page 51

3. What does it mean to increment or decrement a variable?

Incrementing a variable adds one to it, while decrementing a variable subtracts one from it, as described on page 56

4. What is the difference between an integer type and a floating point number type?

Not only is what they store different, but the way the computer sees them is different, as described on page 61

5. What is the purpose of the boolean data type?

You use boolean values to determine the truth value of an expression, as described on page 65

6. How does getting a char value differ from other variable types?

A char type requires that you separate an individual character from the rest of the characters on the line, as described on page 67

7. Do constants have a specific type?

You can create a constant using any variable type, as described on page 69

8. Why would you use constant values in an application?

Constants provide some significant advantages in memory usage, application execution speed, and security, as described on page 50

This chapter discusses variables because you can’t write most applications without using variables. In fact, you’ve already worked with variables in the SayHello and SayHello2 applications described in Chapter 1. A variable is a sort of box that holds information as data. When you want to store information in Java, you create a variable to hold it. The variable is actually a piece of computer memory that stores the information as binary data for you. The way in which your application interprets the data at a memory location gives it value and changes it from simply a number into information you can use.

Variables are categorized by the kind of information they store. The computer sees the information only as 1s and 0s. The letter A is actually the number 65 to the computer. As far as the computer is concerned, your data is simply a set of numbers stored in specific memory locations. It’s the application that determines the sort of data stored in that memory location. Making data into a specific kind of information is called assigning a type to that data. Assigning a type to a variable helps the application interpret the data it contains.


LINGO

Data is numbers assigned to specific memory locations on a computer. The data is actually stored as sequential 1s and 0s. A computer has no understanding of the data and doesn’t do anything with it other than store it in the required memory location. An application can give the data a type, which defines the 1s and 0s as a specific kind of information. Information is an interpretation of the 1s and 0s. For example, the computer may see the number 65 (actually, the binary form of 1000001, which equates to 65 decimal) stored in a specific location, but the application may interpret that data as the letter A.


This chapter looks specifically at primitive types. A primitive type is one that consists of data only. The information contained within a variable of a primitive type is one of the following:

· An integer number — numbers that can be written without a fractional or decimal component (byte, short, int, or long)

· A floating point number, which has an integer and a decimal part (float or double)

· A true or false value (boolean)

· A single character (char)

You’ll also discover constants in this chapter. Constants are a special kind of variable that hold the same value throughout application execution. Constants are useful for a number of reasons:

· They use less memory

· They improve application execution speed

· They are more secure because no one can change them


EXTRA INFO

Oracle currently has plans for creating a unified type system for Java 10. This means that there would no longer be primitive types in Java — everything would be an object. Just how Oracle plans to implement this change isn’t clear at the moment and it may not even happen, but it’s always a good idea to keep track of changes that could occur to the language. For now, primitive types offer clear advantages and you should use them as appropriate, but keep in mind that future versions of Java may not support them.


Working with the Primitive Types

It’s important to use the right type for a particular purpose. Otherwise, your application won’t know how to interpret the data it creates and provide the user with the correct output.

Besides the way in which the application interprets the data as information, the main difference between these types is their size (measured in bits). Each bit is one little piece of memory — it can be either a 1 or a 0. Combining bits makes it possible to create larger numbers or more complex information. Table 2-1 shows the primitive types that Java supports.

Table 2-1 Java Primitive Types

Type Name

Number of Bits

Range of Values

byte

8

–128 to 127

short

16

–32,768 to 32,767

int

32

–2,147,483,648 to 2,147,483,647

long

64

–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float

32

1.40129846432481707–45 to 3.40282346638528860+38 (positive or negative)

double

64

4.94065645841246544–324 to 1.79769313486231570+308 (positive or negative)

boolean

1

true or false

char

16

Any single 16-bit Unicode character including common letters such as A, the numbers 0 through 9, and common symbols such as !

Table 2-1 demonstrates something important. As the number of bits consumed by a variable increases, the range of values it can contain also increases. The type tells how to interpret the memory used by the variable. The same memory can hold one long, two int, four short, or eight bytevariables. Only the type tells the application how to look at that memory.

tip.eps Use smaller variables to improve application memory usage and execution speed. Larger variables allow your application to process greater values. It’s important to choose the correct variable size for a specific use to ensure your application works as fast and efficiently as possible.

Now that you have an overview of the primitive types, it’s time to look at them in detail. The following sections demonstrate how each of the primitive types work.

byte

The byte type consumes eight bits — one byte of the computer’s memory. Each bit can be either a 1 or a 0. The combination of 1s and 0s determines the value of the byte. A byte-sized variable can hold any value between –128 and 127 or 256 different values (including 0).


LINGO

A bit is a single memory location containing either a 0 or a 1. A byte consists of eight bits. The most significant bit determines whether a byte is positive or negative. So, a binary value (a group of bits) with a value of 10000001 has a decimal value of –127, while a binary value of 00000001 has a decimal value of 1. When the leftmost bit is a 1, the value is negative.


In the following exercise, you create an application that interacts with a variable of type byte.

Files needed: ShowByte.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;

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

// Obtain a byte value.
System.out.print("Type any number: ");
byte MyByte = GetByte.nextByte();

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

In this example, GetByte is a Scanner object that obtains (gets) the user’s input from the keyboard. The GetByte.nextByte() method scans the next byte input from the keyboard and places it in MyByte, of type byte. The application then outputs the value of MyByte to screen.


LINGO

It’s important to remember that GetByte is an object of type Scanner. (Scanner is part of the Java API, so you don’t need to worry too much about it now, except that it helps you obtain input from the user.) On the other hand, MyByte is simply a number — not an object — of type byte. A byte value is a number, an actual data location in memory, not an object.


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

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

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

5. Type java ShowByte and press Enter.

The application asks you to type any number. As mentioned in Table 2-1, a byte is limited to a range of –128 to 127.

6. Type 3 and press Enter.

The application outputs the expected value of 3 as shown in Figure 2-1. So, what happens if you try a negative value?

9781118098783-fg0201.tif

Figure 2-1:

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

The application outputs the expected value of –15 as shown in Figure 2-2. Now it’s time to have a little fun. When creating any application, you must assume that someone will enter the wrong information. Users could easily type a value that’s too large.

9781118098783-fg0202.tif

Figure 2-2:


LINGO

An exception occurs whenever the application experiences something unexpected, such as incorrect user input. The exception output tells you what went wrong, provides the incorrect input (when appropriate), and shows you where the error occurred in your source code. All of this information helps you understand the exception and do something about it.


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

The value you just typed is one larger than byte can support. The application doesn’t output the value you typed. Instead, the application outputs a whole bunch of text as shown in Figure 2-3.

If you read the first line of output, you’ll see the source of the problem. Java tells you that the number you typed is out of range. It then tells you what you typed (128). The last line tells you precisely where the error occurred in the source file. For now, you don’t need to worry about the remaining information because you seldom need it. All of this information is called an exception. An exception occurs any time your application experiences a problem, such as incorrect input from the user.

9781118098783-fg0203.tif

Figure 2-3:

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

The value you just typed isn’t even a number. Notice that the application provides an exception again, but this time the exception is different. The exception shown in Figure 2-4 tells you that the type of the input — a letter in this case — doesn’t match the expected input, which would be a byte. (Just another example of how Java helps you understand when applications go wrong, why they’ve gone wrong, and how to fix them.)

9781118098783-fg0204.tif

Figure 2-4:

short

The short type consumes 16 bits, two bytes, or one word. A short-sized variable can hold any value between –32,768 and 32,767 or 65,536 different values (including 0).

In the following exercise, you create an application that interacts with a variable of type short.

Files needed: ShowShort.java


LINGO

You may hear two bytes of information referred to as a word, which in this context means a unit of computer memory that corresponds to 16-bits of information. The use of specific terms to describe memory units makes it possible to talk with other developers to exchange ideas without ambiguity. Other interesting memory units are the nibble (4-bits), DWORD, or double-word (32-bits), and QWORD, or quadword (64-bits).


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 ShowShort
{
public static void main(String[] args)
{
// Create a variable to hold a result.
short MyVar = 1;

// Display the initial value.
System.out.println("The MyVar starting value equals: "
+ MyVar);

// Add 5 to MyVar.
MyVar += 5;

// Display the result.
System.out.println("Add 5 to MyVar equals: " + MyVar);

// Subtract 4 from MyVar.
MyVar -= 4;

// Display the result.
System.out.println("Subtract 4 from MyVar equals: "
+ MyVar);

// Increment MyVar.
MyVar++;

// Display the result.
System.out.println("Increment MyVar equals: " + MyVar);

// Decrement MyVar.
MyVar--;

// Display the result.
System.out.println("Decrement MyVar equals: " + MyVar);

// Multiply MyVar by 6.
MyVar *= 6;

// Display the result.
System.out.println("Multiply MyVar by 6 equals: " + MyVar);

// Divide MyVar by 3.
MyVar /= 3;

// Display the result.
System.out.println("Divide MyVar by 3 equals: " + MyVar);
}
}

This application performs a number of math operations. Of course, you know from school that the four basic math operations are add, subtract, multiply, and divide. However, this example also shows two special math operations: increment and decrement. You use these special math operations to add one or subtract one from the variable. Later chapters will demonstrate just how useful this feature is.


LINGO

Incrementing a variable means adding a value of 1 to it. Decrementing a variable means subtracting a value of 1 from it. You use incrementing and decrementing to perform special tasks within an application. For example, every time an event happens, you could increment a variable to keep track of the number of times the event has happened while the application is running.


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

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

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

5. Type java ShowShort and press Enter.

You see the results of the various math operations as shown in Figure 2-5.

9781118098783-fg0205.tif

Figure 2-5:

practice_fmt.eps Change the code in the example shown in the “byte” section to use a short instead of a byte. What you need to do is change the line of code that reads, byte MyByte = GetByte.nextByte(); to short MyByte = GetByte.nextShort();. Go through the exercise again and note the changes that occur.

int

The int type consumes 32 bits — 4 bytes, two words, or one DWORD. An int-sized variable can hold any value between –2,147,483,648 and 2,147,483,647 or 4,294,967,296 different values (including 0).

In the following exercise you create an application that interacts with a variable of type int. The result of this interaction is a guessing game where you try to guess the number that the computer has chosen.

Files needed: ShowInt.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.util.Random;
import java.util.Calendar;

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

// Obtain an int value.
System.out.print("Type a number between 1 and 10: ");
int YourGuess = GetInt.nextInt();

// Get the current time.
Calendar MyCal = Calendar.getInstance();

// Create a random number generator.
Random MyRandom = new Random();

// Set the seed value for the random number using
// the current number of milliseconds in the time.
MyRandom.setSeed(MyCal.getTimeInMillis());

// Obtain a random number between 1 and 10.
int MyGuess = MyRandom.nextInt(10) + 1;

// Display the value on screen.
System.out.print("Your guess was: " + YourGuess);
System.out.println(" My guess was: " + MyGuess);
}
}

This application performs a few new tasks. First, it gets an int, which is the same process as getting a byte or a short (see the examples in the “byte” and “short” sections of the chapter), but it relies on the nextInt() method. The first new task is obtaining an instance of a Calendarobject, which you could use to discover the current date or time. In this case, the application uses the time as a means of ensuring that a random number is actually random. The next new task is creating a random number between 1 and 10, which consists of three subtasks:

· Create the Random object, MyRandom.

· Set the seed value, which is used to determine the starting point for random numbers generated by MyRandom. Imagine a seed value as you would a seed that you physically plant in the ground — the seed you choose determines the plant that grows (the output from the randomization process). Otherwise, you’ll always get the same output — it won’t be random at all.

· Get the random number between 1 and 10. The MyRandom.nextInt() method actually returns a value between 0 and 9, so you must add 1 to this output to obtain a number between 1 and 10. The output shows your guess and the application’s guess side-by-side.

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

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

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

5. Type java ShowInt and press Enter.

6. Type any number between 1 and 10 and press Enter.

You see your guess and the application’s guess as shown in Figure 2-6.

9781118098783-fg0206.tif

Figure 2-6:

practice_fmt.eps Try commenting out the MyRandom.setSeed(MyCal.getTimeIn
Millis()) line of code in the application by typing // in front of the line of code. Perform steps 3 and 4 again to see what happens. Notice that the output is the same every time you run the application because the random number output is no longer random. Setting a seed value is an essential part of creating a random number.

long

The long type consumes 64 bits — 8 bytes, four words, two DWORDs, or one QWORD. It’s the largest non-decimal variable type that Java supports. A long-sized variable can hold any value between –9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 or 18,446,744,073,709,551,616 different values (including 0).

In the following exercise you create an application that interacts with a variable of type long.

Files needed: ShowLong.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;

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

// Obtain the dividend (the first number in the division).
System.out.print("Type a number for the dividend: ");
long Dividend = GetLong.nextLong();

// Obtain the divisor (the part used to divide the
// dividend).
System.out.print("Type a number for the divisor: ");
   long Divisor = GetLong.nextLong();

// Perform the division.
System.out.print(Dividend + " divided by ");
System.out.print(Divisor + " equals ");
System.out.print(Dividend / Divisor);
System.out.print(" with a remainder of ");
System.out.println(Dividend % Divisor);
}
}

This application performs division of two numbers of any size that a long can support (a considerable range). The output can’t contain a decimal portion, however, so the result also includes the remainder, which you obtain using the modulus (%) operator. In short, division with integer numbers includes a quotient and a remainder.

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

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

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

5. Type java ShowLong and press Enter.

The application asks you to enter the dividend, which is the number that gets divided.

6. Type 22 and press Enter.

The application asks you to enter the divisor, which is the number used to divide the dividend.

7. Type 5 and press Enter.

You see the results of the division (the quotient) as shown in Figure 2-7.

9781118098783-fg0207.tif

Figure 2-7:

float

Up to this point, all of the variable types have supported a specific number of bytes that directly correlate to a numeric range. None of these types have supported decimals — they have contained only the integer portion of the number. A float includes both an integer and a decimal portion. The float is 32-bits long. Precisely how the float supports numbers with a decimal portion is unimportant for the purposes of understanding Java, only the fact that it does so is important. A float can support numbers between 1.40129846432481707–45 to 3.40282346638528860+38 (positive or negative).

In the following exercise you create an application that interacts with a variable of type float.


LINGO

Floating point numbers are those that contain both an integer and a decimal portion, such as 1.25. In this case, 1 is the integer portion and 25 is the decimal portion. A computer uses an entirely different set of circuits to work with floating point numbers, and the procedure for working with them is entirely different as well. Some people call floating point numbers real numbers. Strictly speaking, these people are incorrect because floating point numbers on a computer only approximate real numbers (the numbers as they actually are in the real world).


Files needed: ShowFloat.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;

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

// Obtain the dividend (the first number in the 

// division).
System.out.print("Type a number for the dividend: ");
float Dividend = GetFloat.nextFloat();

// Obtain the divisor (the part used to divide the
// dividend).
System.out.print("Type a number for the divisor: ");
float Divisor = GetFloat.nextFloat();

// Perform the division.
System.out.print(Dividend + " divided by ");
System.out.print(Divisor + " equals ");
System.out.println(Dividend / Divisor);
}
}

This application closely mirrors the ShowLong application found in the preceding “long” section of the chapter. The major difference here is that this version doesn’t calculate a remainder — the use of a floating point number makes it possible to output a result that shows both an integer and a decimal portion.


GO ONLINE

For the purposes of this book, you really don’t need to know the difference between floating point numbers and real numbers. However, there is a definite difference between the two. If you want to know more, you can find out about the details at http://ugweb.cs.ualberta.ca/~c229/F07/resources/IEEE-reals.html.


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

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

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

5. Type java ShowFloat and press Enter.

The application asks you to enter the dividend, which is the number that gets divided.

6. Type 22 and press Enter.

The application asks you to enter the divisor, which is the number used to divide the dividend.

7. Type 5 and press Enter.

You see the results of the division (quotient) as shown in Figure 2-8. Notice that the input numbers are converted to floating point format. Even though you typed 22, the application outputs 22.0. The same thing happens when you type 5; the application converts the output to 5.0.

9781118098783-fg0208.tif

Figure 2-8:

practice_fmt.eps Repeat Steps 5 through 7. However, type 125.5 instead of 22 and 9.316 instead of 5. You should see 13.471447 as the output value. More importantly, you couldn’t use 125.5 and 9.316 as inputs to the ShowLong application. Try these inputs with the ShowLong application to see what happens (the output should show an InputMismatchException error after you try to enter the dividend).

double

The double works precisely the same as the float, but it uses 64-bits instead of 32-bits to hold information. The larger memory space means that a double can hold larger numbers — a range from 4.94065645841246544–324 to 1.79769313486231570+308 (positive or negative). However, it also means that the double can add precision to inexact floating point values. For example, if you want to calculate the circumference of a circle, a double that contains the value of pi will offer more precision than an equivalent float.

In the following exercise you create an application that interacts with a variable of type double. This application will help you find the squares and square root of any number.

Files needed: ShowDouble.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.Math;

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

// Obtain a number to manipulate.
System.out.print("Type any number: ");
double Calc = GetDouble.nextDouble();

// Output the square and the square root
// of this number.
System.out.print("The square of " + Calc + " is: ");
System.out.println(Calc * Calc);
System.out.print("The square root of " + Calc + " is: ");
System.out.println(Math.sqrt(Calc));
}
}

This application relies on a new class, java.lang.Math, to perform some variable manipulation. Although you can find the square of any number simply by multiplying the number by itself, you need a special function to obtain the square root. The Math.sqrt() method performs this task.

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

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

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

5. Type java ShowDouble and press Enter.

The application asks you to type a number.

6. Type 121 and press Enter.

You see the square and square root of the input as shown in Figure 2-9.

9781118098783-fg0209.tif

Figure 2-9:

boolean

A boolean value is either true or false. It doesn’t contain any other information. However, boolean variables are really important in Java because they help the application make decisions. Imagine what would happen if an application couldn’t make up its mind!

In the following exercise you create an application that interacts with a variable of type boolean.

Files needed: ShowBoolean.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;

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

// Obtain input from the user.
System.out.print("Do you like oranges? ");
boolean TheTruth = GetBoolean.nextBoolean();

// Show the result.
System.out.print("It's " + TheTruth);
System.out.println(" that you like oranges.");
}
}

boolean values are always true or false. This application accepts a boolean value in response to a simple question and displays it on screen.

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

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

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

5. Type java ShowBoolean and press Enter.

The application asks whether you like oranges.

6. Type true and press Enter.

You see the result of answering the question as shown in Figure 2-10.

9781118098783-fg0210.tif

Figure 2-10:

7. Repeat Steps 5 and 6, but this time type yes.

The application displays an InputMismatchException error message. Boolean values are really a number — either 0 (false) or 1 (true) as far as the computer is concerned. Of course, it’s interesting to see how the application views the numeric status of a Boolean value.

8. Repeat Steps 5 and 6, but this time answer 1.

The application displays an InputMismatchException error message.

remember.eps A type enforces not only a certain type of output, such as true or false for a boolean value, but also a certain type of input. You’ve seen that this holds true for numbers and now boolean values as well. It’s essential to choose the correct variable type when you write an application.

char

Of all of the data types, the char is the one that your computer understands least. As far as the computer is concerned, a char is simply a 16-bit number that can contain any of 65,536 values. Java turns this number into a specific character. For example, the number 65 equates to the letter A. It’s important to realize, though, that Java assigns the letter A to 65 — the computer sees just the number.

In the following exercise you create an application that interacts with a variable of type char.

Files needed: ShowChar.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;

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

// Obtain input from the user.
System.out.print("Type any single letter or number: ");
char AChar = GetChar.findInLine(".").charAt(0);

// Display the input.
System.out.println ("You typed: " + AChar);
}
}

The Scanner class doesn’t provide any means of obtaining a char directly, so this example shows a new way to work with Scanner input. In this case, the example retrieves any string because the period (.) represents any character. However, you don’t need a string (a series ofcharacters as in a sentence) — you need a char. The charAt(0) part of the code selects just the first character from any string that the user types and returns it as a char.

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

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

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

5. Type java ShowChar and press Enter.

The application asks you to type any character at all.

6. Type b and press Enter.

You see the letter you typed as output. The fact that the pattern relies on a period may have you worried that you can’t type a period as input.

7. Repeat Steps 5 and 6, but type . (a period) instead of the b.

You see a period displayed on screen. So, you can type letters and special characters. It may be interesting to see whether numbers present a problem.

8. Repeat Steps 5 and 6, but type 123 instead of the b.

The application doesn’t display any sort of error, but it also displays only the 1. The input isn’t treated as a number; it’s treated as a series of characters. This input consists of three characters: 1, 2, and 3. You can probably guess what would happen if you typed a boolean value.

9. Repeat Steps 5 and 6, but type true instead of the b.

This time you see just the t. Every input you provide is turned into a single character, as shown in Figure 2-11.

9781118098783-fg0211.tif

Figure 2-11:

practice_fmt.eps Change the code in the example shown in the earlier “byte” section to use a char instead of a byte. What you need to do is change the line of code that reads, byte MyByte = GetByte.nextByte(); to char MyByte = GetByte.findInLine(".").charAt(0);. Go through the exercise again and note the changes that occur. For example, you’ll notice that you don’t see any errors from the application. However, instead of the intended output, you see 3, then –, then 1, and finally C, instead of 3, –15, 128, and C as intended.

Creating and Using Constants

Every variable you’ve worked with so far is a container that can hold anything. In addition, you can change the content as needed. Constants make it possible to create variables that can’t change value during application execution.

Constants have a lot of uses, which you’ll see as the book progresses. However, it’s a good idea to get started with constants early because they can make your application more stable. For example, because you can’t change a constant, using one can make your application more resistant to outside interference.

In this exercise, you create a constant and interact with it in various ways to see how it works. In this case, you also see the effect of errors in your application code.

Files needed: CreateConst.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;

public class CreateConst
{
public static void main(String[] args)
{
// Create a constant.
final int MyConst = 345;

// Display the constant on screen.
System.out.println("The current value of MyConst is: "
+ MyConst);

// Create the scanner.
Scanner GetConst = new Scanner(System.in);

// Try to change the value.
System.out.print("Enter a new value for MyConst: ");
MyConst = GetConst.nextInt();
}
}

This application begins by creating a constant. Whenever you see a final variable, you know that it’s a constant. MyConst is assigned the value of 345 and that value can’t change as long as the application is running. The application displays the value of MyConst and then invites you to try changing the value of MyConst to a new value.

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

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

You see an error message like the one shown in Figure 2-12 instead of the compiled .class file you expected. This has never happened with any of the other examples. You can expect to see an error message like this for any application that has a coding error in it of the sort we’ve created for this example.

remember.eps The compiler will catch all of your syntax errors for you. It’s illegal to assign a value to a constant in any location but the definition, so the compiler tells you about the error. The compiler will also normally tell you precisely which line has an error in it so that you can fix it easily.

9781118098783-fg0212.tif

Figure 2-12:

5. Type // in front of the line of code that reads MyConst = GetConst.nextInt();.

This change will fix the error. Removing the // will change the line from a comment into code that the compiler will compile.

6. Type javac CreateConst.java and press Enter.

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

7. Type java CreateConst and press Enter.

You see the current value of MyConst, as shown in Figure 2-13. Ignore the request to type a new value because the line for accepting a new value is commented out.

9781118098783-fg0213.tif

Figure 2-13:

remember.eps Constants can have any type. The only difference is that you can’t change a constant. So, if you want to create a final char, feel free to do so.

summingup_fmt.eps Summing Up

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

· Computers see only 1s and 0s on memory and don’t understand the concept of information.

· Data types determine how an application interprets the 1s and 0s stored in computer memory.

· Primitive data types exist as pure numbers. They have the advantage of performing tasks faster using less memory.

· The primitive data types are: byte, short, int, long, float, double, boolean, and char.

· Constants make it possible to create secure, high performance variables that contain the same value throughout application execution.

Try-it-yourself lab

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

1. Open the ShowByte application.

2. Change this application to use the float data type, rather than the byte data type.

You may want to rename the resulting application and its associated class to show the change in data type. For example, you could rename the application to FloatVersionOfShowByte, if you wanted, but something shorter would probably work better.

3. Perform Steps 3 through 7 in the “byte” section of the chapter.

4. Note how the application behavior changes.

One change that you’ll want to note is how the input affects the application. In addition, how does the output from the application appear? Different data types do indeed work differently, so this exercise points out the need to use the right type.

Know this tech talk

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

· decrement: Subtracting a value of 1 from a variable.

· exception: A condition that occurs when the application experiences something unexpected, such as incorrect user input. An exception occurs during exceptional conditions — conditions that no one expected to happen. Every exception tells you the exception type, the incorrect condition (when known), and the place where the exception happened in the source file.

· 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.

· increment: Adding a value of 1 to a variable.

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

· 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.