2.1. Primitive variables

[2.1] Declare and initialize variables (including casting of primitive data types)

[2.2] Differentiate between object reference variables and primitive variables

In this section, you’ll learn all the primitive data types in Java, their literal values, and the process of creating and initializing primitive variables. A variable defined as one of the primitive data types is a primitive variable.

Primitive data types, as the name suggests, are the simplest data types in a programming language. In the Java language, they’re predefined. The names of the primitive types are quite descriptive of the values that they can store. Java defines the following eight primitive data types:

  • char
  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean

Examine figure 2.1 and try to match the given value with the corresponding type.

Figure 2.1. Matching a value with its corresponding type

This should be a simple exercise. Table 2.1 provides the answers.

Table 2.1. Matching a value with its corresponding data type

Character values

Integer values

Decimal values

Boolean

a 100 7.3 true
  4573    

In the preceding exercise, I categorized the data that you need to store as follows: character, integer, decimal, and Boolean values. This categorization will make your life simpler when confronted with selecting the most appropriate primitive data type to store a value. For example, to store an integer value, you need a primitive data type that’s capable of storing integer values; to store decimal numbers, you need a primitive data type that can store decimal numbers. Simple, isn’t it?

Let’s map the types of data that the primitive data types can store, because it’s always easy to group and remember information.

Note

The category Boolean is not the same as the primitive data type boolean or wrapper class Boolean. Java primitive data types and class names are displayed using code font.

The primitive data types can be categorized as follows: Boolean, character, and numeric (further categorized as integral and floating-point) types. Take a look at this categorization in figure 2.2.

Figure 2.2. Categorization of primitive data types

As shown in figure 2.2, the char primitive data type is an unsigned numeric data type. It can only store positive integers. The rest of the numeric data types (byte, short, int, long, float, and double) are signed numeric data types (they can store both negative and positive values). The categorization in figure 2.2 will help you further associate each data type with the value that it can store. Let’s start with the Boolean category.

2.1.1. Category: Boolean

The Boolean category has only one data type: boolean. A boolean variable can store one of two values: true or false. It’s used in scenarios where only two states can exist. See table 2.2 for a list of questions and their probable answers.

Table 2.2. Suitable data that can be stored using a boolean data type

Question

Probable answers

Did you purchase the exam voucher? Yes/No
Did you log in to your email account? Yes/No
Did you tweet about your passion today? Yes/No
Tax collected in financial year 2001–2002 Good question! But it can’t be answered as yes/no.
Exam Tip

In this exam, the questions test your ability to select the best suitable data type for a condition that can only have two states: yes/no or true/false. The correct answer here is the boolean type.

Here’s some code that defines boolean primitive variables:

boolean voucherPurchased = true;
boolean examPrepStarted = false;

In some languages, such as JavaScript, you don’t need to define the type of a variable before you use it. In JavaScript, the compiler defines the type of the variable according to the value that you assign to it. Java, in contrast, is a strongly typed language. You must declare a variable and define its type before you can assign a value to it. Figure 2.3 illustrates defining a boolean variable and assigning a value to it.

Figure 2.3. Defining and assigning a primitive variable

Another point to note here is the value that’s assigned to a boolean variable. I used the literals true and false to initialize the boolean variables. A literal is a fixed value that doesn’t need further calculations in order for it to be assigned to any variable. true and false are the only two boolean literals.

Note

There are only two boolean literal values: true and false.

2.1.2. Category: signed numeric

The numeric category defines two subcategories: integers and floating point (also called decimals). Let’s start with the integers.

Integers: byte, int, short, long

When you can count a value in whole numbers, the result is an integer. It includes both negative and positive numbers. Table 2.3 lists probable scenarios in which the data can be stored as integers.

Table 2.3. Data that can be categorized as numeric (nondecimal numbers) data type

Situation

Can be stored as integers?

