Updated 3_ExploringHelloWorld.txt

gee authored
revision a44caba031ffe80a9eb788fd5b8bbef6362ecf55
# 3 - Exploring Hello World

### Learning Objectives :

- Learn basic Fantom syntax
- Learn how to write output to the console
- Learn what objects are
- Learn what classes are
- Learn what methods are

### Introduction

Now that we have Fantom set up on our computer we are ready to begin. Before we start exploring Fantom's wonderful features we will take a close look at the sample program we ran in the previous chapter. This is probably one of the most important programs you will write when you first learn a language. The *Hello World* application prints the words "Hello World" to the console. This program usually shows the basic syntax of a programming language. It also shows the basic structure of a program in the programming langauge.

We will be dissecting Fantom's version of the *Hello World* program to learn the basics of the language. Many of the definitions and topics we will cover are going to be explained in abstract, high-level ways. I don't expect you to understand the more advanced concepts right away but if you do then you have a head start.

### Hello World

If you haven't already written the hello world program from the previous chapter then you will need to create a new file named *HelloWorld.fan* ( make sure the extension is .fan ). If you already created a project or file from the previous chapter then you can use that same file. When you have the file created make sure it contains the following code. I encourage you not to always just copy code from this book. You will learn how to program better by typing out the code. Just like you learn stuff better by writing things down, you learn programming better by typing things out.


