CSC204 – Programming I

Download Report

Transcript CSC204 – Programming I

CSC204 – Programming I
Lecture 4
August 28, 2002
Recap: Compilation & Execution
editor
Compilation
Source
compiler
Code
edit
(xxx.cpp) (g++) Compiled
File
load
text file
compile
(a.out)
saved on disk
Edition
8/28/2002
Instructions in
machine language
CPU specific
saved on disk
CSC 204 Programming I
CPU
Memory
Execution
2
Recap: Interpretation & Execution
editor
Source
Code
edit
(xxx.bas)
CPU
interpreter
Memory
text file
Edition
8/28/2002
interpret
Compilation &
Execution
CSC 204 Programming I
Internal
file
Instructions in
machine language
CPU specific
3
Recap: Java’s Approach
editor
Compilation
Source
Compiler
Code
edit
(xxx.java) (javac)
text file
saved on disk
Edition
8/28/2002
Bytecode
compile program
load
(xxx.class)
Instructions in
bytecode
saved on disk
CSC 204 Programming I
CPU
Memory
JVM
interpret
Execution
4
A Simple Java Program

The following program displays the
message Java rules! on the screen.
// Saved in a file namedJavaRules.java
// Displays the message "Java rules!"
public class JavaRules {
public static void main(String[] args) {
System.out.println("Java rules!");
}
}
8/28/2002
CSC 204 Programming I
5
Program Layout

The JavaRules program raises a couple of
issues:


8/28/2002
Why do we put comments into programs, and
what are the rules for doing so?
How should we “lay out” a program? Does it
matter where we put spaces and blank lines?
Where should the curly braces go?
CSC 204 Programming I
6
Comments
Comments are an important part of
every program.
 They provide information that’s useful
for anyone who will need to read the
program in the future.

8/28/2002
CSC 204 Programming I
7
Typical Uses Of Comments
To document who wrote the program,
when it was written, what changes have
been made to it, and so on.
 To describe the behavior or purpose of a
particular part of the program, such as a
variable or method.
 To describe how a particular task was
accomplished, which algorithms were
used, or what tricks were employed to get
the program to work.

8/28/2002
CSC 204 Programming I
8
Types of Comments

Single-line comments:
// Comment style 1

Multiline comments:
/* Comment style 2 */

“Doc” comments:
/** Comment style 3 */

Doc comments are designed to be
extracted by a special program, javadoc.
8/28/2002
CSC 204 Programming I
9
Problems with Multiline Comments

Forgetting to terminate a multiline
comment may cause the compiler to
ignore part of a program:
System.out.print("My ");
/* forgot to close this comment...
System.out.print("cat ");
System.out.print("has "); /* so it ends here */
System.out.println("fleas");
8/28/2002
CSC 204 Programming I
10
Single-line Comments

Many programmers prefer // comments to
/* … */ comments, for several reasons:




8/28/2002
Ease of use
Safety
Program readability
Ability to “comment out” portions of a program
CSC 204 Programming I
11
Java Programs in General

Building blocks of a Java program:



8/28/2002
Classes. A class is a collection of related
variables and/or methods (usually both). A
Java program consists of one or more classes.
Methods. A method is a series of statements.
Each class may contain any number of
methods.
Statements. A statement is a single
command. Each method may contain any
number of statements.
CSC 204 Programming I
12
Natural V.S. Java Languages
Book
Application
parts
packages
chapters
classes
sections
methods
paragraphs
8/28/2002
sentences
statements
words &
punctuations
tokens
CSC 204 Programming I
blocks/
segments
13
Tokens
A Java compiler groups the characters in a
program into tokens.
 The compiler then puts the tokens into
larger groups (such as statements,
methods, and classes).
 Tokens in the JavaRules program:

