Chapter 2 Primitive Data Types and Operations

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word

Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations hapter 3 Selection Statements Chapter 4 Loops Chapter 5 Methods §§19.1-19.3 in hapter 19 Recursion hapter 23 Algorithm Efficiency and Sorting

Chapter 6 Arrays

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

1

Objectives
To rite Java programs to per orm simple calculations (§2.2). To use identi iers to name variables, constants, methods, and classes (§2.3). To use variables to store data (§2.4-2.5). To program ith assignment statements and assignment expressions (§2.5). To use constants to store permanent data (§2.6). To declare Java primitive data types: byte, short, int, long, loat, double, and char (§2.7 ± 2.10). To use Java operators to rite expressions (§2.7 ± 2.9). To represent a string using the tring type. (§2.10) To obtain input using the JOptionPane input dialog boxes (§2.11). (Optional) To obtain input rom console (§2.13). To become amiliar ith Java documentation, programming style, and naming conventions (§2.14). To distinguish syntax errors, runtime errors, and logic errors (§2.15). To debug logic errors (§2.16).

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

2

Introducing Programming ith an xample
isting 2.1 Computing the rea o a Circle This program computes the area o the circle.
ComputeArea Run
I PO T NT NOT : To run the program rom the un button, (1) set c:\Program Files\java\jdk1.5.0\bin or path, and (2) install slides rom the Instructor esource Website to a directory (e.g., c:\ iangI ) .
3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

animation

Trace a Program xecution
public class Compute rea { /** ain method */ public static void main( tring[] args) { double radius; double area; // ssign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results ystem.out.println("The area or the circle o radius " + radius + " is " + area); } } allocate memory or radius radius no value

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

4

14159. } } memory radius area no value no value allocate memory or area Liang. // Display results ystem.animation Trace a Program xecution public class Compute rea { /** ain method */ public static void main( tring[] args) { double radius. // ssign a radius radius = 20. // Compute area area = radius * radius * 3. Inc.println("The area or the circle o radius " + radius + " is " + area). Sixth Edition. All rights reserved. 0-13-222158-6 5 . (c) 2007 Pearson Education.out. double area. Introduction to Java Programming.

out. 0-13-222158-6 6 . } } assign 20 to radius radius area 20 no value Liang.14159. // ssign a radius radius = 20.animation Trace a Program xecution public class Compute rea { /** ain method */ public static void main( tring[] args) { double radius. double area. All rights reserved. Introduction to Java Programming. Sixth Edition. // Compute area area = radius * radius * 3. // Display results ystem.println("The area or the circle o radius " + radius + " is " + area). Inc. (c) 2007 Pearson Education.

0-13-222158-6 7 . Sixth Edition. (c) 2007 Pearson Education. Introduction to Java Programming. } } compute area and assign it to variable area memory radius area 20 1256.out. // ssign a radius radius = 20.636 Liang. double area. All rights reserved. // Compute area area = radius * radius * 3. // Display results ystem.animation Trace a Program xecution public class Compute rea { /** ain method */ public static void main( tring[] args) { double radius.14159. Inc.println("The area or the circle o radius " + radius + " is " + area).

636 print a message to the console Liang. Sixth Edition. Introduction to Java Programming. // ssign a radius radius = 20. 0-13-222158-6 8 . double area.14159.animation Trace a Program xecution public class Compute rea { /** ain method */ public static void main( tring[] args) { double radius. Inc. (c) 2007 Pearson Education. } } memory radius area 20 1256.println("The area or the circle o radius " + radius + " is " + area). All rights reserved. // Compute area area = radius * radius * 3. // Display results ystem.out.

false. ( ee Appendix A.Identi iers An identi ier is a sequence o characters that consist o letters. Liang. An identi ier must start ith a letter. or null. digits. An identi ier can be o any length. an underscore (_). (c) 2007 Pearson Education. An identi ier cannot be true. Inc. and dollar signs ($). underscores (_). 0-13-222158-6 9 . All rights reserved. ± An identi ier cannot be a reserved ord. Sixth Edition.´ or a list o reserved ords). It cannot start ith a digit. Introduction to Java Programming. ³Java Key ords. or a dollar sign ($).

// Compute the second area radius = 2.0.14159. Introduction to Java Programming. (c) 2007 Pearson Education. area = radius * radius * 3. Liang.Variables // Compute the first area radius = 1. All rights reserved.println("The area is ³ + area + " for radius "+radius).out.out. 0-13-222158-6 10 . area = radius * radius * 3.println("The area is ³ + area + " for radius "+radius). System. System.14159.0. Sixth Edition. Inc.

