Sie sind auf Seite 1von 24

Java Methods

Object-Oriented Programming
and Data Structures
2nd AP edition with GridWorld

Maria Litvin Gary Litvin

/**
* Chapter 5
*/
Java Syntax and Style

Copyright 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved.
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

5-2
Comments
Comments are notes in plain English inserted
in the source code.
Comments are used to:
document the programs 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

5-3
Formats for Comments
A block comment is placed between /* and
*/ marks:
/* Exercise 5-2 for Java Methods
Author: Miss Brace
Date: 3/5/2015
Rev. 1.0 */

A single-line comment goes from // to the end


of the line:
weight *= 2.2046; // Convert to kilograms

5-4
Javadoc Comments
Used by the JDKs 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 methods return value

5-5
Javadoc Comments (contd)
/** indicates a javadoc
comment

/**
* Returns total sales from all vendors;
* sets <code>totalSales</code> Can use
* to 0. HTML tags
*
* @return total amount of sales from all vendors
*/

Common
style

5-6
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.
5-7
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.

5-8
Names (contd)
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.

5-9
Names (contd)
Programmers follow strict style conventions.
Style: names of classes begin with an
uppercase letter, subsequent words are
capitalized:
public class ActorWorld
Style: names of methods, fields, and
variables begin with a lowercase letter,
subsequent words are capitalized:
private int sideLength;
public void moveTo()

5-10
Names (contd)
Method names often sound like verbs:
setBackground, getText, moveForward, stop
Field names often sound like nouns:
color, steps, button, controlPanel
Constants often use all caps:
PI, PIXELS_PER_INCH
It is OK to use short names for temporary
throwaway variables:
i, k, x, y, str

5-11
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.

5-12
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.

5-13
Syntax (contd)
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

5-14
Syntax (contd)
Common syntax errors:

Public static int abs (int x)


Spelling
{
(p P,
If (x < 0);
if If)
{
Extraneous
x = -x
semicolon
}
Missing return x; Missing
closing semicolon
brace public static int sqrt (int x)
...
5-15
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.

5-16
Style (contd)
public void act()
{
public void act() if (steps < sideLength &&
{if(steps< canMove())
sideLength&& {
canMove()){move(); move();
steps++;}else{ steps++;
turn();turn(); }
steps=0;}} else
{
turn();
Compiles fine turn();
steps = 0;
}
}

A little more readable


5-17
Style (contd)
public void fill (char ch)
{
int rows = grid.length, cols = grid[0].length;
Add blank lines for
for (int r = 0; r < rows; r++) readability
{
for (int c = 0; c < cols; c++)
{
grid[r][c] = ch;
}
}
Add spaces around operators and
} after semicolons

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

5-19
Blocks, Indentation (contd)
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.

5-20
private static void merge(double[] a,
int from, int middle, int to)
Methods
{ body
int i = from, j = middle + 1, k = from;

while (i <= middle && j <= to)


{
if (a[i] < a[j])
{
One One
temp[k] = a[i]; compound compound
i++; statement
statement
}
else
{
One
temp[k] = a[j]; compound
j++; statement
}

k++;
}
...
}
5-21
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?

5-22
Review (contd):
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?

5-23
Review (contd):
What are braces used for in Java?
Is indentation required by Java syntax or
style?

5-24

Das könnte Ihnen auch gefallen