public class JavaRules { public
String [ ] args ) { System .
"Java rules!" ) ; } }
8/28/2002
CSC 204 Programming I
static
out .
void main
println (
(
14
Avoiding Problems with Tokens

Always leave at least one space between
tokens that would otherwise merge
together:
publicclassJavaRules {

Don’t put part of a token on one line and
the other part on the next line:
public class JavaRules {
8/28/2002
CSC 204 Programming I
15
Indentation

Programmers use indentation to indicate
nesting.


An increase in the amount of indentation
indicates an additional level of nesting.
The JavaRules program consists of a
statement nested inside a method nested
inside a class:
8/28/2002
CSC 204 Programming I
16
How Much Indentation?

Common amounts of indentation:





2
3
4
8
spaces:
spaces:
spaces:
spaces:
the bare minimum
the optimal amount
what many programmers use
probably too much
The JavaRules program with an
indentation of four spaces:
public class JavaRules {
public static void main(String[] args) {
System.out.println("Java rules!");
}
}
8/28/2002
CSC 204 Programming I
17
Brace Placement
Brace placement is another important
issue.
 One technique is to put each left curly
brace at the end of a line. The matching
right curly brace is lined up with the first
character on that line:

public class JavaRules {
public static void main(String[] args) {
System.out.println("Java rules!");
}
}
8/28/2002
CSC 204 Programming I
18
Brace Placement

Some programmers prefer to put left curly
braces on separate lines:


This makes it easier to verify that left and right
braces match up properly.
However, program files become longer because
of the additional lines.
public class JavaRules
{
public static void main(String[] args)
{
System.out.println("Java rules!");
}
}
8/28/2002
CSC 204 Programming I
19
Brace Placement

To avoid extra lines, the line containing
the left curly brace can be combined with
the following line:
public class JavaRules
{ public static void main(String[] args)
{ System.out.println("Java rules!");
}
}

In a commercial environment, issues
such as indentation and brace placement
are often resolved by a “coding standard”
8/28/2002
CSC 204 Programming I
20
Using Variables
In Java, every variable must be declared
before it can be used.
 Declaring a variable means informing the
compiler of the variable’s name and its
properties, including its type.
 int is one of Java’s types. Variables of
type int can store integers (whole
numbers).

8/28/2002
CSC 204 Programming I
21
Declaring Variables

Form of a variable declaration:




The type of the variable
The name of the variable
A semicolon
Example:
int i;

// Declares i to be an int variable
Several variables can be declared at a
time:
int i, j, k;

It’s often better to declare variables
individually.
8/28/2002
CSC 204 Programming I
22
Initializing Variables

A variable is given a value by using =, the
assignment operator:
i = 0;
Initializing a variable means to assign a
value to the variable for the first time.
 Variables always need to be initialized
before the first time their value is used.
 The Java compiler checks that variables
declared in methods are initialized prior to
their first use.

8/28/2002
CSC 204 Programming I
23
Initializers

Variables can be initialized at the time
they’re declared:
int i = 0;
0 is said to be the initializer for i.

If several variables are declared at the
same time, each variable can have its own
initializer:
int i = 0, j, k = 1;
8/28/2002
CSC 204 Programming I
24
Changing the Value of a Variable

The assignment operator can be used both
to initialize a variable and to change the
value of the variable later in the program:
i = 1;
…
i = 2;
8/28/2002
// Value of i is now 1
// Value of i is now 2
CSC 204 Programming I
25
Program: Printing a Lottery Number
Lottery.java
// Displays the winning lottery number
public class Lottery {
public static void main(String[] args) {
int winningNumber = 973;
System.out.print("The winning number ");
System.out.print("in today's lottery is ");
System.out.println(winningNumber);
}
}
8/28/2002
CSC 204 Programming I
26
Types

A partial list of Java types:
int — An integer
double — A floating-point number
boolean — Either true or false
char — A character

Declarations of double, boolean, and
char variables:
double x, y;
boolean b;
char ch;
8/28/2002
CSC 204 Programming I
27
Literals
A literal is a token that represents a
particular number or other value.
 Examples of int literals: 0 297 30303
 Examples of double literals:

48.0
48.
4.8e1
4.8e+1
.48e2
480e-1
The only boolean literals are true and
false.
 char literals are enclosed within single
quotes:

'a'
8/28/2002
'z'
'A'
'Z'
'0'
'9'
CSC 204 Programming I
'%'
'.'
' '
28
Using Literals as Initializers

Literals are often used as initializers:
double x = 0.0, y = 1.0;
boolean b = true;
char ch = 'f';
8/28/2002
CSC 204 Programming I
29
Conventions
A rule that we agree to follow, even
though it’s not required by the language,
is said to be a convention.
 A common Java convention is beginning a
class name with an uppercase letter:

Color
FontMetrics
String

Names of variables and methods, by
convention, never start with an uppercase
letter.
8/28/2002
CSC 204 Programming I
30
Keywords

The following keywords can’t be used as
identifiers:
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do

double
else
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
null, true, and false are also reserved.
8/28/2002
CSC 204 Programming I
31