Basic code structure

Dr Andy Evans

[Fullscreen]

Basic code structure

 

  • The fundamental unit of code is the Class.
  • Classes are chunks of code that do stuff.
  • Usual each class has its own file.
  • The class name and filename should be the same, and start with an uppercase letter.
    • E.g., the FilmQuiz class would be in a FilmQuiz.java file
  • Case Sensitive. No spaces. Usually CamelCase
    • I.e., filmQuiz, filmquiz, and Filmquiz would all be different classes.

Our first Class

 

Starting with a blank file, we add the following code...


public class HelloWorld {
		
}

And save it as HelloWorld.java

 

  • Won't do anything - needs something between its brackets {}.
  • public and class are keywords: words you can only use in special contexts.
  • The public bit isn't always needed here, but helps.

Blocks

  • The area between the brackets is known as a block.
  • These are used to divide up Java code into areas that do different things.
  • These can be nested inside each other.
  • They usually start with a "declaration" of what they are (e.g. the class declaration "public class HelloWorld").

public class HelloWorld {
    {
		Code to do stuff would go here.
    }
}

The first thing we need is a 'main' block.

The starting class

  • When you pass a file to the interpreter, the interpreter looks in the class for a block called main. It knows all the instructions for how to start are in this block.
  • Without a main block the interpreter wouldn't know where to start - so you must have one to start the interpreter.
  • Only one class in a full program need have one.

 

Main block

 


public class HelloWorld {
    public static void main (String args[]){
	
    }
}

  • Don't worry about the details ('static' etc.) we'll cover these at a later point.
  • Any class with a main block can be 'run'.

That's the tricky bit done

 

  • We've made our starting class, and told the interpreter where to start.
  • Now we just have to fill the main block with stuff to do.
  • This is where we really start the coding.

Cheesy example

 


public class HelloWorld {
    public static void main (String args[]){
			System.out.println("Hello World");
    }
}

  • 'Prints' (writes) "Hello World" to the screen (the command line).
  • Note that it uses a class called 'System' to print.
  • Note that all lines not followed by a block end in a semi-colon ("statements").

Review

 

  • We define classes which have code in them to do stuff.
  • Blocks are section of code that do stuff. Lines that don't end in blocks end in semi-colons.
  • The first class you pass to the interpreter must have a 'main' block, with instructions of what to do to first run the program.