char a. Inc. Sixth Edition. // Declare a to be a // character variable. (c) 2007 Pearson Education. 0-13-222158-6 11 . // Declare radius to // be a double variable. // Declare x to be an // integer variable.Declaring Variables int x. Introduction to Java Programming. All rights reserved. double radius. Liang.

Liang. All rights reserved.0 to radius. // Assign 1. // Assign 1 to x.Assignment tatements x = 1. Inc. (c) 2007 Pearson Education. 0-13-222158-6 12 . radius = 1. a = 'A'. // Assign 'A' to a. Sixth Edition.0. Introduction to Java Programming.

Sixth Edition. Liang.4.Declaring and Initializing in One tep int x = 1. (c) 2007 Pearson Education. double d = 1. Introduction to Java Programming. Inc. All rights reserved. 0-13-222158-6 13 .

Liang.Constants final datatype CONSTANTNAME = VALUE. Sixth Edition. All rights reserved. final int SIZE = 3. final double PI = 3. 0-13-222158-6 14 . (c) 2007 Pearson Education. Inc. Introduction to Java Programming.14159.

-9223372036854775808 to 9223372036854775807 64-bit ¢ ¡ ¡ int   ±231 -2147483648 to 231±1 2147483647 32-bit ¢   ¡ ¡   ±215 -32768 to 215±1 32767 16-bit ¢   ¡ ¡ -128     ±27 to 27±1 127 8-bit igned igned igned igned ¤¥ £¢ ¤ 15 .4028235E+38 Negative range: -1. (c) 2007 Pearson Education.4E-45 to 3. Inc.4028235E+38 to -1.4E-45 Positive range: 1. Introduction to Java Programming. Sixth Edition. 0-13-222158-6 ¢ ¡   ong ±263 to 263±1 i.9E-324 to 1.7976931348623157E+308 32-bit IEEE 754 double 64-bit IEEE 754 Liang..9E-324 Positive range: 4.7976931348623157E+308 to -4.Numerical Data Types Name byte ort Range Storage Size oat Negative range: -3. All rights reserved.e.

Introduction to Java Programming. You can access it at http:// . (c) 2007 Pearson Education.neu. All rights reserved.htm Liang.edu/jpt/jpt_2_3/bitdisplay/applet. Sixth Edition.ccs. Inc. 0-13-222158-6 16 .TIP An excellent tool to demonstrate ho numbers are stored in a computer as developed by ichard asala.

0 ± 0.9 9000 0.0 / 2.Numeric Operators Name + * / % Meaning Addition Subtraction Multiplication Division Remainder Example 34 + 1 34. Introduction to Java Programming. Sixth Edition.1 300 * 30 1.0 20 % 3 Result 35 33. Inc.5 2 Liang. (c) 2007 Pearson Education. 0-13-222158-6 17 . All rights reserved.

0 / 2 yields a double value 2. 0-13-222158-6 18 . Introduction to Java Programming. *. Sixth Edition.5 5 % 2 yields 1 (the remainder o the division) Liang. (c) 2007 Pearson Education. -. 5. and % 5 / 2 yields an integer 2. /. Inc. All rights reserved.Integer Division +.

