Hour 13. Java’s Details

In this hour, you will gain a deeper understanding of the Java programming language. Java has its roots in C and C++. Once you become familiar with Java, you will then be familiar with much of C and C++. Java has become the most widely used programming language in the world, overtaking C++.

Java is actually simpler to learn than C++ because many of the skills of Java programming come from knowing which internal prebuilt Java procedures to run. As you saw in the previous hour’s overview, when you want to print a message in color, you don’t have to do much more than find the name of the prebuilt procedure that first sets the color, find the name of the procedure that prints in an output window, and then use those procedures in your program.

The highlights of this hour include

Image Seeing how Java treats literals

Image Declaring variables

Image Understanding operators

Image Controlling programs with if statements

Image Validating user input

Image Looping with the for and while statements

Defining Java Data

JavaScript supports numeric and string data types. Most languages, including Java, break data down further into several different types. Data can be either literals, constant values that do not change such as your first name or date of birth, and variables, which, as you know already from JavaScript, are named storage locations for data that can change.

Java Literals

A literal is just a number, character, or string of characters. Several kinds of Java literals exist. Java supports integer (whole numbers without decimal places) and floating-point (numbers with decimal place) literals. Here are some valid integer literals:

23   -53819   0

Here are sample floating-point literals:

90544.5432211     -.0000324     -2.354     67.1

Integer literals can use the _ underscore character to make them more readable:

7_500_000     8_650_300_000

The _ just makes the value easier for humans to understand. You can see at a glance that the first number is 7.5 million without needing to count the zeroes. The Java compiler ignores the underscores.

Java also supports two Boolean literals. These Boolean literals are true and false. You’ll use Boolean literals to test or set Boolean values to true or false to determine if certain events are to occur.

A character literal is a single character. You must enclose character literals inside single quotation marks. The following are character literals:

'J'    '@'     '4'     'p'

A character literal doesn’t have to be alphabetic. You cannot compute with a number inside a character literal. Therefore, '4' is a character literal but 4 is an integer literal. If you need to represent several characters as a single literal, use a string literal as described at the end of this section. Programmers work with literals all the time, such as when printing a corporation’s name on a report.

Java supports special character literals called escape sequences. Due to the nature of some character literals, you cannot always represent a character inside single quotation marks. For example, a tab character can appear on a screen to move the cursor forward a few characters to the next tab stop. But to store a tab character in a variable, you cannot assign the tab key directly to a variable—you must use an escape sequence to represent the tab character. These escape characters do consume more than one position inside the single quotes, such as ' ', but they only take one character’s storage location as do all character literals. Table 13.1 lists some Java escape sequences.

Image

TABLE 13.1 Java’s escape sequence characters represent nontypable characters.


Note

Remember that Java came from C and C++. C and C++ support the same data types as Java (except for strings) as well as the same escape sequences. As you learn more about Java’s operators and control statements throughout the rest of this hour, virtually all you learn is applicable in C and C++ as well.


