Our first Java program

From Juneday education
Jump to: navigation, search

Source code

 1 import lib.Greeter;
 2 
 3 public class Simple {
 4 
 5     public static void main(String[]args) {
 6 
 7         Greeter hello = new Greeter();
 8         Greeter hi    = new Greeter("Hi, I am simple");
 9 
10         hello.greet();
11         hi.greet();
12     }
13 
14 }

Line by line explanation

  1. import - tells java we want to use functionality not found in this file, in this case the class "lib.Greeter"
  2. a simple blank line to make it easier to read
  3. naming our class. More on classes soon, but for now a class is a building block of a Java program. We're starting a (named) block
  4. a simple blank line to make it easier to read
  5. starting point of our program inside a block (a named block, main)
  6. a simple blank line to make it easier to read
    The program starts to work/function at line 7
  7. Declare a reference "hello", create an object of class Greeter which hello can refer to
  8. Declare a reference "hi", create an object of class Greeter which hi can refer to
  9. a simple blank line to make it easier to read
  10. ask the object, using the reference hello, to greet
  11. ask the object, using the reference hi, to greet
    now the program has worked its way through the main block and will terminate
  12. ending the block
  13. a simple blank line to make it easier to read
  14. ending the class

Exercises

  1. This program defines a new Java "class" called Simple. What characters do you think symbolizes the start of the class, and the end of the class respectively? (You do not need to understand what a Java class is yet! This is just a reading exercise.)
  2. The class Simple declares a "method" called main. What characters do you think symbolizes the start of the method, and the end of the method respectively? (You do not need to understand what a method is yet! This is just a reading exercise.)
  3. What names used in this small program starts with a capital letter?