an even number % 2 is al ays 0 and an odd number % 2 is al ays 1. Introduction to Java Programming. uppose today is aturday and you and your riends are going to meet in 10 days. (c) 2007 Pearson Education. Sixth Edition. What day is in 10 days? You can ind that day is Tuesday using the ollo ing expression: Saturday is the 6 th day in a week A week has 7 days A ter 10 days Liang. Inc. 0-13-222158-6 § (6 + 10 % 7 is 2 The 2 nd day in a week is Tuesday ¦ 19 . o you can use this property to determine hether a number is even or odd. For example.emainder Operator emainder is very use ul in programming. All rights reserved.

(c) 2007 Pearson Education. 0-13-222158-6 20 . Introduction to Java Programming. All rights reserved.xample: Displaying Time Write a program that obtains hours and minutes rom seconds. DisplayTime Run Liang. Sixth Edition. Inc.

5.0 .1 .1). Integers are stored precisely. ystem.1 .5000000000000001.1.0.0.out.println(1. All rights reserved. not 0.0 .out.09999999999999998. displays 0. Introduction to Java Programming. and ystem.0. 0-13-222158-6 21 . calculations ith integers yield a precise integer result. Sixth Edition.NOT Calculations involving loating-point numbers are approximated because these numbers are not stored ith complete accuracy. For example.1 . Liang.9).0.0. not 0. Inc.0.println(1.1 . There ore. (c) 2007 Pearson Education. displays 0.

0. All rights reserved. long x = 1000000. 1. Sixth Edition. and 5. 34.Number iterals A literal is a constant value that appears directly in the program. Inc. Liang. Introduction to Java Programming. For example.0 are literals in the ollo ing statements: int i = 34. double d = 5.000. (c) 2007 Pearson Education. 0-13-222158-6 22 .000.

An integer literal is assumed to be o the int type. A compilation error ould occur i the literal ere too large or the variable to hold. (c) 2007 Pearson Education. Inc. hose value is bet een -231 (-2147483648) to 231±1 (2147483647).Integer iterals An integer literal can be assigned to an integer variable as long as it can it into the variable. Liang. append it ith the letter or l. To denote an integer literal o the long type. is pre erred because l (lo ercase ) can easily be con used ith 1 (the digit one). the statement byte b = 1000 ould cause a compilation error. because 1000 cannot be stored in a variable o the byte type. All rights reserved. Introduction to Java Programming. For example. 0-13-222158-6 23 . Sixth Edition.

Inc. (c) 2007 Pearson Education. For example.Floating-Point iterals Floating-point literals are ritten ith a decimal point. 5. and 100. 0-13-222158-6 24 . Liang. For example.2D or a double number. Introduction to Java Programming. a loating-point literal is treated as a double type value.2F or a loat number. y de ault.0 is considered a double value. not a loat value.2 or 100. All rights reserved.2d or 100. you can use 100. You can make a number a loat by appending the letter or F. Sixth Edition. and make a number a double by appending the letter d or D.

is equivalent to 123. Sixth Edition.23456e2.23456e-2 is equivalent to 0. (c) 2007 Pearson Education. Inc.0123456.23456e+2. 1. 0-13-222158-6 25 . or example. and 1. Introduction to Java Programming. (or e) represents an exponent and it can be either in lo ercase or uppercase.cienti ic Notation Floating-point literals can also be speci ied in scienti ic notation. All rights reserved. same as 1.456. Liang.

All rights reserved. 0-13-222158-6 26 . Sixth Edition. (c) 2007 Pearson Education. Introduction to Java Programming. Inc.Arithmetic xpressions 3  4 x 10( y  5)( a  b  c ) 4 9 x   9(  ) 5 x x y is translated to (3+4*x)/5 ± 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) Liang.

(c) 2007 Pearson Education. 0-13-222158-6 27 . Introduction to Java Programming. Inc.xample: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the ormula: 5 celsius ! ( 9 )( fahrenheit  32) FahrenheitToCelsius Run Liang. All rights reserved. Sixth Edition.

(c) 2007 Pearson Education. Sixth Edition.0 i = i * 8 i = i / 8 i = i % 8 Liang.Shortcut Assignment Operators Operator Example += -= *= /= %= i += 8 f -= 8. Introduction to Java Programming. Inc. 0-13-222158-6 28 .0 i *= 8 i /= 8 i %= 8 Equivalent i = i + 8 f = f . All rights reserved.8.

Introduction to Java Programming. (c) 2007 Pearson Education. 0-13-222158-6 29 . Inc. The expression (var--) evaluates to the original value in var and decrements var by 1.Increment and Decrement Operators Operator ++var var++ --var var-Name preincrement postincrement predecrement postdecrement Description The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. The expression (var++) evaluates to the original value in var and increments var by 1. Sixth Edition. Liang. The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. All rights reserved.

Introduction to Java Programming. int newNum = 10 * (++i) Same effect as i = i + 1. (c) 2007 Pearson Education. int i = 10. Sixth Edition. 0-13-222158-6 © int i = 10. cont. All rights reserved. int newNum = 10 * i.Increment and Decrement Operators. int newNum = 10 * i++. ¨ 30 . Inc. Liang. Same e ect as int ne Num = 10 * i. i = i + 1.

0-13-222158-6 31 . or the same variable or multiple times such as this: int k = ++i + i.Increment and Decrement Operators. Liang. Introduction to Java Programming. Inc. Avoid using these operators in expressions that modi y multiple variables. but it also makes them complex and di icult to read. (c) 2007 Pearson Education. cont. All rights reserved. Using increment and decrement operators makes expressions short. Sixth Edition.