You can use an escape character to move the cursor down a line with the newline escape sequence, or you could use one to place a single quotation mark on a window. You could not represent a single quote by placing it inside two single quotes like this: '''.

Specify string literals by enclosing them in quotation marks. All the following items are string literals:

"This is a string."     "12345"     ""     "q"


Tip

You can place an escape sequence character inside a string. Therefore, the following string literal contains starting and ending quotation marks due to two escape sequences that represent the quote marks: ""Java"".


Java Variables

As in JavaScript, you’re in charge of naming Java variables. You must inform Java that you need to use a variable by declaring that variable before you use it. When you declare a variable, you tell Java the name and data type of that variable. Java then reserves storage for that variable throughout the variable’s lifetime. A variable’s life may be for the entire program (as is the case with global variables) or may exist only for a few lines of code (as is the case with local variables), depending on how and where you declare the variable. Once you declare a variable, Java protects that variable’s data type; that is, you cannot store a string in an integer variable.

Integer Variables

Table 13.2 lists the four kinds of integer variables Java supports. The integer variable you use depends on what you’re going to store in that variable. For example, if you’re going to store a child’s age in a variable, you could do so in a byte variable. If you are going to store intergalactic distances, you need to use a long integer.

Image

TABLE 13.2 Java variable sizes determine which integer variable you use.

A byte of memory represents a single character of storage. Therefore, you can store approximately 16 million characters, or byte integers, in 16 million bytes of free memory.

Generally, you’ll find variable declarations near the beginning of Java programs and procedures. To declare a variable, use Table 13.2’s first column to tell Java the kind of variable you require. The following statement declares an integer variable named numKeys:

int numKeys;   // defines a 4-byte integer variable

Remember to follow your variable declarations, as with all Java statements, with semicolons. The following statements define four variables, one for each type of Java integer:

byte a;
short b;
int c;
long d;

You can define several variables of the same data type on one line like this:

int x, y, z;   // defines 3 integer variables


Caution

Java declares variables but does not initialize variables for you. Therefore, don’t assume zero or blanks are in numeric and string variables. Be sure to initialize each variable with a value before you use that variable inside a calculation.


Use the assignment operator, =, to assign values to your variables. You can assign a variable an initial value at the same time you define a variable. The following statements declare four variables and initialize three of them:

byte f = 32;
int c, d = 7639;   // defines but does not initialize c
long highCount = 0;

Floating-Point Variables

Table 13.3 lists the two kinds of floating-point variables that Java supports. You’ll use the larger floating-point variable to represent extremely large or small values with a high degree of accuracy. Generally, only scientific and mathematically related programs need the double data type. For most floating-point calculations, float works just fine.

Image

TABLE 13.3 Java supports two floating-point variable data types.

The following statements declare and initialize floating-point variables that can hold decimal numbers:

float w = -234.4332F;
float x = 76545.39F;
double y = -0.29384848458, z = 9283.11223344;

The first two values are followed by an uppercase F, which indicates that they are float values instead of double. Java’s default for decimal numbers is double.

Boolean Variables

Use the boolean keyword to declare Boolean variables. A Boolean variable can hold only true or false. The following statements declare and initialize three Boolean variables:

boolean hasPrinted = false;
boolean gotAnswer = false, keyPressed = true;

These conditional values specify whether or not an event took place.

Character Variables

Declare character variables with the char keyword as the following statements do:

char firstInitial;
char lastInitial = 'Z';

You may assign any of the character literals you learned about earlier this hour, including escape sequences, to character variables. The following statements store the letter A in a variable and a tab character in another variable:

c1 = 'A';
tabChar = ' ';

String Variables

Java does not actually support string variables, and neither do C or C++, but Java includes a built-in class that defines string data as variables so you can declare string variables just as you can the other data types. Use the String keyword (notice the uppercase S; most programmers use an initial uppercase letter for names of classes) to declare string variables. You cannot directly change a string variable once you declare and initialize the variable but you can use built-in functions to change string variables.

The following statements declare three strings:

String s;                           // no initialization
String langName = "Java";       // an initialized string
String warning = "Don't press Enter yet!"; // initialized

Arrays

Java supports arrays, which are lists of zero or more variables of the same data type, as you learned in Hour 9, “Programming Algorithms.” All array subscripts begin at 0, so a 10-element array named ara utilizes these array elements: ara[0] through ara[9]. Of course, you don’t have to name arrays ara; you can assign any name you wish to an array.

To define an array, use the new command. The following statements define three arrays:

int countList[] = new int[100];   // declare an array of 100 elements
double temps[] = new double[30];  // declare 30 double elements
char initials[] = new char[1000]; // declare 1,000 characters

Although their declarations require more typing than non-array variables, once you’ve declared arrays, you can use the array elements just as you use other variables. For example, the following statements work with individual array elements:

countList[0] = 10;
countList[50] = 394;
temps[2] = 34334.9298;
initials[1] = 'a';
initials[2] = initials[1];

Operators

Java supports several mathematical and conditional operators. You don’t have to be a math expert to understand them but Java’s operators are somewhat more involved than JavaScript’s due to Java’s heavier reliance on operators (the same holds for C and C++).

The Primary Math Operators

Table 13.4 contains Java’s primary math operators.

Image

TABLE 13.4 Java supports fundamental math operators.

You can use parentheses to group calculations together. Java normally computes division and multiplication in a formula before addition and subtraction, but the following makes sure the addition is computed first so an average can result:

average = (sales1 + sales2 + sales3 + sales4) / 4;

The modulus operator returns the remainder when you divide one integer into another. The assignment operator evaluates from right to left so you can combine multiple assignments as in this statement:

a = b = c = d = e = 0;  // Stores 0 in all five variables

Increment and Decrement Operators

As you learned in Hour 9, your programs will often keep track of running totals or count down or up to a value such as a total score. To add one or subtract one from a variable, you can use Java’s increment (++) and decrement (--) operators as follows:

runningTotal++;  // adds 1 to variable
countdown--;     // subtracts 1 from variable

You may place increment and decrement operators inside expressions such as this:

answer = aVar++ * 4;

You can place increment and decrement operators on either side of a variable. If you place them on the left, prefix notation occurs and Java computes the increment or decrement before other operators. If you place them on the right, postfix notation occurs and Java computes the increment and decrement after other operators.

Assuming x contains 5 before the next statement, answer receives the value of 12:

answer = ++x * 2;  // evaluate prefix first

The next statement performs a different calculation, however, due to the postfix notation. Java does not update x until after x is evaluated in the rest of the expression:

answer = x++ * 2;  // evaluate postfix last

In this expression, answer will contain 10 because the multiplication occurs before x increments. As with the prefix version, x always ends up with 6 before the statement completes. The choice of prefix or postfix depends on how you formulate the expression. If, for example, you used the same variable more than once on the right side of the equal sign, you should use postfix notation if you increment the variable so the expression is accurate. In other words, the following assignment statement uses postfix increment because age is incremented after it’s used for the assignment:

ageFactor = age++ * .45 + age;  // uses postfix

This statement uses the value of age twice in the calculation and then, after assigning the answer to ageFactor, increments the value in age. If prefix had been used, age would first be incremented before being used in the expression.

Arithmetic Assignments

Often, you will update, or change, the value of a variable based on that variable’s existing value. For example, suppose you are keeping track of a 10-question polling result. Every time the user answers a polling questionnaire, you’ll add 10 to a running total. Any time you want to modify the value of a variable, while using that variable’s current value in the expression, put the variable on both sides of the assignment operator. The following statement adds 10 to the variable named totalAnswers:

totalAnswers = totalAnswers + 10;  // adds 10

You can divide a variable by two, as done with aVar here:

aVar = aVar / 2.0;

This updating of variables occurs so frequently that the Java language borrowed common C and C++ operators called arithmetic assignment operators. Table 13.5 explains these.

Image

TABLE 13.5 Java’s arithmetic operators shortcut the updating of variables.

Given Table 13.5’s operator listing, the following statements use the arithmetic assignments to produce the same results described before the table:

totalAnswers += 10;   // same as totalAnswers = totalAnswers + 10;
aVar /= 2.0;          // same as aVar = aVar / 2.0;

Comparison Operators

Table 13.6 describes Java’s conditional operators. These operators do not perform mathematical operations but return a Boolean true or false result that indicates how one data value relates to another. You should have little trouble understanding these operators, as they are similar to JavaScript’s comparison operators.

Image

TABLE 13.6 Java’s comparison operators compare how data values relate to one another.


Caution

Don’t confuse the equality operator, ==, with the assignment, =. Java, C, and C++ use = for assignment and == to test for equality.


The Conditional Operator

The conditional operator is the only Java operator that requires three values. The conditional operator actually combines if-then-else logic into a simple, clear operation. The conditional operator returns one of two values depending on the result of a comparison operator.

Here is the general format of the conditional operator:

(comparison) ? true result : false result;

Often, you’ll assign a conditional to a variable as in the following statement:

minVal = (a < b) ? a: b;  // stores the lesser of a or b

If the comparison of (a < b) results in true, a is assigned to minVal. Otherwise, if (a < b) is false, the conditional assigns b to minVal. Although you’ll learn about Java’s if statement later this hour, Java’s if statement is close enough to JavaScript’s if statement that you can understand much of it now. As a comparison, and to help strengthen your understanding of the conditional operator, here is the identical logic using if-else statements:

if (a < b)
    minVal = a;
else
    minVal = b;

Use a conditional when you must make a fairly simple calculation based on the result of a comparison, such as (a < b) here. In most instances, a multi-statement if-else is easier to maintain than a conditional statement that tries to do too much.

Programming Control

Now that you know how to define Java data and work with its operators, you need to know how to manipulate that data through program control. Java programmers group statements together in blocks of code. A block of code is one or more statements enclosed within a pair of braces such as this:

{
    count++;
    System.out.println("The count is now higher");
}

Blocks can contain other blocks so you can nest one block inside another. The indention of the block’s body helps to show where blocks begin and end in long programs.


Learn the Format

As you learn programming languages, you’ll see how statements are formatted or put together. A general notation is often used to show you how to code a programming language statement.

Italicized words are placeholders that you fill in with your own values. The non-italicized words, such as if, are required. If any part of the format appears inside square brackets, with the exception of array brackets, that part of the statement is optional.

The following format shows that if is required but the else portion is optional. You fill in the italicized placeholder code with other programming statements:

if (condition) {
    block of one or more Java statements;
} else {
    block of one or more Java statements;
}


The if and if-else Statements

Here is the general format of the if statement:

if (condition) {
    block of one or more Java statements;
}


Caution

Never put a semicolon at the end of the condition’s parenthesis! Semicolons go only at the end of the executable statements. The condition does not terminate the if statement but only introduces the if. If you placed a semicolon after the condition, then a null statement would execute, meaning nothing would happen no matter how the condition tested and the block would always execute.


Consider the following if statement:

if (age >= 21) {
    g.drawString("You have authorization for the payment", 25, 50);
    makePmt(pmt);
}
// rest of program goes here

The two statements in the body of the if execute only if age contains a value of 21 or more. If age is less than 21, the block of code does not execute. Whether or not the block executes does not keep the subsequent statements in the program from continuing.

A common use of if is input verification. When you ask the user for a value, you should check the value to make sure the user entered a reasonable answer. For example, the following code asks the user for his or her age. If the user enters zero or a negative value, the program’s if statement displays an error message and prompts the user again:

getAge(age);  // calls a procedure to get the user's age
if (age <= 0) {
    // the following lines output to the user's screen
    System.out.println("You entered a bad age value.");
    System.out.println("Try again please.");
    getAge(age);
}
// code goes here to process the age

The if-else adds an else block to the if statement. Here is the format of the if-else statement:

if (condition) {
  block of one or more Java statements;
} else {
  block of one or more Java statements;
}

If the condition evaluates to true, the first block of Java statements executes. If, however, the condition evaluates to false, the second block of Java statements executes.

The section of Java code in Listing 13.1 computes a payroll amount based on the following general rules:

Image If the employee works 40 or fewer hours, the employee gets paid an hourly rate times the number of hours worked.

Image If the employee works from 40 to 50 hours, the employee gets paid one-and-one-half times the hourly pay for all hours over 40.

Image If the employee works more than 50 hours, the employee gets paid twice the hourly rate for those hours over 50.

LISTING 13.1 Using if-else to compute an employee’s overtime


// assume all variables are declared and initialized
// to 0 in earlier code

// check for double-time first
if (hours > 50) {
    doubleTime = 2.0 * payRate * (hours - 50);
    // 1.5 pay for middle 10 hours
    halftime = 1.5 * payRate * 10.0;
} else {
    // no double because no hours over 50
    doubleTime = 0.0;
}

// check for time-and-a-half
if ((hours > 40) && (hours <= 50)) {
    halftime = 1.5 * payRate * (hours - 40);
}

// compute regular pay for everybody
if (hours <= 40) {
     regPay = hours * payRate;
} else {
   regPay = 40 * payRate;
}

// add the parts to get total gross pay
totalPay = regPay + halftime + doubleTime;



Note

You’ll notice a new operator in Listing 13.1, the and operator, &&. && combines two conditions. Both conditions must be true for the entire if to be true. Therefore, if ((hours > 40) && (hours <= 50)) means the hours must be over 40 and less than or equal to 50 for the if to be true.


The while Loop

Java supports several kinds of loops. The while loop continues as long as a condition is true. Here is the format of the while loop:

while (condition) {
    block of one or more Java statements;
}

While the condition remains true, the block repeats, but as soon as the condition becomes false, the loop body stops executing. It’s incumbent upon you to modify the condition inside the loop’s body or the loop will never stop.

In some cases, the body of the while loop will never execute. If the condition is false upon entering the loop, Java skips the loop’s body and continues with the rest of the program. Earlier, you saw how an if statement can inform a user if the user enters invalid data. With looping, you can take the user’s input validation a step further: You can keep asking the user for an answer until the user enters a value that falls within your program’s expected range.

The following code uses a while loop to keep asking the user for an age value until the user enters a value greater than zero:

getAge(age);  // calls a procedure to get the user's age
while (age <= 0) {
     // user didn't enter proper age
     System.out.println(" You entered a bad age value.");
     System.out.println("Try again please.");
     getAge(age);
}
System.out.println(" Thank you");
// when execution gets here, age contains a positive value

Here is an example of the output:

How old are you? -16
<beep>

You entered a bad age value.
Try again please.
How old are you? 0
<beep>

You entered a bad age value.
Try again please.
How old are you? 22

Thank you

The for Loop

The simplest for loop in Java works very much like JavaScript. Here is the general format of the for loop:

for (startExpression; testExpression; countExpression) {
    block of one or more Java statements;
}

Java evaluates the startExpression before the loop begins. Typically, the startExpression is an assignment statement (such as ctr = 1;), but the startExpression can be any legal expression you specify. Java evaluates the startExpression only once, at the top of the loop, just before the loop begins.


Caution

Although semicolons appear twice in the for’s parenthetical control statement, you should never put a semicolon after the for’s closing parenthesis or the for loop will never repeat its body of code.


The for statement tests its condition at the top of the loop. Here’s the way the test works:

Image If the testExpression is true when the loop begins, the body of the loop executes.

Image If the testExpression is false when the loop begins, the body of the loop never executes.

A count is one of the quickest ways to see how the for loop operates. Consider the following for loop:

for (int ctr = 1; ctr <= 13; ctr++) {
    System.out.print(ctr);
    System.out.print(" ");
}

When the code runs, here is what the user sees:

1 2 3 4 5 6 7 8 9 10 11 12 13

You don’t have to increment the countExpression. You can increment or decrement the variable by any value each time the loop executes. The following code prints all even numbers below 20:

System.out.println("Even numbers below 20:");
for (int num = 2; num <= 20; num+= 2) {  // adds 2 each loop iteration
    System.out.println(num);
}

From Details to High-Level

Throughout this hour, you’ve been studying the details of the Java language. If you’ve made it through without too many scars, you will be surprised at how much you also know of C and C++ when you look at a program written in one of those two languages.

Two areas of Java programming that this hour did not concentrate on are

Image Input and output (I/O)

Image Object-oriented programming (OOP) concepts

It was important to focus on the language specifics in this hour. Now that you have done that, you are ready to tackle the other side of Java. Fortunately, I/O is rather simple in Java because the built-in library routines that come with Java enable you to get the user’s input and display output relatively easily. As you learn about Java I/O in the next hour, you’ll also learn about how Java supports OOP.

Summary

The goal of this hour was to teach you about Java operators and the language’s fundamental commands. You now understand how to control Java programs and how to form mathematical expressions in Java. You saw how knowledge of JavaScript helped you master Java more quickly due to the similarities between the programming languages.

When you finish the next hour, you will put everything together and begin using NetBeans to enter and test the programs you write.

Q&A

Q. Why should I use escape characters?

A. Escape characters were more important before windows-type environments due to the row and column textual nature of older computer screens, but you’ll still use escape characters in modern-day Java (and C and C++) programs to represent characters that you cannot type directly from your keyboard, such as a carriage return character.

Q. Which should I use, the conditional operator or the if statement?

A. Although you saw both the conditional operator and an equivalent if statement for comparison in this hour, the two are for different purposes. The if statement can be much more complex than the conditional statement because you can use the else and blocks to execute many statements depending on the complexity of the problem you’re coding. Use the conditional for short, one-statement conditional bodies that produce results that you’ll assign to other variables. Most of the time, a multiline if-else statement is easier to maintain than a complex conditional statement.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. True or false: You can change a Java literal just as you can change the value of a variable.

2. How would you store a quotation mark in a character variable named aQuote?

3. How many integer data types does Java support?

4. What is the lowest subscript in a Java array?

5. How many different values can a Boolean variable hold?

6. Describe what the modulus operator does.

7. Rewrite the following code in Java using only one variable and one operator:

sum = sum * 18;

8. What is in the value of y when the following code completes?

int x, y;
x = 4;
y = ++x + 3 * 2;

9. What is wrong with the following for loop?

for (int num = 1; num > 20; num++); {
    System.out.println("Hello!");
}

10. True or false: You must increment the for loop’s variable by one each time through the loop.

Answers

1. False. You cannot change a literal.

2. Store the escape character for the quotation mark.

3. Java supports four integer data types: byte, short, int, and long.

4. The first subscript in a Java array is 0.

5. A Boolean variable can hold one of two possible values.

6. The modulus operator returns the integer remainder of a division between two integers.

7. sum*=18;

8. 11

9. The semicolon at the end of the for statement causes the loop to execute without ever doing anything but looping. Once the loop finishes, the System.out.println() executes one time.

10. False. You can increment, decrement, or change the loop variable by whatever value you want.

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

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