Download presentation
Presentation is loading. Please wait.
Published byHarjanti Jayadi Modified over 6 years ago
1
Java Methods /** * Chapter 5 */ Java Syntax and Style A & AB
Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin /** * Chapter 5 */ This is an important chapter because it explains and contrasts two related aspects of writing code in a high-level programming language: language syntax rules and good programming style. Java Syntax and Style Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
2
Objectives: Learn to distinguish the required Java syntax from the conventional style Learn when to use comments and how to mark them Review reserved words and standard names Learn the proper style for naming classes, methods, and variables Learn to space and indent blocks of code An unstated objective is to give students some appreciation for what is involved in creating working code and the required level of attention to detail.
3
Comments Comments are notes in plain English inserted in the source code. 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 How detailed should comments be? In general, self-documenting, clear code is better than obscure, heavily commented code. Use comments to mark important sections and occasionally explain unexpected twists of logic or use, but do not comment every statement. Sometimes you need to comment out a fragment of code to try a variation or to test the remaining code separately.
4
Formats for Comments A “block” comment is placed between /* and */ marks: A single-line comment goes from // to the end of the line: /* Exercise 5-2 for Java Methods Author: Miss Brace Date: 3/5/2010 Rev */ Make sure you do not carry a // comment over to the next line. If you do, you need another // mark on that line. Placing // at the beginning of a line comments out that line. Java does not allow nested /* */ comments: /* ... */ within /* ... */ does not work. Be careful when you use /* ... */ to comment out a fragment of code that itself contains a /* ... */ comment. weight *= ; // Convert to kilograms
5
Javadoc Comments Used by the JDK’s special utility program javadoc to automatically generate documentation in HTML format from the source code Should precede a class, a method, or a field Can use special javadoc tags: @param – describes a parameter of a method @return - describes the method’s return value javadoc.exe is in the JDK...\bin folder. To run javadoc from the command line, set path to include the ...\bin folder and enter: C> javadoc MyFile1.java MyFile2.java ... Enter C> javadoc ? to see the list of all the options and the general command syntax.
6
Javadoc Comments (cont’d)
/** indicates a javadoc comment /** * Returns total sales from all vendors; * sets <code>totalSales</code> * to 0. * * @return total amount of sales from all vendors */ Can use HTML tags As far as a Java compiler is concerned, a documentation comment is simply a special case of a /* ... */ comment. All the documentation of Java library packages is generated using javadoc. This forced the authors to worry about the documentation while they were working on the code (or even before they started writing the code). Embedded HTML tags make the resulting documentation look better. <code> is the most commonly used tag. javadoc also has tag that generates hyperlinks automatically. Common style
7
Reserved Words In Java a number of words are reserved for a special purpose. Reserved words use only lowercase letters. 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. See Java Methods A & AB, p. 107. Note that the same words with a capital letter or in all caps are not reserved, but it is not a good idea to use them in programs anyway.
8
Programmer-Defined Names
In addition to reserved words, Java uses standard names for library packages and classes: String, Graphics, JFrame, JButton, java.awt, javax.swing The programmer gives names to his or her classes, methods, fields, and variables. Programmers often give the same name to methods in different classes or use the names of library methods, if they perform similar tasks. One must be careful, though, not to inadvertently override in a subclass a name of a method from the superclass.
9
Names (cont’d) Syntax: A name can include:
upper- and lowercase letters digits underscore characters Syntax: A name cannot begin with a digit. Style: Names should be descriptive to improve readability. Underscore in names is not common in Java. Names can also contain $, but this is not common either. Names should be descriptive but not too long. Very long names can be hard to read and may get annoying.
10
Names (cont’d) Programmers follow strict style conventions.
Style: names of classes begin with an uppercase letter, subsequent words are capitalized: public class DanceFloor Style: names of methods, fields, and variables begin with a lowercase letter, subsequent words are capitalized: private int stepsCount = 0; public void nextStep() If you do not follow conventional style, you look like a dunce. Remember that your product is the source code, not the executable program.
11
Names (cont’d) Method names often sound like verbs:
setBackground, getText, moveForward, stop Field names often sound like nouns: foot, picture, button, controlPanel Constants often use all caps: PI, PIXELS_PER_INCH It is OK to use standard short names for temporary “throwaway” variables: i, k, x, y, str Class fields should have prominent names: i or x won’t do. Boolean methods (discussed in Chapter 7) often start with “is” or “has” (for example, boolean isEmpty()).
12
Syntax vs. Style Syntax is part of the language. The compiler checks it. Style is a convention widely adopted by software professionals. The main purpose of style is to improve the readability of programs. Syntax is needed to avoid any possible ambiguity. The beginner may find it difficult to get used to. Just be very careful.
13
Syntax The compiler catches syntax errors and generates error messages. 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. Reading and checking your code before compiling saves you a lot of time. Some errors look like acceptable syntax to the compiler, so they pass syntax checks. The compiler cannot follow your intentions; it is pretty dumb.
14
Syntax (cont’d) Pay attention to and check for:
matching braces { }, parentheses ( ), and brackets [ ] missing or extraneous semicolons correct symbols for operators +, -, =, <, <=, ==, ++, &&, etc. correct spelling of reserved words, library names and programmer-defined names, including upper/lower case For example, & is also an operator in Java, but it is different from &&.
15
Syntax (cont’d) Common syntax errors: Public static int abs (int x)
{ If (x < 0); x = -x } return x; public static int sqrt (int x) ... Spelling (p P, if If) Extraneous semicolon Extraneous semicolons are especially bad: they are not detected but can break your code. Even experienced programmers occasionally have one. Missing closing brace Missing semicolon
16
Style Arrange statements on separate lines
Insert blank lines between fragments of code. Indent code within braces. Use comments judiciously: comment constructors, methods, fields, important steps, but not every statement in the program. Always assume that others will look at your code. Make it look good.
17
Style (cont’d) A little more readable Compiles fine
public void nextStep() { if (stepsCount % 2 == 0) leftFoot. moveForward (2 * stepLength); else rightFoot. moveForward(2 * stepLength); stepsCount++; } public void nextStep() { if (stepsCount % 2 == 0) leftFoot.moveForward (2 * stepLength); else rightFoot.moveForward (2 * stepLength); stepsCount++; } Style is for humans; the compiler doesn’t care. For a compiler, one space looks the same as 100 spaces or tabs. The compiler requires spaces only to separate variable names and constants. Compiles fine A little more readable
18
Style (cont’d) public void fill (char ch) {
int rows = grid.length, cols = grid[0].length; for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) grid[r][c] = ch; } Add blank lines for readability Some people get too fancy, adding spaces around all ( ) and [ ] and even around dots. This is a matter of taste but not common style. Math . PI compiles but it is surely not conventional (just Math.PI is better). Add spaces around operators and after semicolons
19
Blocks, Indentation Java code consists mainly of declarations and control statements. Declarations describe objects and methods. Control statement describe actions. Declarations and control statements end with a semicolon. No semicolon is used after a closing brace (except in certain array declarations). Individual elements in a declaration are separated by commas: int x, y, z;
20
Blocks, Indentation (cont’d)
Braces mark nested blocks. Braces indicate that the statements within them form one compound statement. Statements inside a block are indented, usually by two spaces or one tab. There are two common styles for braces: if (...) { ... } and if (...) { Each has minor advantages and disadvantages, but basically it is a matter of habit. Once you are used to one style, the other looks ugly. But one can adjust.
21
Method’s body public void makeNextStep ( ) { One compound statement
if (currentState == State.READY) amy.firstStep(); ben.firstStep(); currentState = State.MOVING; stepsCount = 0; } else if (currentState == State.MOVING) if (amy.distanceTraveled() <= danceFloor.getWidth() * 3 / 4) amy.nextStep(); ben.nextStep(); stepsCount++; else amy.stop(); ben.stop(); currentState = State.STOPPED; danceFloor.update(this); Method’s body One compound statement One compound statement One compound statement Indenting each level by two spaces is customary in Java. Your IDE lets you set the tab to a specified number of spaces. Many editors and IDEs support the auto-indent feature: they start indenting automatically after an opening brace. One compound statement
22
Review: Name as many uses of comments as you can.
What does the javadoc program do? Explain the difference between syntax and style. Why is style important? Roughly how many reserved words does Java have? Name as many uses of comments as you can. (1) document the program purpose, authors, copyright, revisions; (2) explain obscure logic or usage; (3) temporarily comment out fragments of code. What does the javadoc program do? Automatically generates HTML documentation from “documentation” comments in the source code. Explain the difference between syntax and style. Syntax is required by the language and it is checked by the compiler; style is a convention among programmers. Why is style important? It makes programs easier to read and understand for your colleagues (and for you yourself). Roughly how many reserved words does Java have? 50
23
Review (cont’d): Explain the convention for naming classes, methods, and variables. Which of the following are syntactically valid names for variables: C, _denom_, my.num, AvgScore, count1, 7seas? Which of them are in good style? What can happen if you put an extra semicolon in your program? Explain the convention for naming classes, methods and variables. Class names start with a capital letter. Method and variables names start with a lowercase letter. Subsequent words are capitalized. Method names often sound like verbs, class and variable names like nouns. Which of the following are syntactically valid names for variables: C, _denom_, my.num, AvgScore, count1, 7seas? Which of them are in good style? All are valid except my.num and 7seas Only count1 is in good style. What can happen if you put an extra semicolon in your program? Depending where it is, it may either be caught by the compiler as a syntax error or not. If it isn’t caught, it may be harmless or it could cause a logical error that will break your program.
24
Review (cont’d): What are braces used for in Java?
Is indentation required by Java syntax or style? What are braces used for in Java? To mark the code of methods and to group several statements into one compound statement. Is indentation required by Java syntax or style? Style. But it is essential for readability and helps avoid syntax errors.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.