Inc. Sixth Edition. All rights reserved. variable++. only the ollo ing types o expressions can be statements: variable op= expression. // Where op is +. or % ++variable. all the expressions can be used as statements. 0-13-222158-6 32 . *. --variable. variable--. Liang. /. -. (c) 2007 Pearson Education.Assignment xpressions and Assignment Statements Prior to Java 2. Since Java 2. Introduction to Java Programming.

(c) 2007 Pearson Education. Sixth Edition. 0-13-222158-6 33 . Liang. Inc. long k = i * 3 + 4. double d = i * 3.1 + k / 2.Numeric Type Conversion Consider the ollo ing statements: byte i = 100. All rights reserved. Introduction to Java Programming.

i one o the operands is loat. (c) 2007 Pearson Education. Other ise. the other is converted into double. the other is converted into loat. the other is converted into long. Other ise.Conversion ules When per orming a binary operation involving t o operands o di erent types. I one o the operands is double. 3. 4. Java automatically converts the operand based on the ollo ing rules: 1. Sixth Edition. 0-13-222158-6 34 . Liang. Introduction to Java Programming. both operands are converted into int. Other ise. All rights reserved. 2. Inc. i one o the operands is long.

Introduction to Java Programming.0. (Fraction part is truncated) What is rong? int x = 5 / 2.9. double Liang.0. Inc. long. (type idening) Explicit casting int i = (int)3. (c) 2007 Pearson Education. 0-13-222158-6 35 . All rights reserved.Type Casting Implicit casting double d = 3. int. (type narrowing) int i = (int)3. float. range increases byte. short. Sixth Edition.

Introduction to Java Programming. All rights reserved. 0-13-222158-6 36 . (c) 2007 Pearson Education. SalesTax Run Liang.xample: Keeping T o Digits After Decimal Points Write a program that displays the sales tax ith t o digits after the decimal point. Sixth Edition. Inc.

the follo ing statements display character b. Sixth Edition.println(++ch).Character Data Type char letter = 'A'. (Unicode) NOT : The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. All rights reserved. (ASCII) Four hexadecimal digits. (Unicode) char numChar = '\u0034'. Liang. Inc. System. char letter = '\u0041'. For example. char ch = 'a'. Introduction to Java Programming. 0-13-222158-6 37 . (c) 2007 Pearson Education. (ASCII) char numChar = '4'.out.

Inc. Unicode can represent 65535 + 1 characters. and display of ritten texts in the orld¶s diverse languages. preceded by \u. All rights reserved.Unicode Format Java characters use Unicode. expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters Liang. Unicode takes t o bytes. (c) 2007 Pearson Education. 0-13-222158-6 38 . Sixth Edition. processing. a 16-bit encoding scheme established by the Unicode Consortium to support the interchange. Introduction to Java Programming.

(c) 2007 Pearson Education. DisplayUnicode Run Liang. Introduction to Java Programming. Inc. All rights reserved. 0-13-222158-6 39 .xample: Displaying Unicodes Write a program that displays t o Chinese characters and three Greek letters. Sixth Edition.

Inc. (c) 2007 Pearson Education. All rights reserved. Sixth Edition. 0-13-222158-6 . Introduction to Java Programming.scape Sequences for Special Characters Description Backspace Tab inefeed Escape Sequence \b \t \n Unicode \u0008 \u0009 \u000A \u000D \u005C \u0027 \u0022 40 Carriage return \r Backslash Single Quote Double Quote \\ \' \" Liang.

Introduction to Java Programming. Inc. (c) 2007 Pearson Education. 0-13-222158-6 41 . All rights reserved.Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang. Sixth Edition.

ASCII Character Set. Introduction to Java Programming. All rights reserved. cont. (c) 2007 Pearson Education. Sixth Edition. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f Liang. 0-13-222158-6 42 . Inc.

All rights reserved. Liang. // Same as char c = (char)97.Casting bet een char and Numeric Types int i = 'a'. // Same as int i = (int)'a'. Inc. char c = 97. (c) 2007 Pearson Education. Sixth Edition. Introduction to Java Programming. 0-13-222158-6 43 .

