0% found this document useful (0 votes)
9 views48 pages

02 Slide

Uploaded by

Stricker Man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views48 pages

02 Slide

Uploaded by

Stricker Man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

1

Chapter 2 Elementary
Programming
2

Introducing Programming
with an Example
Listing 2.1 Computing the
Area of a Circle
This program computes the
area of the circle.

ComputeArea IMPORTANT NOTE: To enable the buttons,


you must download the entire slide file
slide.zip and unzip the files into a directory
Run (e.g., c:\slide) .
animation 3

Trace a Program Execution


public class ComputeArea { allocate
/** Main method */ memory for
public static void main(String[] args) { radius
double radius; radiu no value
double area; s
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle
of radius " +
radius + " is " + area);
}
}
animation 4

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radiu no value
double area; s
area no value
// Assign a radius
radius = 20;
allocate
// Compute area memory for
area = radius * radius * 3.14159; area
// Display results
System.out.println("The area for the circle
of radius " +
radius + " is " + area);
}
}
animation 5

Trace a Program Execution


public class ComputeArea { assign 20 to
/** Main method */ radius
public static void main(String[] args) {
double radius; radiu 20
double area; s
area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle
of radius " +
radius + " is " + area);
}
}
animation 6

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radiu 20
double area; s
area 1256.636
// Assign a radius
radius = 20;

// Compute area compute area and


area = radius * radius * 3.14159; assign it to variable
area
// Display results
System.out.println("The area for the circle
of radius " +
radius + " is " + area);
}
}
animation 7

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radiu 20
double area; s
area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;
print a message to
// Display results the console
System.out.println("The area for the circle
of radius " +
radius + " is " + area);
}
}
8

Identifier
• sequence of characters that consist of
letters, digits, underscores (_), and dollar
signs ($).
• cannot start with a digit.
▫ An identifier cannot be a reserved word. (See
Appendix A, “Java Keywords,” for a list of
reserved words).
• An identifier cannot be true, false, or
null.
• An identifier can be of any length.
9

Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
10

Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
11

Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to


radius;
a = 'A'; // Assign 'A' to a;
12

Declaring and Initializing


in One Step
• int x = 1;
• double d = 1.4;
13

Constants
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

Must be declared at initialization.


14

Numerical Data Types


Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
15
Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2
16
Integer Division

+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
2.5 will be truncated (not rounded) if
assigned to an integer

5 % 2 yields 1 (the remainder of the


division)
17

Problem: Displaying Time


Write a program that obtains hours
and minutes from seconds.

DisplayTime Run
18

Number Literals
A literal is a constant value that
appears directly in the program. For
example, 34, 1,000,000, and 5.0 are
literals in the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;
19

Arithmetic Expressions

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)

Remember: Order of operations!


20
Shortcut Assignment
Operators
OperatorExample Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
21

Increment / Decrement

++var preincrement
var++ postincrement

--var predecrement
var-- postdecrement

What is the difference between ++var and


var++?
22

Numeric Type Conversion


Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
23

Conversion Rules
When performing a binary operation
involving two operands of different types,
Java automatically converts the operand
based on the following rules:

1. If one of the operands is double, the


other is converted into double.
2. Otherwise, if one of the operands is float,
the other is converted into float.
3. Otherwise, if one of the operands is long,
the other is converted into long.
4. Otherwise, both operands are converted
into int.
24

Type Conversion
• Widening: convert numeric type of
smaller range to type of larger range
▫ Done implicitly
• Narrowing: convert numeric type of
larger range to type of smaller range
▫ May result in overflow
▫ Explicit casts
25
Type Casting
Implicit casting
double d = 3; (type widening)

Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (truncate decimal)
What is wrong? int x = 5 / 2.0;

range increases

byte, short, int, long, float, double


26

Character Data Type


Four hexadecimal
char letter = 'A'; (ASCII)digits.
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034';
(Unicode)

NOTE: Increment (decrement) operators on char


variables get the next (preceding) Unicode
character.
What character is printed by these statements?
char ch = 'a';
System.out.println(++ch);
27
Escape Sequences for Special
Characters
Description Escape Sequence
Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
28

Appendix B: ASCII Character Set


ASCII Character Set is a subset of the Unicode from \
u0000 to \u007f
29
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

Unicode representation of characters


30

The String Type


String message = "Welcome to Java";

Compare char and String:


char: single character
String: several characters
char literal ‘a’
String literal “A”
char is a primitive data type
String is predefined class (reference type)

More on classes later!


String Concatenation (+ 31

operator)
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number


2
String s = "Chapter" + 2; // s becomes
Chapter2

// String Supplement is concatenated with


