Transcript Ch2

Getting Past the Compiler
• A compiler is responsible for checking that
programs obey a language’s rules.
– Syntax errors.
– Semantic errors.
• Logical errors could still get through.
– Logical errors only manifest themselves at
runtime.
OOP with Java, David
J. Barnes
Common Program Components
1
Fundamental Language Elements
• Reserved Words (over 40)
• Identifiers
– Look similar to reserved words.
• Curly Brackets - always in pairs.
class Nothing {
public static void main(String[] args) {
}
}
OOP with Java, David
J. Barnes
Common Program Components
2
The Simple Structure of a
Method
• Methods have a header and a body.
– The body contains declarations and statements.
• The Main Method.
– A program’s starting point.
– public static void main(String[] args)
• Formal arguments between parentheses.
OOP with Java, David
J. Barnes
Common Program Components
3
White Space
• Mainly for human readers.
• White space only required between
identifiers and reserved words.
– class Nothing{public static void
main(String[]args){}}
• Indent to show program structure.
• Try to be consistent.
OOP with Java, David
J. Barnes
Common Program Components
4
Comments
• Entirely for human readers; ignored by the
compiler.
• Three forms in Java.
– // A single line comment.
– /* The text of a multi-line comment
may be spread over several lines. */
– /** Javadoc multi-line comments
contain program documentation
directives. */
OOP with Java, David
J. Barnes
Common Program Components
5
Compiling and Running A
Simple Program
• Store in the file Hello.java
// A program to print "hello, world".
class Hello {
public static void main(String[] args) {
System.out.println("hello, world");
}
}
OOP with Java, David
J. Barnes
Common Program Components
6
The Edit-Compile-Run Cycle
• Create the file, Hello.java
• Compile (using JavaSoft’s SDK).
– javac Hello.java
• (Edit to correct errors?)
• Run using the bytecode interpreter.
– java Hello
• Edit and repeat until satisfied.
OOP with Java, David
J. Barnes
Common Program Components
7
Bytecode Files
• The Java compiler creates per-class
bytecode files.
• A bytecode file has a .class suffix.
– Hello.class
• The same bytecode file may be run on any
machine with a bytecode interpreter,
without recompilation.
OOP with Java, David
J. Barnes
Common Program Components
8
Review
• Compilers apply stringent checks to the text
of a program.
• A program may not be run until it compiles.
• A program starts running from its main
method.
• A program is compiled with javac.
• A compiled program is run with java.
OOP with Java, David
J. Barnes
Common Program Components
9