´ For the time being.The String Type The char type only represents one character. To represent a string of characters. The String type is not a primitive type. (c) 2007 Pearson Education. you just need to kno ho to declare a String variable. ho to assign a string to the variable. String message = "Welcome to Java". Sixth Edition. Inc. All rights reserved. For example. 0-13-222158-6 44 . use the data type called String. ³Classes and Objects. It is kno n as a reference type. eference data types ill be thoroughly discussed in Chapter 6. Any Java class can be used as a reference type for a variable. String is actually a predefined class in the Java library just like the System class and JOptionPane class. and ho to concatenate strings. Introduction to Java Programming. Liang.

Sixth Edition. Inc. All rights reserved. 0-13-222158-6 45 .String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java". // s becomes Chapter2 // String Supplement is concatenated ith character B String s1 = "Supplement" + 'B'. // s becomes SupplementB Liang. // String Chapter is concatenated ith number 2 String s = "Chapter" + 2. (c) 2007 Pearson Education. Introduction to Java Programming.

All rights reserved.5 Scanner class (§2. 1.Obtaining Input This book provides three ays of obtaining input.16) Liang. Inc.15) Using the JDK 1. Introduction to Java Programming. 0-13-222158-6 46 . Using JOptionPane input dialogs (§2. 2. (c) 2007 Pearson Education. Sixth Edition.

Getting Input from Input Dialog Boxes
String string = JOptionPane.sho InputDialog( null, ³Prompting essage´, ³Dialog Title´, SSAG )); JOptionPane.QU STION_

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

47

T o Ways to Invoke the

ethod

There are several ays to use the sho InputDialog method. For the time being, you only need to kno t o ays to invoke it. One is to use a statement as sho n in the example:
String string = JOptionPane.sho InputDialog(null, x, SSAG )); y, JOptionPane.QU STION_

here x is a string for the prompting message, and y is a string for the title of the input dialog box. The other is to use a statement like this:
JOptionPane.sho InputDialog(x);

here x is a string for the prompting message.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

48

Converting Strings to Integers
The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns ³123´. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follo s: int intValue = Integer.parseInt(intString); here intString is a numeric string such as ³123´.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

49

Converting Strings to Doubles
To convert a string into a double value, you can use the static parseDouble method in the Double class as follo s: double doubleValue =Double.parseDouble(doubleString); here doubleString is a numeric string such as ³123.45´.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6

50

number of years. 0-13-222158-6 .xample: Computing oan Payments This program lets the user enter the interest rate. (c) 2007 Pearson Education. and loan amount and computes monthly payment and total payment. loanA ount v onthlyInt erestRate 1 1 nu berOfYearsv12 (1  onthlyInt erestRate ) ComputeLoan Run 51 Liang. Sixth Edition. Inc. Introduction to Java Programming. All rights reserved.

(c) 2007 Pearson Education. Your program should report maximum number of dollars.xample: onetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars. nickels. quarters. and pennies. Sixth Edition. then the maximum number of quarters. in this order. Introduction to Java Programming. dimes. 0-13-222158-6 Run 52 . ComputeChange Liang. All rights reserved. Inc. and so on.

0-13-222158-6 remainingAmount 1156 remainingAmount initialized 53 . remainingAmount = remainingAmount % 5. All rights reserved. remainingAmount = remainingAmount % 25.56 int remainingAmount = (int)(amount * 100). Introduction to Java Programming. // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5. remainingAmount = remainingAmount % 10. // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10. Sixth Edition. // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount.Trace ComputeChange Suppose amount is 11. remainingAmount = remainingAmount % 100. // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25. (c) 2007 Pearson Education. // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100. Inc. Liang.

Inc. Sixth Edition. remainingAmount = remainingAmount % 25. remainingAmount = remainingAmount % 100. // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25. (c) 2007 Pearson Education. // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100. // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5. // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount. All rights reserved. 1156 11 numberOfOneDollars assigned Liang. remainingAmount = remainingAmount % 10.56 remainingAmount numberOfOneDollars int remainingAmount = (int)(amount * 100). 0-13-222158-6 54 . Introduction to Java Programming. remainingAmount = remainingAmount % 5. // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10.animation Trace ComputeChange Suppose amount is 11.

// Find the number of one dollars int numberOfOneDollars = remainingAmount / 100. remainingAmount = remainingAmount % 10. 0-13-222158-6 55 . Sixth Edition. // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5. // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10. All rights reserved. // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount. (c) 2007 Pearson Education. Inc. // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25. 56 11 remainingAmount updated Liang. remainingAmount = remainingAmount % 5.56 remainingAmount numberOfOneDollars int remainingAmount = (int)(amount * 100). remainingAmount = remainingAmount % 25.animation Trace ComputeChange Suppose amount is 11. Introduction to Java Programming. remainingAmount = remainingAmount % 100.

