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

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

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

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

4

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

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

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

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

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

9E-324 Positive range: 4. -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 .Numerical Data Types Name byte ort Range Storage Size oat Negative range: -3. Inc. (c) 2007 Pearson Education.7976931348623157E+308 to -4. 0-13-222158-6 ¢ ¡   ong ±263 to 263±1 i. All rights reserved.e.. Introduction to Java Programming.7976931348623157E+308 32-bit IEEE 754 double 64-bit IEEE 754 Liang.4028235E+38 to -1.9E-324 to 1.4E-45 to 3.4E-45 Positive range: 1. Sixth Edition.4028235E+38 Negative range: -1.

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

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

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

emainder Operator emainder is very use ul in programming. (c) 2007 Pearson Education. uppose today is aturday and you and your riends are going to meet in 10 days. Introduction to Java Programming. For example. Sixth Edition. 0-13-222158-6 § (6 + 10 % 7 is 2 The 2 nd day in a week is Tuesday ¦ 19 . an even number % 2 is al ays 0 and an odd number % 2 is al ays 1. o you can use this property to determine hether a number is even or odd. 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. All rights reserved. Inc.

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

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

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

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

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

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

Sixth Edition. All rights reserved. (c) 2007 Pearson Education.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. Introduction to Java Programming. 0-13-222158-6 26 . 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. 0-13-222158-6 27 . (c) 2007 Pearson Education. Introduction to Java Programming. Sixth Edition. Inc.

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

Sixth Edition. The expression (var++) evaluates to the original value in var and increments var by 1. Liang. The expression (var--) evaluates to the original value in var and decrements var by 1. (c) 2007 Pearson Education. Inc. Introduction to Java Programming.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) decrements var by 1 and evaluates to the new value in var after the decrement. 0-13-222158-6 29 . All rights reserved.

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

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

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

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

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

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

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

0-13-222158-6 37 .out. Sixth Edition.println(++ch). (ASCII) Four hexadecimal digits. Liang. (ASCII) char numChar = '4'. char letter = '\u0041'. Introduction to Java Programming.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. Inc. All rights reserved. (c) 2007 Pearson Education. System. the follo ing statements display character b. char ch = 'a'. For example. (Unicode) char numChar = '\u0034'.

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

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

0-13-222158-6 . Inc.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. All rights reserved. Introduction to Java Programming. (c) 2007 Pearson Education. Sixth Edition.

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

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

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

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

0-13-222158-6 45 . // String Chapter is concatenated ith number 2 String s = "Chapter" + 2.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'. (c) 2007 Pearson Education. All rights reserved. Inc. Sixth Edition. // s becomes SupplementB Liang. Introduction to Java Programming.

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

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

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.

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

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

50

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

Introduction to Java Programming. then the maximum number of quarters. Sixth Edition. quarters. ComputeChange Liang. Your program should report maximum number of dollars. in this order. (c) 2007 Pearson Education. 0-13-222158-6 Run 52 . dimes. nickels. Inc. and pennies. and so on. All rights reserved.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.

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

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

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

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

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

and then compute the current second. (c) 2007 Pearson Education. All rights reserved. Introduction to Java Programming. Inc. 1970 G T. The currentTime illis method in the System class returns the current time in milliseconds since the midnight.CurrentTimeMills() ShowCurrentTime Run 58 Liang.) You can use this method to obtain the current time. Sixth Edition. 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. Elapsed time Time Unix Epoch 01-01-1970 00:00:00 GMT Current Time System. January 1. 0-13-222158-6 . (1970 as the year hen the Unix operating system as formally introduced. and hour as follo s.

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

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

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

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

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

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

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

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

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

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

Sixth Edition.exit(0).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. int number = Integer. // Display the result System.QUESTION_MESSAGE).println("The number is between 1 and 100. System. "ShowLogicErrors". All rights reserved. Inc.out.showInputDialog(null. 0-13-222158-6   69 . (c) 2007 Pearson Education.parseInt(input). JOptionPane. Introduction to Java Programming. } } Liang. " + "inclusively? " + ((1 < number) && (number < 100))). "Please enter an integer:".

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

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

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

0-13-222158-6 73 . so you can trace the part of the program at the breakpoint. Introduction to Java Programming. simply click the cutter of the line. you can quickly move over the sections you kno ork correctly and concentrate on the sections causing problems. (c) 2007 Pearson Education. The debugger executes every line until it encounters a breakpoint. To remove a breakpoint. All rights reserved.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. Liang. There are several ays to set a breakpoint on a line. dd Breakpoint. Using the breakpoint. Inc. You also can set breakpoints by choosing un. You ill see the line highlighted. Sixth Edition. One quick ay is to click the cutter of the line on hich you ant to put a breakpoint.

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

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

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

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

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

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

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

(c) 2007 Pearson Education. 0-13-222158-6 81 . All rights reserved. Introduction to Java Programming. Sixth Edition. Inc.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 82 .JBuilder Optional Debugger Commands in the Menu Liang. All rights reserved. (c) 2007 Pearson Education. Sixth Edition. Introduction to Java Programming.

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

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