Number of friends on Facebook Yes
Number of tweets posted today Yes
Number of photographs uploaded for printing Yes
Your body temperature Not always

You can use the byte, short, int, and long data types to store integer values. Wait a minute: why do you need so many types to store integers?

Each one of these can store a different range of values. The benefits of the smaller ones are obvious: they need less space in memory and are faster to work with. Table 2.4 lists all these data types, along with their sizes and the ranges of the values that they can store.

Table 2.4. Ranges of values stored by the signed numeric Java primitive data types

Data type

Size

Range of values

byte 8 bits –128 to 127, inclusive
short 16 bits –32,768 to 32,767, inclusive
int 32 bits –2,147,483,648 to 2,147,483,647, inclusive
long 64 bits –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive

The OCA Java SE 8 Programmer I exam may ask you questions about the range of integers that can be assigned to a byte data type, but it won’t include questions on the ranges of integer values that can be stored by short, int, or long data types. Don’t worry—you don’t have to memorize the ranges for all these data types!

Here’s some code that assigns literal values to primitive numeric variables within their acceptable ranges:

byte num = 100;
short sum = 1240;
int total = 48764;
long population = 214748368;

The default type of a nondecimal number is int. To designate an integer literal value as a long value, add the suffix L or l (L in lowercase), as follows:

long fishInSea = 764398609800L;

Integer literal values come in four flavors: binary, decimal, octal, and hexadecimal:

  • Binary number system— A base-2 system, which uses only 2 digits, 0 and 1.
  • Octal number system— A base-8 system, which uses digits 0 through 7 (a total of 8 digits). Here the decimal number 8 is represented as octal 10, decimal 9 as 11, and so on.
  • Decimal number system— The base-10 number system that you use every day. It’s based on 10 digits, from 0 through 9 (a total of 10 digits).
  • Hexadecimal number system— A base-16 system, which uses digits 0 through 9 and the letters A through F (a total of 16 digits and letters). Here the number 10 is represented as A or a, 11 as B or b, 12 as C or c, 13 as D or d, 14 as E or e, and 15 as F or f.

Let’s take quick look at how you can convert integers in the decimal number system to the other number systems. Figures 2.4, 2.5, and 2.6 show how to convert the decimal number 267 to the octal, hexadecimal, and binary number systems.

Figure 2.4. Converting an integer from decimal to octal

Figure 2.5. Converting an integer from decimal to hexadecimal

Figure 2.6. Converting an integer from decimal to binary

Exam Tip

In the exam, you won’t be asked to convert a number from the decimal number system to the octal and hexadecimal number systems and vice versa. But you can expect questions that ask you to select valid literals for integers. The figures 2.42.6 will help you understand these number systems better and retain this information longer, which will in turn enable you to answer questions correctly during the exam.

You can assign integer literals in base decimal, binary, octal, and hexadecimal. For octal literals, use the prefix 0; for binary, use the prefix 0B or 0b; and for hexadecimal, use the prefix 0X or 0x. Here’s an example of each of these:

Java 7 introduced the use of underscores as part of the literal values. Grouping individual digits or letters of literal values makes them more readable. The underscores have no effect on the values. The following is valid code:

Rules to remember

Here’s a quick list of rules for usage of underscores in the numeric literal values:

  • You can place an underscore right after the prefix 0, which is used to define an octal literal value.
  • You can’t start or end a literal value with an underscore.
  • You can’t place an underscore right after the prefixes 0b, 0B, 0x, and 0X, which are used to define binary and hexadecimal literal values.
  • You can’t place an underscore prior to an L suffix (the L suffix is used to mark a literal value as long).
  • You can’t use an underscore in positions where a string of digits is expected (see the following example).

Because you’re likely to be questioned on valid and invalid uses of underscores in literal values on the exam, let’s look at some invalid examples:

The following line of code will compile successfully but will fail at runtime:

Because a String value can accept underscores, the compiler will compile the previous code. But the runtime will throw an exception stating that an invalid format of value was passed to the method parseInt.