character B
String s1 = "Supplement" + 'B'; // s becomes
SupplementB
32

Problem: Monetary 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, quarters, dimes, nickels, and
pennies. Your program should report
maximum number of dollars, then the
maximum number of quarters, and so
on, in this order.ComputeChange Run
33
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); 1156
remainingA
// Find the number of one dollars mount
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100; remainingAmount
initialized
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining


amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;
animation 34
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); 1156
remainingA
// Find the number of one dollars mount
int numberOfOneDollars = remainingAmount / 100; numberOfOneD 11
remainingAmount = remainingAmount % 100;
ollars
// Find the number of quarters in the remaining
amount numberOfOneD
int numberOfQuarters = remainingAmount / 25; ollars assigned
remainingAmount = remainingAmount % 25;

// Find the number of dimes in the remaining


amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;
animation 35
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); 56
remainingA
// Find the number of one dollars mount
int numberOfOneDollars = remainingAmount / 100; numberOfOneD 11
remainingAmount = remainingAmount % 100;
ollars
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25; remainingAmou
remainingAmount = remainingAmount % 25; nt updated
// Find the number of dimes in the remaining
amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;
animation 36
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); 56
remainingA
// Find the number of one dollars mount
int numberOfOneDollars = remainingAmount / 100; numberOfOneD 11
remainingAmount = remainingAmount % 100;
ollars
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25; numberOfOneQ 2
remainingAmount = remainingAmount % 25; uarters
// Find the number of dimes in the remaining numberOfOneQ
amount
int numberOfDimes = remainingAmount / 10; uarters assigned
remainingAmount = remainingAmount % 10;

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;
animation 37
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); 6
remainingA
// Find the number of one dollars mount
int numberOfOneDollars = remainingAmount / 100; numberOfOneD 11
remainingAmount = remainingAmount % 100;
ollars
// Find the number of quarters in the remaining
amount
int numberOfQuarters = remainingAmount / 25; numberOfQua 2
remainingAmount = remainingAmount % 25; rters
// Find the number of dimes in the remaining
amount
int numberOfDimes = remainingAmount / 10; remainingAmou
remainingAmount = remainingAmount % 10; nt updated

// Find the number of nickels in the remaining


amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;

// Find the number of pennies in the remaining


amount
int numberOfPennies = remainingAmount;
38

Problem: Displaying Current Time


Write a program that displays current time in
GMT in the format hour:minute:second such as
1:45:19.
The currentTimeMillis method in the System
class returns the current time in milliseconds
since the midnight, January 1, 1970 GMT.
(1970 was the year when the Unix operating
system was formally introduced.) You can use
this method to obtain the current time, and
then computeElapsed
the current second,
time
ShowCurrentTime
minute, and
Time
hour Unix
asEpoch
follows. Current Time
01-01-1970
00:00:00 GMT
System.CurrentTimeMills() Run
39
Programming Style and
Documentation
•Appropriate Comments
•Naming Conventions
•Proper Indentation and
Spacing Lines
•Block Styles

Java is case sensitive!


40

Appropriate Comments

Summary before program:


What the program does
Your name
Class Section
Instructor
Date
41

Naming Conventions
• Choose meaningful and descriptive
names.
• Variables and method names:
▫ Lowercase for first word
▫ Camelcase if several words
• Class names:
▫ Capitalize first letter of each word
• Constants:
▫ Capitalize all letters, use underscores to
connect words.
42

Block Styles
Chose next-line or end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
43

Programming Errors
• Syntax Errors
▫ Detected by the compiler
• Runtime Errors
▫ Causes the program to abort
• Logic Errors
▫ Produces incorrect result
44

Syntax Errors
public class ShowSyntaxErrors {
public static void main(String[] args) {
i = 30;
System.out.println(i + 4);
}
}
45

Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
int i = 1 / 0;
}
}
46
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.showInputDialog(null,
"Please enter an integer:",
"ShowLogicErrors", JOptionPane.QUESTION_MESSAGE);
int number = Integer.parseInt(input);

// Display the result


System.out.println("The number is between 1 and 100, " +
"inclusively? " + ((1 < number) && (number < 100)));

System.exit(0);
}
}
47
Debugging
Logic errors are called bugs.
Debugging: process of finding and correcting.

Narrow down segment of code where the bug


is located:
 hand-trace the program
 insert print statements to see what’s
happening
 debugger utility (part of IDE)
48
Debugger
A debugger can

•Execute a single statement at a time.


•Trace into or stepping over a method.
•Set breakpoints.
•Display variables.
•Display call stack.
•Modify variables.

You might also like