Lec 2
Lec 2
Comments
comment: A note written in source code by the
programmer to describe or clarify the code.
Not executed when your program runs.
Syntax:
// comment text, on one line
or,
/* comment text; may span multiple lines */
Examples:
// This is a one-line comment.
/* This is a
two-line comment. */
2
Using comments
Where to place comments:
at the top of each file (a "comment header")
at the start of every method (seen later)
to explain complex pieces of code
3
Comments example
/* Suzy Student, CSE142, Spring 2009
This program prints lyrics about ... something. */
// second verse
System.out.println("diggy said the boogy");
System.out.println("said up jump the boogy");
}
}
4
Static methods
static method: A named group of statements.
denotes the structure of a program
class
eliminates redundancy by code reuse
method A
statement
procedural decomposition:
statement
dividing a problem into methods
statement
method B
statement
Writing a static method is like
statement
adding a new command to Java. method C
statement
statement
statement
5
Using static methods
1. Design the algorithm.
Look at the structure, and which commands are repeated.
Decide what are the important overall tasks.
6
Declaring a method
Gives your method a name so it can be executed
Syntax:
public static void name() {
statement;
statement;
...
statement;
}
Example:
public static void printWarning() {
System.out.println("This product causes cancer");
System.out.println("in lab rats and humans.");
}
7
Calling a method
Executes the method's code
Syntax:
name();
Example:
printWarning();
Output:
8
Program with static method
public class RepeatIt {
public static void main(String[] args) {
rap(); // Calling (running) the rap method
System.out.println();
rap(); // Calling the rap method again
}
Output:
Now this is the story all about how
My life got flipped turned upside-down
System.out.println("Done System.out.println("Done
with main."); with message2.");
} }
12