Here’s the first Twist in the Tale exercise of this chapter for you to attempt. It uses multiple combinations of underscores in numeric literal values. See if you can get all of them right (answers in the appendix).

Twist in the Tale 2.1

Let’s use the primitive variables baseDecimal, octVal, hexVal, and binVal defined earlier in this section and introduce additional code for printing the values of all these variables. Determine the output of the following code:

class TwistInTaleNumberSystems {
public static void main (String args[]) {
        int baseDecimal = 267;
        int octVal = 0413;
        int hexVal = 0x10B;
        int binVal = 0b100001011;
        System.out.println (baseDecimal + octVal);
        System.out.println (hexVal + binVal);
    }
}

Here’s another quick exercise—let’s define and initialize some long primitive variables that use underscores in the literal values assigned to them. Determine which of these does this job correctly:

long var1 = 0_100_267_760;
long var2 = 0_x_4_13;
long var3 = 0b_x10_BA_75;
long var4 = 0b_10000_10_11;
long var5 = 0xa10_AG_75;
long var6 = 0x1_0000_10;
long var7 = 100__12_12;
Floating-point numbers: float and double

You need floating-point numbers where you expect decimal numbers. For example, can you define the probability of an event occurring as an integer? Table 2.5 lists probable scenarios in which the corresponding data is stored as a floating-point number.

Table 2.5. Data that’s stored as floating-point numbers

Situation

Is the answer a floating-point number?

Orbital mechanics of a spacecraft Yes (very precise values are required)
Probability of your friend request being accepted Yes; probability is between 0.0 (none) and 1.0 (sure)
Speed of Earth revolving around the sun Yes
Magnitude of an earthquake on the Richter scale Yes

In Java, you can use the float and double primitive data types to store decimal numbers. float requires less space than double, but it can store a smaller range of values than double. float is less precise than double. float can’t represent accurately some numbers even if they’re in range. The same limitation applies to double—even if it’s a data type that offer more precision. Table 2.6 lists the sizes and ranges of values for float and double.

Table 2.6. Range of values for decimal numbers

Data type

Size

Range of values

float 32 bits +/–1.4E–45 to +/–3.4028235E+38, +/–infinity, +/–0, NaN
double 64 bits +/–4.9E–324 to +/–1.7976931348623157E+308, +/–infinity, +/–0, NaN

Here’s some code in action:

float average = 20.129F;
float orbit = 1765.65f;
double inclination = 120.1762;

Did you notice the use of the suffixes F and f while initializing the variables average and orbit in the preceding code? The default type of a decimal literal is double, but by suffixing a decimal literal value with F or f, you tell the compiler that the literal value should be treated like a float and not a double.

You can also assign a literal decimal value in scientific notation as follows:

You can also add the suffix D or d to a decimal number value to specify that it’s a double value. Because the default type of a decimal number is double, the use of the suffix D or d is redundant. Examine the following line of code:

Starting with Java version 7, you can also use underscores with the floating-point literal values. The rules are generally the same as previously mentioned for numeric literal values; the following rules are specific to floating-point literals:

  • You can’t place an underscore prior to a D, d, F, or f suffix (these suffixes are used to mark a floating-point literal as double or float).
  • You can’t place an underscore adjacent to a decimal point.

Let’s look at some examples that demonstrate the invalid use of underscores in floating-point literal values:

2.1.3. Category: character (unsigned integer)

The character category defines only one data type: char. A char is an unsigned integer. It can store a single 16-bit Unicode character; that is, it can store characters from virtually all the existing scripts and languages, including Japanese, Korean, Chinese, Devanagari, French, German, and Spanish. Because your keyboard may not have keys to represent all these characters, you can use a value from u0000 (or 0) to a maximum value of uffff (or 65,535) inclusive. The following code shows the assignment of a value to a char variable:

