Structure of a Java Program
- Structure of a
Java program:
- A Java program
consists of a number of
classes
- A Java class
contains a number of
(1) class vars,
(2) instance vars and/or
(3) methods
- A Java class
contains a number of
(1) param vars,
(2) local vars and/or
(3) statements
- There are 4 kinds of
statements:
(1) assignment,
(2) cond.,
(3) loop and
(4) method call
|
Your first Java program
- The "classic"
Hello World
program in Java:
public class hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
|
Notice:
- The Java program consists of
one or more
classes
- A class contains
0 or more
(class or instance) variables and
0 or more
methods/functions
- A method contains
parameters,
local variables and
program statements
|
|
DEMO:
01-basics/02-hello/hello.java
(in
~/c/OutSchool/CS/AP-CS/demo/)
How to
define a
class
- A Java class is
defined with the
keyword
class:
public class hello // "hello" is the name of the class
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
|
- The matching
curly braces
{ ... }
denotes the
boundaries of
a class
- Inside a
class, you can
define:
- Class
variables (later)
- Instance
variables (later)
- Methods
(e.g.:
main( ))
|
|
Show the
structure of the
hello class with
slide 1
Adding comments to the codes in your Java program
Example comments in a Java program
/* ----------------------------------------------------
This is your first Java program
---------------------------------------------------- */
public class hello // The name of this class is hello
{
// There are no variables defined in the class
/* ------------------------------------------------------
A Java program starts executing with the method "main"
------------------------------------------------------ */
public static void main(String[] args)
{
System.out.println("Hello World"); // Prints "Hello World"
}
}
|
DEMO:
demo/01-basics/03-comment/hello.java
❮
❯