remainingAmount = remainingAmount % 100. remainingAmount = remainingAmount % 5. 0-13-222158-6 56 .56 remainingAmount numberOfOneDollars int remainingAmount = (int)(amount * 100). (c) 2007 Pearson Education. Inc. // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10.animation Trace ComputeChange Suppose amount is 11. // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount. // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100. // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5. remainingAmount = remainingAmount % 10. // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25. remainingAmount = remainingAmount % 25. All rights reserved. 56 11 numberOfOneQuarters 2 numberOfOneQuarters assigned Liang. Sixth Edition. Introduction to Java Programming.

6 11 numberOfQuarters 2 remainingAmount updated Liang.56 remainingAmount numberOfOneDollars int remainingAmount = (int)(amount * 100). // Find the number of nickels in the remaining amount int numberOfNickels = remainingAmount / 5. (c) 2007 Pearson Education. Introduction to Java Programming. Sixth Edition. Inc. // Find the number of one dollars int numberOfOneDollars = remainingAmount / 100. remainingAmount = remainingAmount % 25. // Find the number of pennies in the remaining amount int numberOfPennies = remainingAmount. remainingAmount = remainingAmount % 100. remainingAmount = remainingAmount % 10. remainingAmount = remainingAmount % 5. // Find the number of quarters in the remaining amount int numberOfQuarters = remainingAmount / 25. 0-13-222158-6 57 . All rights reserved. // Find the number of dimes in the remaining amount int numberOfDimes = remainingAmount / 10.animation Trace ComputeChange Suppose amount is 11.

(1970 as the year hen the Unix operating system as formally introduced.CurrentTimeMills() ShowCurrentTime Run 58 Liang. minute.Example: Displaying Current Time Write a program that displays current time in G T in the format hour:minute:second such as 1:45:19. 0-13-222158-6 . Introduction to Java Programming. 1970 G T. and then compute the current second. Elapsed time Time Unix Epoch 01-01-1970 00:00:00 GMT Current Time System.) You can use this method to obtain the current time. and hour as follo s. Inc. The currentTime illis method in the System class returns the current time in milliseconds since the midnight. (c) 2007 Pearson Education. All rights reserved. January 1. Sixth Edition.

double. byte. Scanner scanner = new Scanner(System. or boolean value. nextDouble(). 0-13-222158-6 Run 59 . System. float.out. nextByte(). double d = scanner. nextShort(). nextLong(). 2.in). Inc. nextInt().Optional Getting Input Using Scanner 1. short.print("Enter a double value: "). All rights reserved. Introduction to Java Programming. int. long. Sixth Edition. or nextBoolean() to obtain to a string. For example. Create a Scanner object Scanner scanner = new Scanner(System.in). nextFloat(). TestScanner Liang. (c) 2007 Pearson Education. Use the methods next().nextDouble().

All rights reserved. Introduction to Java Programming. Sixth Edition. 0-13-222158-6 60 .Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing ines Block Styles Liang. (c) 2007 Pearson Education. Inc.

Sixth Edition. its key features. Introduction to Java Programming. Inc. and any unique techniques it uses.Appropriate Comments Include a summary at the beginning of the program to explain hat the program does. class section. its supporting data structures. All rights reserved. Include your name. instructor. date. and a brief description at the beginning of the program. 0-13-222158-6 61 . Liang. (c) 2007 Pearson Education.

the variables radius and area. (c) 2007 Pearson Education. All rights reserved. Variables and method names: ± Use lo ercase. concatenate all in one. Introduction to Java Programming. and the method computeArea. Sixth Edition. 0-13-222158-6 62 . use lo ercase for the first ord.Naming Conventions Choose meaningful and descriptive names. Inc. and capitalize the first letter of each subsequent ord in the name. If the name consists of several ords. For example. Liang.

the constant PI and MAX_VALUE Liang. Introduction to Java Programming.Naming Conventions. Sixth Edition. For example. cont. Class names: ± Capitalize the first letter of each ord in the name. the class name ComputeArea. 0-13-222158-6 63 . All rights reserved. and use underscores to connect ords. (c) 2007 Pearson Education. For example. Constants: ± Capitalize all letters in constants. Inc.

