Java Syntax
Ann, Tom, Christiane, Ralf
Hasso Plattner Institute
Basic Unit: Class
1 class HelloWorld {
2
3
4
5
6 }
Class
■ Keyword class
■ Every piece of code resides within a class
■ A program can have many classes,
but must have at least one
2
Syntax: Curly Braces
1 class HelloWorld {
2
3
4
5
6 }
Curly Braces
■ Code blocks are delimited by a pair of curly braces { }
■ The body between the curly braces belongs to the current element
■ Put opening and closing curly braces on the same indentation level
3
Structure of Source Code
1 class HelloWorld {
2 public static void main(String[] args){
3 //our program always starts in the main method
4 }
5 }
6
Indentation
■ Everything inside the curly braces (code block) is indented for better
readability
4
Structure of Source Code
1 class HelloWorld {
2 public static void main(String[] args){
3 //our program always starts in the main method
4 }
5 }
main() method
■ Starting point of the program
■ Only exists once within a given program
■ Defined inside of a class
5
Comments
1 class HelloWorld {
2 public static void main(String[] args){
3 // a single line comment
4 /* a multiple line
5 comment */
6 }
7 }
Comments
■ Not executed when running the program
■ Used to explain code to fellow programmers
6
Output
1 class HelloWorld {
2 public static void main(String[] args){
3 System.out.println("Welcome to the course!");
4 }
5 }
Welcome to the course!
7
Statements
1 class HelloWorld {
2 public static void main(String[] args){
3 System.out.println("Welcome to the course!");
4 }
5 }
Statements
■ End with semicolons
8
Structure of a Program
Program
Class Class
main() Method Method
Class
Method
Method
Method
9
Java Syntax
Ann, Tom, Christiane, Ralf
Hasso Plattner Institute