1 CS1001 Lecture 13. 2 Overview Java Programming Java Programming.
-
Upload
anna-merritt -
Category
Documents
-
view
237 -
download
1
Transcript of 1 CS1001 Lecture 13. 2 Overview Java Programming Java Programming.
11
CS1001CS1001
Lecture 13Lecture 13
22
OverviewOverview
Java ProgrammingJava Programming
33
GoalsGoals
Understand the basics of Java Understand the basics of Java programmingprogramming
44
AssignmentsAssignments
Brookshear: Ch 4, Ch 5 (Read)Brookshear: Ch 4, Ch 5 (Read) Read linked documents on these Read linked documents on these
slides (slides will be posted in slides (slides will be posted in courseworks)courseworks)
55
Objectives:Objectives: Learn to distinguish the required syntax from Learn to distinguish the required syntax from
the conventional stylethe conventional style
Learn when to use comments and how to mark Learn when to use comments and how to mark themthem
Review reserved words and standard namesReview reserved words and standard names
Learn the proper style for naming classes, Learn the proper style for naming classes, methods, and variablesmethods, and variables
Learn to space and indent blocks of codeLearn to space and indent blocks of code
66
CommentsComments
Comments are notes in plain English Comments are notes in plain English inserted in the source code.inserted in the source code.
Comments are used to:Comments are used to:– document the program’s purpose, author, document the program’s purpose, author,
revision history, copyright notices, etc.revision history, copyright notices, etc.– describe fields, constructors, and methodsdescribe fields, constructors, and methods– explain obscure or unusual places in the codeexplain obscure or unusual places in the code– temporarily “comment out” fragments of codetemporarily “comment out” fragments of code
77
Formats for CommentsFormats for Comments A “block” comment is placed between A “block” comment is placed between /*/*
and and */*/ marks: marks:/*/* Exercise 5-2 for Java Methods Exercise 5-2 for Java Methods Author: Miss BraceAuthor: Miss Brace Date: 3/5/2010Date: 3/5/2010 Rev. 1.0 Rev. 1.0 */*/
A single-line comment goes from A single-line comment goes from //// to to the end of the line:the end of the line:wt wt **= 2.2046; = 2.2046; //// Convert to kilograms Convert to kilograms
88
Reserved WordsReserved Words In Java a number of words are reserved for a In Java a number of words are reserved for a
special purpose.special purpose.
Reserved words use only lowercase letters.Reserved words use only lowercase letters.
Reserved words include:Reserved words include:– primitive data types: primitive data types: intint, , doubledouble, , charchar, , booleanboolean, etc., etc.– storage modifiers: storage modifiers: publicpublic, , privateprivate, , staticstatic, , finalfinal, etc., etc.– control statements: control statements: ifif, , elseelse, , switchswitch, , whilewhile, , forfor, etc., etc.– built-in constants: built-in constants: truetrue, , falsefalse, , nullnull
There are about 50 reserved words total. There are about 50 reserved words total.
99
Programmer-Defined Programmer-Defined NamesNames In addition to reserved words, In addition to reserved words,
Java uses standard names for Java uses standard names for library packages and classes:library packages and classes:StringString, , GraphicsGraphics, , javax.swingjavax.swing, , JAppletJApplet,,JButtonJButton, , ActionListenerActionListener, , java.awtjava.awt
The programmer gives names to The programmer gives names to his or her classes, methods, his or her classes, methods, fields, and variables.fields, and variables.
1010
Names (cont’d)Names (cont’d) Syntax: A name can include: Syntax: A name can include:
– upper- and lowercase lettersupper- and lowercase letters– digitsdigits– underscore charactersunderscore characters
Syntax: A name cannot begin with a Syntax: A name cannot begin with a digit.digit.
Style: Names should be descriptive Style: Names should be descriptive toto improve improve readabilityreadability..
1111
Names (cont’d)Names (cont’d) Programmers follow strict style conventions.Programmers follow strict style conventions.
Style: Names of classes begin with an Style: Names of classes begin with an uppercaseuppercase letter, subsequent words are letter, subsequent words are capitalized:capitalized:public class public class FallingCubeFallingCube
Style: Names of methods, fields, and Style: Names of methods, fields, and variables begin with a lowercase letter, variables begin with a lowercase letter, subsequent words are capitalized.subsequent words are capitalized.
private final int private final int delaydelay = 30; = 30;public void public void dropCubedropCube()()
1212
Names (cont’d)Names (cont’d) Method names often sound like verbs:Method names often sound like verbs:
setBackgroundsetBackground, , getTextgetText, , dropCubedropCube, , startstart
Field names often sound like nouns:Field names often sound like nouns:cubecube, , delaydelay, , buttonbutton, , whiteboardwhiteboard
Constants sometimes use all caps:Constants sometimes use all caps:PIPI, , CUBESIZECUBESIZE
It is OK to use standard short names It is OK to use standard short names for temporary “throwaway” variables:for temporary “throwaway” variables:ii, , kk, , xx, , yy, , strstr
1313
Syntax vs. StyleSyntax vs. Style
SyntaxSyntax is part of the language. The is part of the language. The compiler checks it.compiler checks it.
StyleStyle is a convention widely adopted is a convention widely adopted by software professionals.by software professionals.
The main purpose of style is to The main purpose of style is to improve the improve the readability of readability of programsprograms..
1414
SyntaxSyntax
The compiler catches syntax errors and The compiler catches syntax errors and generates error messages.generates error messages.
Text in comments and literal strings Text in comments and literal strings within double quotes are excluded from within double quotes are excluded from syntax checking.syntax checking.
Before compiling, carefully read your Before compiling, carefully read your code a couple of times to check for code a couple of times to check for syntax and logic errors.syntax and logic errors.
1515
Syntax (cont’d)Syntax (cont’d)
Pay attention to and check for:Pay attention to and check for:– matching braces matching braces { }{ }, parentheses , parentheses ( )( ), and , and
brackets brackets [ ][ ]– missing and extraneous semicolonsmissing and extraneous semicolons– correct symbols for operatorscorrect symbols for operators
++, , --, , ==, , <<, , <=<=, , ====, , ++++, , &&&&, etc., etc.
– correct spelling of reserved words, library correct spelling of reserved words, library names and programmer-defined names, names and programmer-defined names, including caseincluding case
1616
Syntax (cont’d)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
1717
StyleStyle
Arrange code on separate lines; Arrange code on separate lines; insert blank lines between insert blank lines between fragments of code.fragments of code.
Use comments.Use comments.
Indent blocks within braces.Indent blocks within braces.
1818
Style (cont’d)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!
1919
Style (cont’d)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
2020
Blocks, IndentationBlocks, Indentation Java code consists mainly of declarations Java code consists mainly of declarations
and control statements.and control statements.
Declarations describe objects and Declarations describe objects and methods.methods.
Control statement describe actions.Control statement describe actions.
Declarations and control statements end Declarations and control statements end with a semicolon.with a semicolon.
No semicolon is used after a closing No semicolon is used after a closing brace (except certain array declarations).brace (except certain array declarations).
2121
Braces divide code into nested blocks.Braces divide code into nested blocks.
A block in braces indicates a number of A block in braces indicates a number of statements that form one statements that form one compoundcompound statement.statement.
Statements inside a block are indented, Statements inside a block are indented, usually by two spaces or one tab.usually by two spaces or one tab.
Blocks, Indentation Blocks, Indentation (cont’d)(cont’d)
2222
Blocks, Indentation Blocks, Indentation (cont’d)(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; } } }
2323
Review:Review: Name as many uses of comments as Name as many uses of comments as
you can.you can. Explain the difference between syntax Explain the difference between syntax
and style.and style. Why is style important?Why is style important? Roughly how many reserved words does Roughly how many reserved words does
Java have?Java have?
2424
Review (cont’d):Review (cont’d): Explain the convention for naming classes, Explain the convention for naming classes,
methods and variables.methods and variables. Which of the following are syntactically valid Which of the following are syntactically valid
names for variables: names for variables: CC, , _denom__denom_, , mymy..numnum, , AvgScoreAvgScore? Which of them are in good style?? Which of them are in good style?
What can happen if you put an extra What can happen if you put an extra semicolon in your program?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 Is indentation required by Java syntax or
style?style?
2525
Objectives:Objectives: Review primitive data typesReview primitive data types
Learn how to declare fields and local Learn how to declare fields and local variablesvariables
Learn about arithmetic operators, Learn about arithmetic operators, compound assignment operators, and compound assignment operators, and increment / decrement operatorsincrement / decrement operators
Learn how to avoid common mistakes in Learn how to avoid common mistakes in arithmeticarithmetic
2626
VariablesVariables A variable is a “named container” A variable is a “named container”
that holds a value. that holds a value.
q = 100 q = 100 -- q; q;
means:means:
1. Read the current value of 1. Read the current value of qq
2. Subtract it from 1002. Subtract it from 100
3. Move the result back into 3. Move the result back into qq
count
5
mov ax,qmov bx,100sub bx,axmov q,bx
2727
Variables (cont’d)Variables (cont’d)
Variables can be of different data types: Variables can be of different data types: intint, , charchar, , doubledouble, , booleanboolean, etc., etc.
Variables can hold objects; then the type is Variables can hold objects; then the type is the classthe class of the object. of the object.
The programmer gives names to variables.The programmer gives names to variables.
Names usually start with a lowercase Names usually start with a lowercase letter.letter.
2828
Variables (cont’d)Variables (cont’d) A variable must be declared before it A variable must be declared before it
can be used:can be used: int count;
double x, y;
JButton go;
FallingCube cube;
String firstName;
Declarations
Type
Name(s)
2929
Variables (cont’d)Variables (cont’d) The assignment operator The assignment operator == sets the variable’s sets the variable’s
value: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
3030
Variables (cont’d)Variables (cont’d) Each variable has a Each variable has a scopescope — the area — the area
in the in the source codesource code where it is where it is “visible.”“visible.”
If you use a variable outside If you use a variable outside its scope, the compiler its scope, the compiler reports a syntax error. reports a syntax error.
Variables Variables cancan have the same have the same name. name. Caution:Caution: use only when use only when their scopes do not intersect. their scopes do not intersect.
{ int k; ...}
{ int k; ...}
3131
Fields vs. Local Fields vs. Local Variables Variables Fields are declared Fields are declared outsideoutside all all
constructors and methods.constructors and methods.
Local variables are declared Local variables are declared insideinside a constructor or a method.a constructor or a method.
3232
Fields vs. Local Fields vs. Local Variables (cont’d)Variables (cont’d) Fields are usually grouped Fields are usually grouped
together, either at the top or at together, either at the top or at the bottom of the class.the bottom of the class.
The scope of a field is The scope of a field is the whole the whole class.class.
3333
FieldsFieldspublic class SomeClass{
}
Fields
Constructors and methods
public class SomeClass{
}
Scope
Scope
Fields
Constructors and methods
3434
Variables (cont’d)Variables (cont’d)
Common mistakes:Common mistakes:
public void SomeMethod (...){ int x; ... int x = 5; // should be: x = 5; ...
Variable declared twice — syntax error
3535
Primitive Data TypesPrimitive Data Types
intint doubledouble charchar booleanboolean
bytebyte shortshort longlong floatfloat
Used inJava Methods
3636
ConstantsConstants
'A', '+', '\n', '\t' // char
-99, 2010, 0 // int
0.75, -12.3, 8., .5 // double
new line
tab
3737
Constants (cont’d)Constants (cont’d)
private final int delay = 30;
private final double aspectRatio = 0.7;
Symbolic constants are initialized Symbolic constants are initialized finalfinal variables: variables:
3838
Constants (cont’d)Constants (cont’d)
Why use symbolic constants?Why use symbolic constants?
– easier to change the value easier to change the value throughout, if necessarythroughout, if necessary
– easy to change into a variableeasy to change into a variable– more readable, self-documenting more readable, self-documenting
codecode– additional data type checkingadditional data type checking
3939
ArithmeticArithmetic Operators: Operators: ++, , --, , //, , ** , , %%
The precedence of operators and The precedence of operators and parentheses work the same way as in parentheses work the same way as in algebra.algebra.
m % nm % n means the remainder when means the remainder when mm is divided by is divided by nn (e.g. 17 % 5 is 2). (e.g. 17 % 5 is 2).
%% has the same rank as has the same rank as // and and **
Same-rank binary operators are Same-rank binary operators are performed in order from left to right.performed in order from left to right.
4040
Arithmetic (cont’d)Arithmetic (cont’d)
The type of the result is determined by The type of the result is determined by the the typestypes of the operands, not their of the operands, not their values; this rule applies to values; this rule applies to all all intermediate resultsintermediate results in expressions. in expressions.
If one operand is an If one operand is an intint and another is a and another is a doubledouble, the result is a , the result is a doubledouble; if both ; if both operands are operands are intints, the result is an s, the result is an intint..
4141
Arithmetic (cont’d)Arithmetic (cont’d)
Caution:Caution: if if aa and and bb are are intints, then s, then a a // b b is is truncatedtruncated to an to an intint……
1717 // 5 gives 5 gives 33 33 // 4 gives 4 gives 00
……even if you assign the result to a even if you assign the result to a doubledouble::
double ratio = 2double ratio = 2 // 3; 3;The double type of the result doesn’t help: ratio still gets the value 0.0.
4242
Arithmetic (cont’d)Arithmetic (cont’d) To get the correct To get the correct doubledouble result, use result, use doubledouble
constants or the constants or the castcast operator: operator:
double ratio = double ratio = 2.02.0 // 3; 3;
double ratio = 2double ratio = 2 // 3.03.0;;
double factor = double factor = (double)(double) m m // (double)(double) n; n;
double factor = mdouble factor = m // (double)(double) n; n;
double r2 = kdouble r2 = k // 2.02.0;;
double r2 = double r2 = (double)(double) k / 2; k / 2;Casts
4343
Arithmetic (cont’d)Arithmetic (cont’d) Caution: Caution: the range for the range for intints is from s is from
--223131 to 2 to 23131--1 (about 1 (about --2·102·1099 to to 2·102·1099))
Overflow is Overflow is notnot detected by the Java detected by the Java compiler or interpretercompiler or interpretern = 8 10^n = 100000000 n! = 40320n = 9 10^n = 1000000000 n! = 362880n = 10 10^n = 1410065408 n! = 3628800n = 11 10^n = 1215752192 n! = 39916800n = 12 10^n = -727379968 n! = 479001600n = 13 10^n = 1316134912 n! = 1932053504n = 14 10^n = 276447232 n! = 1278945280
4444
Arithmetic (cont’d)Arithmetic (cont’d)
Use compound Use compound assignment assignment operators:operators:
a a == a a ++ b; b; a a +=+= b; b;
a a == a a -- b; b; a a -=-= b; b;
a a == a a ** b; b; a a *=*= b; b;
a a == a a // b; b; a a /=/= b; b;
a a == a a %% b; b; a a %%== b; b;
Use increment Use increment and decrement and decrement operators:operators:
a a == a a ++ 1; 1; a a++++;;
a a == a a -- 1; 1; a a----;;
Do not use these in larger expressions
4545
Review:Review: What is a variable? What is a variable? What is the type of variable that holds What is the type of variable that holds
an object?an object?
4646
Review (cont’d):Review (cont’d): What is the range for What is the range for intints?s? When is a cast to When is a cast to doubledouble used? used? GivenGiven
double dF = 68.0;double dF = 68.0;double dC = 5 double dC = 5 / / 9 9 ** (dF (dF -- 32); 32);
what is the value of what is the value of dCdC?? When is a cast to When is a cast to intint used? used? Should compound assignment Should compound assignment
operators be avoided?operators be avoided?