Liang. 0-13-222158-6 64 . Inc. Spacing ± Use blank line to separate segments of the code.Proper Indentation and Spacing Indentation ± Indent t o spaces. All rights reserved. Sixth Edition. (c) 2007 Pearson Education. Introduction to Java Programming.

Next-line style public class Test { public static void main(String[] args) { System.out. 0-13-222158-6 65 . All rights reserved.out. Sixth Edition. Introduction to Java Programming. Inc. (c) 2007 Pearson Education.println("Block Styles"). } } End-of-line style public class Test { public static void main(String[] args) { System.Block Styles Use end-of-line style for braces. } } Liang.println("Block Styles").

0-13-222158-6 66 . Sixth Edition.Programming Errors Syntax Errors ± Detected by the compiler untime Errors ± Causes the program to abort Logic Errors ± Produces incorrect result Liang. Inc. (c) 2007 Pearson Education. Introduction to Java Programming. All rights reserved.

out.println(i + 4). 0-13-222158-6 67 .Syntax Errors public class ShowSyntaxErrors public static void main(String[] args) i = 30. } } Liang. Inc. Introduction to Java Programming. (c) 2007 Pearson Education. Sixth Edition. All rights reserved. System.

Runtime Errors public class ShowRuntimeErrors public static void main(String[] args) int i = 1 / 0. Sixth Edition. 0-13-222158-6 68 . All rights reserved. Introduction to Java Programming. } } Liang. (c) 2007 Pearson Education. Inc.

Introduction to Java Programming. JOptionPane.println("The number is between 1 and 100. "ShowLogicErrors". // Display the result System. All rights reserved. int number = Integer.exit(0).parseInt(input). } } Liang. (c) 2007 Pearson Education. Inc.showInputDialog(null. "Please enter an integer:". System. " + "inclusively? " + ((1 < number) && (number < 100))). 0-13-222158-6   69 . Sixth Edition.Logic Errors public class ShowLogicErrors // Determine if a number is between 1 and 100 inclusively public static void main(String[] args) // Prompt the user to enter a number String input = JOptionPane.QUESTION_MESSAGE).out.