A very common mistake is using double quotes to assign a value to a char. The correct option is single quotes. Figure 2.7 shows a conversation between two (hypothetical) programmers, Paul and Harry.

Figure 2.7. Never use double quotes to assign a letter as a char value.

What happens if you try to assign a char using double quotes? The code will fail to compile, with this message:

Type mismatch: cannot convert from String to char
Exam Tip

Never use double quotes to assign a letter to a char variable. Double quotes are used to assign a value to a variable of type String.

Internally, Java stores char data as an unsigned integer value (positive integer). It’s therefore acceptable to assign a positive integer value to a char, as follows:

Note

The exam will test you on multiple (obscure) techniques like assigning an unsigned integer value to a char data type. But I don’t recommend using these on real projects. Please write code that’s readable and easy to maintain.

The integer value 122 is equivalent to the letter z, but the integer value 122 is not equal to the Unicode value u0122. The former is a number in base 10 (uses digits 0–9) and the latter is a number in base 16 (uses digits 0–9 and letters a–f—lower- or uppercase). u is used to mark the value as a Unicode value. You must use quotes to assign Unicode values to char variables. Here’s an example:

char c2 = 'u0122';
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);

Figure 2.8 shows the output of the preceding code on a system that supports Unicode characters.

Figure 2.8. The output of assigning a character using the integer value 122 versus the Unicode value u0122

As mentioned earlier, char values are unsigned integer values, so if you try to assign a negative number to one, the code won’t compile. Here’s an example:

But you can forcefully assign a negative number to a char type by casting it to char, as follows:

In the previous code, note how the literal value –122 is prefixed by (char). This practice is called casting. Casting is the forceful conversion of one data type to another data type.

You can cast only compatible data types. For example, you can cast a char to an int and vice versa. But you can’t cast an int to a boolean value or vice versa. When you cast a bigger value to a data type that has a smaller range, you tell the compiler that you know what you’re doing, so the compiler proceeds by chopping off any extra bits that may not fit into the smaller variable. Use casting with caution—it may not always give you the correct converted values.

Figure 2.9 shows the output of the preceding code that cast a value to c3 (the value looks weird!).

Figure 2.9. The output of assigning a negative value to a character variable

The char data type in Java doesn’t allocate space to store the sign of an integer. If you try to forcefully assign a negative integer to char, the sign bit is stored as the part of the integer value, which results in the storage of unexpected values.

Exam Tip

The exam will test your understanding of the possible values that can be assigned to a variable of type char, including whether an assignment will result in a compilation error. Don’t worry—it won’t test you on the value that’s actually displayed after assigning arbitrary integer values to a char!

2.1.4. Confusion with the names of the primitive data types

If you’ve previously worked in another programming language, there’s a good chance that you might get confused with the names of the primitive data types in Java and other languages. For example, C defines a primitive short int data type. But short and int are two separate primitive data types in Java. The OCA Java SE 8 Programmer I exam will test you on your ability to recognize the names of the primitive data types, and the answers to these questions may not be immediately obvious. An example follows:

Question: What is the output of the following code?

public class MyChar {
    public static void main(String[] args) {
        int myInt = 7;
        bool result = true;
        if (result == true)
            do
                System.out.println(myInt);
            while (myInt > 10);
    }
}

  1. It prints 7 once.
  2. It prints nothing.
  3. Compilation error.
  4. Runtime error.

The correct answer is (c). This question tries to trick you with complex code that doesn’t use any if constructs or do-while loops! As you can see, it uses an incorrect data type name, bool, to declare and initialize the variable result. Therefore, the code will fail to compile.

Exam Tip

Watch out for questions that use incorrect names for the primitive data types. For example, there isn’t any bool primitive data type in Java. The correct data type is boolean. If you’ve worked with other programming languages, you might get confused trying to remember the exact names of all the primitive data types used in Java. Remember that just two of the primitive data types—int and char—are shortened; the rest of the primitive data types (byte, short, long, float, and double) are not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.85.181