class HelloWorld {
Void main() {
echo( "Hello, World!" )

Once you have your file set up, compile and run it. If you forgot how to compile and run then revisit chapter 2. This should be your outpu:


Hello, World!

Now that we are sure we have everything set we will take a look at the Fantom code.

### Dissecting the Hello World Program

It is very important that you get in the habit of analyzing your code, getting an idea of what the code is doing, and getting an idea of what the output of your code will be. Let's analyze the *Hello World* program.

**I will start, going backwards. I will start on this line in *HelloWorld.fan* :**


echo( "Hello, World!" )

This line is the most interesting one in the program. This is the line that actualy prints the words "Hello World" to the console. In this line we call the `echo` method. **A method is a reusable body of code that performs an action**. We invoke a method by calling it. Calling it consists of using the method's name and supplying any parameters it might need in parentheses. **Parameter or arguments is the data a method uses to perform an action(s)**. Some methods don't require you give it parameters. In those cases you can omit the parentheses when calling the method. Methods can calculate a value and give it back to us or they can just perform and action and return nothing.

In this example the `echo` method takes a `Str` parameter. `Str` is just a string of characters. `echo` will print the `Str` parameter you give it to the console. One good thing about methods is that they provide a high level interface for programmers. We don't have to know *how*`echo` gets the data to the console. It would be nice and interesting to know, but all we have to know to write our program is that it prints what we give it to the console. We will learn more about methods in a later chapter.

If you have programmed in a language like C/C++, Java, C#, JavaScript, or Python this syntax will look familiar to you.

**The next line we will look at is :**


Void main() {

This line *declares* a method. The method we declare is a special method called *the main mehthod*. **The main method is the starting point for all Fantom applications**. Every Fantom program has to include a main method that is declared the same way. As you can see the main method tatkes no arguments. Right now don't worry about what static means. So what does `Void` mean? As previously stated some methods don't return any values to us. That is just what main does, it return nothing or `Void`

**The next line we will look at is :**

class HelloWorld {

This is the declaration of a class. **classes classify the attributes of an object and the behaviour of and object( methods ). An object is a way we represent data in programming**. To help you better understand what objects are, take a look at this picture :


When you look at this image you dont think of it as a piece of wood with lead in it and an eraser. You usually think of it as a pencil. You dont think about all its details but you think of it as an *object* based on the properties it has. In programming, a **class is like the classification of a pencil**. The properties like color, weight, and material are included in this classification. **You can think of the actual pencil as being the object**. You can have many different color or sized pencils but they are all a pencil. In programming, you can have many different objects based one class. We will talk in detail about classes and objects in a later chapter. Right now think of a class as being a blueprint for an object and an object as the result of that blueprint.

### Details ( Beginners can skip )

class HelloWorld {
Void main() {
echo( "Hello, World!" )

In Fantom every value is an object, and every program is a set of one or more classes, each of which can have methods and fields. That is it. Every user-defined part of a program is a method or a field. The _HelloWorld.fan_ program defines a `HelloWorld` class with one method called `main`, and no fields. Conventionally, and actually if you use the Fantom intepreter, the method named `main` is the entry point for a program.

The `main` method here is declared to have `void` (no) return type and no parameters. As in Java, all methods and fields in Fantom must be given static types. Unlike Java, local variables need not be given types - they are inferred from context. Also we will see later how the language supports dynamic typing where that is appropriate. For programmers this mix of static and dynamic typing allows language which is very compact, expressive, but also well sanity-checked by the compiler. Advocates of the language would say that in practice its type system provides _better_ error protection than Java while also removing a lot of unnecessary "boiler-plate" code.

The method `echo` is used here as a function would be in many other languages. This method is called as `echo` without any qualifying class name (`OtherClass.echo`) inside a method of HelloWorld and therefore `echo` is assumed to be another method of HelloWorld.

This is surprising, because `echo` is not defined in class `HelloWorld`. It works because all classes in Fantom (except `Obj`) have a unique parent class from which they can _inherit_ methods and fields. The default parent, when as here no other is specified, is `Obj`, the root of the class hierarchy. Our method `echo` is defined as a static method of type `Obj` and therefore is inherited by HelloWorld, and indeed all other classes. It can be used anywhere in a program in the same way as a global predefined function would be in another language.

If you are learning Fantom from the standard documentation you will find that many of the built-in things you need to write code are defined as methods of standard classes, for example: `Obj`, `Str`, `Int`, and `List`.

### Syntax

The syntax of Fantom will be mostly familiar to anyone who has programmed in C-related languages, but there are some differences that are designed to make Fantom code easier to read and write.

Types ( i.e `Void`, `HelloWorld`, `Str`, `Int` ) are written with an initial upper-case letter. Methods and fields ( i.e `main()` ), and local variables ( as we will see later ), must be written with an initial lower-case letter. Fantom conventionally uses pascal-casing in which words are indicated by capitals within a name ( i.e `HelloWorld` not `Hello_world` ).

We see in *HelloWorld* that `;`s are not used. In C and Java, a `;` turns an expression into a statement and would therefore be needed after the `echo` method call. In Fantom, `;`s have the same meaning - but it can nearly always (optionally) be omitted at line breaks or before a `}` where the compiler can work out what was meant. A `;` is needed to separate expression statements written on the same line. There are very few cases where the compiler gets confused about what is meant. In those cases `;`'s should be added.

As you are learning Fantom, you will find one of the distinguishing features it has is its syntactical shortcuts (sometimes referred to as syntax sugar). These shortcuts make Fantom code easier to read. For example, any method call without parameters can omit the `()`, needed in many other languages. These shortcuts allow the compiler still to give informative error messages and programmers new to Fantom will find compiler error messages especially useful.

### Closing

We covered a lot today. I dont expect you to understand all of the concepts we went over. We will talk more in depth about the different topics covered in later chapters. This was to introduce you to the basic structure of a Fantom application and the basic syntax of Fantom. In the next chapter we will start with the building blocks of a Fantom application; statements, expressions, and operators.

## Exercises

*1. Change `echo( "Hello, World!" )` so that it prints nothing to the console

*2. Remove the main method and see what happens when you run the program without it.

## Advance Exercises ( Beginners can skip )

*1. Find out from the standard documentation what are the other static methods of class `sys::Obj` (that is, class `Obj` of module `sys`)?

*2. How can you tell which of the following user-defined names: `BigInt`, `myCompoundNumber` are types?

*3. Give an example of Fantom code written which requires use of a `;`.

*4. What is the parent of the HelloWorld class?