catch errors by reading the program). But for a large. Sixth Edition.e. simple program. Introduction to Java Programming. Liang. The process of finding and correcting errors is called debugging. complex program. or you can insert print statements in order to sho the values of the variables or the execution flo of the program. A common approach to debugging is to use a combination of methods to narro do n to the part of the program here the bug is located. 0-13-222158-6 70 . Inc.. the most effective approach for debugging is to use a debugger utility. You can hand-trace the program (i.Debugging Logic errors are called bugs. This approach might ork for a short. All rights reserved. (c) 2007 Pearson Education.

All rights reserved. Display call stack. Sixth Edition. Display variables. (c) 2007 Pearson Education. Liang. You can use a debugger to Execute a single statement at a time. Modify variables. Set breakpoints. Inc. 0-13-222158-6 71 . Trace into or stepping over a method. Introduction to Java Programming.Debugger Debugger is a program that facilitates debugging.

Liang. (c) 2007 Pearson Education. The JBuilder debugger enables you to set breakpoints and execute programs line by line. you can atch the values stored in variables. As your program executes. observe hich methods are being called. You can pinpoint bugs in your program ith the help of the JBuilder debugger ithout leaving the IDE. and kno hat events have occurred in the program. Sixth Edition. 0-13-222158-6 72 . Inc. All rights reserved.JBuilder Optional Debugging in JBuilder The debugger utility is integrated in JBuilder. Introduction to Java Programming.

Introduction to Java Programming. simply click the cutter of the line. 0-13-222158-6 73 . Sixth Edition. You also can set breakpoints by choosing un. dd Breakpoint. One quick ay is to click the cutter of the line on hich you ant to put a breakpoint. There are several ays to set a breakpoint on a line. you can quickly move over the sections you kno ork correctly and concentrate on the sections causing problems. All rights reserved. Inc. (c) 2007 Pearson Education. so you can trace the part of the program at the breakpoint. The debugger executes every line until it encounters a breakpoint. Liang. To remove a breakpoint.JBuilder Optional Setting Breakpoints A breakpoint is a stop sign placed on a line of source code that tells the debugger to pause hen this line is encountered. Using the breakpoint. You ill see the line highlighted.

(c) 2007 Pearson Education. and can remove breakpoints at any time during debugging. Breakpoint Liang. cont. you can set as many breakpoints as you ant. Introduction to Java Programming. Sixth Edition. The breakpoints are restored hen you reopen it. The project retains the breakpoints you have set hen you exit the project. 0-13-222158-6 74 .JBuilder Optional Setting Breakpoints. Cutter area As you debug your program. All rights reserved. Inc.

Starting the debugger Set breakpoints.java in the project pane. and right-click the mouse button to display the context menu. Sixth Edition. 0-13-222158-6 75 . Click Debug Using Defaults in the context menu to start debugging. All rights reserved.. Liang.g. Inc. Introduction to Java Programming. Choose the program (e. 2.JBuilder Optional 1. (c) 2007 Pearson Education. Sho CurrentTime.

(c) 2007 Pearson Education.JBuilder Optional Console Vie Console vie displays output and errors. 0-13-222158-6 76 . You can also enter input from the console vie . Console vie Liang. All rights reserved. Inc. Introduction to Java Programming. Sixth Edition.

Introduction to Java Programming. Sixth Edition. All rights reserved. Call stacks Liang. Inc.JBuilder Optional Stack Vie Stack vie displays the methods and local variables in the call stack. 0-13-222158-6 77 . (c) 2007 Pearson Education.

All rights reserved.JBuilder Optional Watch Vie You can add variables to the atch vie . Introduction to Java Programming. Inc. (c) 2007 Pearson Education. Watch vie displays the contents of the variables in the atch vie . 0-13-222158-6 78 . Sixth Edition. Data atches Liang.

JBuilder Optional Adding Variables to Watch Vie There are several ays to add variables to the atch vie . Sixth Edition. 0-13-222158-6 79 . (c) 2007 Pearson Education. Introduction to Java Programming. A simple ay is to highlight the variable and then right-click the mouse to display the context menu. Choose Add Watch in the context menu to add the variable to the atch vie . Inc. All rights reserved. Liang.

When JBuilder is in the debugging mode.JBuilder Optional Controlling Program Execution The program pauses at the first breakpoint line encountered. called the current execution point. Sixth Edition. 0-13-222158-6 80 . the un menu contains the debugging commands. Inc. When the program pauses at the execution point. is highlighted and has a green arro to the left. You also can inspect or modify the values of variables in the program. (c) 2007 Pearson Education. The execution point marks the next line of source code to be executed by the debugger. Here are the commands for controlling program execution: Liang. This line. All rights reserved. you can issue debugging commands to control the execution of the program. The toolbar contains additional commands that are not in the un menu. Most of the commands also appear in the toolbar under the message pane. Introduction to Java Programming.

Sixth Edition. All rights reserved.JBuilder Optional Debugger Commands in the Toolbar Reset program Resume program Pause program Step over Step Step into out Liang. Inc. 0-13-222158-6 81 . (c) 2007 Pearson Education. Introduction to Java Programming.

JBuilder Optional Debugger Commands in the Menu Liang. (c) 2007 Pearson Education. Sixth Edition. All rights reserved. 0-13-222158-6 82 . Inc. Introduction to Java Programming.

Use Reset to restart an application from the beginning. the entire method is executed ithout stepping through it. This command terminates debugging and returns to the normal editing session. Sixth Edition. All rights reserved. Resume Program continues the current debugging session or restarts one that has finished or been reset. Introduction to Java Programming. Run to End of Method runs the program until it reaches the end of the current method or a breakpoint. If the statement contains a call to a method. Step Into executes a single statement or steps into a method. Show Execution Point positions the cursor at the execution point in the content pane. or if variables or data structures become corrupted ith un anted values. (c) 2007 Pearson Education. starting from the current execution point. Reset Program ends the current program and releases it from memory. 0-13-222158-6 83 . or at a breakpoint. Inc. Step Out executes all the statements in the current method and returns to its caller. as hen you make a change to the code and ant to run again from the beginning. Liang. Run to Cursor runs the program.JBuilder Optional Debugger Commands Step Over executes a single statement. and pauses and places the execution point on the line of code containing the cursor.

JBuilder Optional Tracing Execution You may trace the program line by line and see the contents of the variables in the stack vie . (c) 2007 Pearson Education. This is most convenient. Liang. 0-13-222158-6 84 . Introduction to Java Programming. Inc. All rights reserved. Sixth Edition.

Sign up to vote on this title
UsefulNot useful