Download presentation
Presentation is loading. Please wait.
Published byAnna Merritt Modified over 9 years ago
1
1 CS1001 Lecture 13
2
2 Overview Java Programming Java Programming
3
3 Goals Understand the basics of Java programming Understand the basics of Java programming
4
4 Assignments Brookshear: Ch 4, Ch 5 (Read) Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these slides (slides will be posted in courseworks) Read linked documents on these slides (slides will be posted in courseworks)
5
5 Objectives: Learn to distinguish the required syntax from the conventional style Learn to distinguish the required syntax from the conventional style Learn when to use comments and how to mark them Learn when to use comments and how to mark them Review reserved words and standard names Review reserved words and standard names Learn the proper style for naming classes, methods, and variables Learn the proper style for naming classes, methods, and variables Learn to space and indent blocks of code Learn to space and indent blocks of code
6
6 Comments Comments are notes in plain English inserted in the source code. Comments are notes in plain English inserted in the source code. Comments are used to: Comments are used to: –document the program’s purpose, author, revision history, copyright notices, etc. –describe fields, constructors, and methods –explain obscure or unusual places in the code –temporarily “comment out” fragments of code
7
7 Formats for Comments A “block” comment is placed between /* and */ marks: A “block” comment is placed between /* and */ marks: /* Exercise 5-2 for Java Methods Author: Miss Brace Author: Miss Brace Date: 3/5/2010 Date: 3/5/2010 Rev. 1.0 */ Rev. 1.0 */ A single-line comment goes from // to the end of the line: A single-line comment goes from // to the end of the line: wt * = 2.2046; // Convert to kilograms
8
8 Reserved Words In Java a number of words are reserved for a special purpose. In Java a number of words are reserved for a special purpose. Reserved words use only lowercase letters. Reserved words use only lowercase letters. Reserved words include: Reserved words include: –primitive data types: int, double, char, boolean, etc. –storage modifiers: public, private, static, final, etc. –control statements: if, else, switch, while, for, etc. –built-in constants: true, false, null There are about 50 reserved words total. There are about 50 reserved words total.
9
9 Programmer-Defined Names In addition to reserved words, Java uses standard names for library packages and classes: In addition to reserved words, Java uses standard names for library packages and classes: String, Graphics, javax.swing, JApplet, JButton, ActionListener, java.awt The programmer gives names to his or her classes, methods, fields, and variables. The programmer gives names to his or her classes, methods, fields, and variables.
10
10 Names (cont’d) Syntax: A name can include: Syntax: A name can include: –upper- and lowercase letters –digits –underscore characters Syntax: A name cannot begin with a digit. Syntax: A name cannot begin with a digit. Style: Names should be descriptive to improve readability. Style: Names should be descriptive to improve readability.
11
11 Names (cont’d) Programmers follow strict style conventions. Programmers follow strict style conventions. Style: Names of classes begin with an uppercase letter, subsequent words are capitalized: Style: Names of classes begin with an uppercase letter, subsequent words are capitalized: public class FallingCube Style: Names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized. Style: Names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized. private final int delay = 30; public void dropCube()
12
12 Names (cont’d) Method names often sound like verbs: Method names often sound like verbs: setBackground, getText, dropCube, start Field names often sound like nouns: Field names often sound like nouns: cube, delay, button, whiteboard Constants sometimes use all caps: Constants sometimes use all caps: PI, CUBESIZE It is OK to use standard short names for temporary “throwaway” variables: It is OK to use standard short names for temporary “throwaway” variables: i, k, x, y, str
13
13 Syntax vs. Style Syntax is part of the language. The compiler checks it. Syntax is part of the language. The compiler checks it. Style is a convention widely adopted by software professionals. Style is a convention widely adopted by software professionals. The main purpose of style is to improve the readability of programs. The main purpose of style is to improve the readability of programs.
14
14 Syntax The compiler catches syntax errors and generates error messages. The compiler catches syntax errors and generates error messages. Text in comments and literal strings within double quotes are excluded from syntax checking. Text in comments and literal strings within double quotes are excluded from syntax checking. Before compiling, carefully read your code a couple of times to check for syntax and logic errors. Before compiling, carefully read your code a couple of times to check for syntax and logic errors.
15
15 Syntax (cont’d) Pay attention to and check for: Pay attention to and check for: –matching braces { }, parentheses ( ), and brackets [ ] –missing and extraneous semicolons –correct symbols for operators +, -, =, <, <=, ==, ++, &&, etc. –correct spelling of reserved words, library names and programmer-defined names, including case
16
16 Syntax (cont’d) Common syntax errors: Common syntax errors: Missing closing brace Public static int abs (int x) { If (x < 0); { x = - x } return x; public static int sign (int x)... Extraneous semicolon Spelling (p P, if If) Missing semicolon
17
17 Style Arrange code on separate lines; insert blank lines between fragments of code. Arrange code on separate lines; insert blank lines between fragments of code. Use comments. Use comments. Indent blocks within braces. Indent blocks within braces.
18
18 Style (cont’d) public boolean moveDown(){if (cubeY<6*cubeX) {cubeY+=yStep; return true;}else return false;} public boolean moveDown() { if (cubeY < 6 * cubeX) { cubeY += yStep; return true; } else { return false; } Before:After: Compiles fine!
19
19 Style (cont’d) public void fill (char ch) { int rows = grid.length, cols = grid[0].length; int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; } Add blank lines for readability Add spaces around operators and after semicolons
20
20 Blocks, Indentation Java code consists mainly of declarations and control statements. Java code consists mainly of declarations and control statements. Declarations describe objects and methods. Declarations describe objects and methods. Control statement describe actions. Control statement describe actions. Declarations and control statements end with a semicolon. Declarations and control statements end with a semicolon. No semicolon is used after a closing brace (except certain array declarations). No semicolon is used after a closing brace (except certain array declarations).
21
21 Braces divide code into nested blocks. Braces divide code into nested blocks. A block in braces indicates a number of statements that form one compound statement. A block in braces indicates a number of statements that form one compound statement. Statements inside a block are indented, usually by two spaces or one tab. Statements inside a block are indented, usually by two spaces or one tab. Blocks, Indentation (cont’d)
22
22 Blocks, Indentation (cont’d) public void fill (char ch) { int rows = grid.length, cols = grid[0].length; int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < cols; c++) { grid[r][c] = ch; }
23
23 Review: Name as many uses of comments as you can. Name as many uses of comments as you can. Explain the difference between syntax and style. Explain the difference between syntax and style. Why is style important? Why is style important? Roughly how many reserved words does Java have? Roughly how many reserved words does Java have?
24
24 Review (cont’d): Explain the convention for naming classes, methods and variables. Explain the convention for naming classes, methods and variables. Which of the following are syntactically valid names for variables: C, _denom_, my. num, AvgScore? Which of them are in good style? Which of the following are syntactically valid names for variables: C, _denom_, my. num, AvgScore? Which of them are in good style? What can happen if you put an extra semicolon in your program? What can happen if you put an extra semicolon in your program? What are braces used for in Java? What are braces used for in Java? Is indentation required by Java syntax or style? Is indentation required by Java syntax or style?
25
25 Objectives: Review primitive data types Review primitive data types Learn how to declare fields and local variables Learn how to declare fields and local variables Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Learn about arithmetic operators, compound assignment operators, and increment / decrement operators Learn how to avoid common mistakes in arithmetic Learn how to avoid common mistakes in arithmetic
26
26 Variables A variable is a “named container” that holds a value. A variable is a “named container” that holds a value. q = 100 - q; q = 100 - q;means: 1. Read the current value of q 2. Subtract it from 100 3. Move the result back into q count 5 mov ax,q mov bx,100 sub bx,ax mov q,bx
27
27 Variables (cont’d) Variables can be of different data types: int, char, double, boolean, etc. Variables can be of different data types: int, char, double, boolean, etc. Variables can hold objects; then the type is the class of the object. Variables can hold objects; then the type is the class of the object. The programmer gives names to variables. The programmer gives names to variables. Names usually start with a lowercase letter. Names usually start with a lowercase letter.
28
28 Variables (cont’d) A variable must be declared before it can be used: A variable must be declared before it can be used: int count; double x, y; JButton go; FallingCube cube; String firstName; Declarations Type Name(s)
29
29 Variables (cont’d) The assignment operator = sets the variable’s value: The assignment operator = sets the variable’s value: A variable can be initialized in its declaration: A variable can be initialized in its declaration: count = 5; x = 0; go = new JButton("Go"); firstName = args[0]; Assignments int count = 5; JButton go = new JButton("Go"); String firstName = args[0]; Declarations with initialization
30
30 Variables (cont’d) Each variable has a scope — the area in the source code where it is “visible.” Each variable has a scope — the area in the source code where it is “visible.” If you use a variable outside its scope, the compiler reports a syntax error. If you use a variable outside its scope, the compiler reports a syntax error. Variables can have the same name. Caution: use only when their scopes do not intersect. Variables can have the same name. Caution: use only when their scopes do not intersect. { int k;... } { int k;... }
31
31 Fields vs. Local Variables Fields are declared outside all constructors and methods. Fields are declared outside all constructors and methods. Local variables are declared inside a constructor or a method. Local variables are declared inside a constructor or a method.
32
32 Fields vs. Local Variables (cont’d) Fields vs. Local Variables (cont’d) Fields are usually grouped together, either at the top or at the bottom of the class. Fields are usually grouped together, either at the top or at the bottom of the class. The scope of a field is the whole class. The scope of a field is the whole class.
33
33 Fields public class SomeClass { } Fields Constructors and methods public class SomeClass { } Scope Fields Constructors and methods
34
34 Variables (cont’d) Common mistakes: Common mistakes: public void SomeMethod (...) { int x;... int x = 5; // should be: x = 5;... Variable declared twice — syntax error
35
35 Primitive Data Types int int double double char char boolean boolean byte byte short short long long float float Used in Java Methods
36
36 Constants 'A', '+', '\n', '\t' // char - 99, 2010, 0 // int 0.75, - 12.3, 8.,.5 // double new line tab
37
37 Constants (cont’d) private final int delay = 30; private final double aspectRatio = 0.7; Symbolic constants are initialized final variables: Symbolic constants are initialized final variables:
38
38 Constants (cont’d) Why use symbolic constants? Why use symbolic constants? –easier to change the value throughout, if necessary –easy to change into a variable –more readable, self-documenting code –additional data type checking
39
39 Arithmetic Operators: +, -, /, *, % Operators: +, -, /, *, % The precedence of operators and parentheses work the same way as in algebra. The precedence of operators and parentheses work the same way as in algebra. m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). m % n means the remainder when m is divided by n (e.g. 17 % 5 is 2). % has the same rank as / and * % has the same rank as / and * Same-rank binary operators are performed in order from left to right. Same-rank binary operators are performed in order from left to right.
40
40 Arithmetic (cont’d) The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int. If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.
41
41 Arithmetic (cont’d) Caution: if a and b are ints, then a / b is truncated to an int… Caution: if a and b are ints, then a / b is truncated to an int… 17 / 5 gives 3 3 / 4 gives 0 3 / 4 gives 0 …even if you assign the result to a double: …even if you assign the result to a double: double ratio = 2 / 3; double ratio = 2 / 3; The double type of the result doesn’t help: ratio still gets the value 0.0.
42
42 Arithmetic (cont’d) To get the correct double result, use double constants or the cast operator: To get the correct double result, use double constants or the cast operator: double ratio = 2.0 / 3; double ratio = 2.0 / 3; double ratio = 2 / 3.0; double ratio = 2 / 3.0; double factor = (double) m / (double) n; double factor = (double) m / (double) n; double factor = m / (double) n; double factor = m / (double) n; double r2 = k / 2.0; double r2 = k / 2.0; double r2 = (double) k / 2; double r2 = (double) k / 2; Casts
43
43 Arithmetic (cont’d) Caution: the range for ints is from - 2 31 to 2 31 - 1 (about - 2·10 9 to 2·10 9 ) Caution: the range for ints is from - 2 31 to 2 31 - 1 (about - 2·10 9 to 2·10 9 ) Overflow is not detected by the Java compiler or interpreter Overflow is not detected by the Java compiler or interpreter n = 8 10^n = 100000000 n! = 40320 n = 9 10^n = 1000000000 n! = 362880 n = 10 10^n = 1410065408 n! = 3628800 n = 11 10^n = 1215752192 n! = 39916800 n = 12 10^n = -727379968 n! = 479001600 n = 13 10^n = 1316134912 n! = 1932053504 n = 14 10^n = 276447232 n! = 1278945280
44
44 Arithmetic (cont’d) Use compound assignment operators: Use compound assignment operators: a = a + b; a += b; a = a - b; a -= b; a = a * b; a *= b; a = a / b; a /= b; a = a % b; a % = b; Use increment and decrement operators: Use increment and decrement operators: a = a + 1; a ++ ; a = a - 1; a -- ; Do not use these in larger expressions
45
45 Review: What is a variable? What is a variable? What is the type of variable that holds an object? What is the type of variable that holds an object?
46
46 Review (cont’d): What is the range for ints? What is the range for ints? When is a cast to double used? When is a cast to double used? Given Given double dF = 68.0; double dC = 5 / 9 * (dF - 32); what is the value of dC? When is a cast to int used? When is a cast to int used? Should compound assignment operators be avoided? Should compound assignment operators be avoided?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.