Saturday, November 2, 2013

Introduction

Introduction

This is the introduction into the series of articles about Java programming for beginners. I'll start with the assumption that you, my dear reader, don't have any experience in Java or any other programming language. I'll be honest with you - programming is not easy thing to do. But teaching programming is even harder because it requires not only trying to forget whatever I've learned so far myself to be as close as possible to the state of mind of the person who has never seen a program before, but it also requires me to remember and make very clear and simple all the hardest things I had problems with and spent sleepless nights figuring them out.

First, we'll start with installing the Java virtual machine on your computer. Second, we'll look at the code for our first and the simplest Java program. During this introduction we'll make notes and remember the basic concepts about programming and writing programs.

Let's start.

Programming languages concepts

There are many programming languages, so many that I can't even remember all of them from top of my head. Some are very easy to read. Some are very fast. But almost all of them share some common features:

  1. The program code is written is some sort of text files readable by humans.
  2. The program code is transformed from the human readable format into the machine instructions that computers can understand.
  3. The computer executes the transformed machine code step by step, instruction by instruction.
  4. The program terminates when there's no more instructions left.

You have to understand that the program is just the instructions you tell the computer to execute. There's no magic out there. The computers are not some smart creatures that know how to do things. The only thing computers know is how to move electrons at the very high frequencies. That's all. They don't know how to sum up numbers, how to draw images, how to print text. Computers only know how to execute very limited number of the commands which you, as the programmer, tell them to do. And they do it very fast. That's only reason computers exists - they can do very limited numbers of things very fast. So fast that we, humans, will never be able to do at that speed.

So how do computers know how to connect to the Internet and display your lovely cat memes? Programs and programmers evolved. They became very sophisticated and capable to understand and write instructions to connect to other computers and display pixels on the screen. But underneath, it's still same set of building blocks - very small and limited set of instructions which every program consists of. These basic instructions are like atoms. Limited number of atoms form all known substances. So do basic instructions in programming languages. The order of instructions you put into your program results in the program execution and the final result. These instructions can be put into right order and the program will produce the expected result. Or they can be ordered in such a way that there will be unexpected errors. And this is where the programmer comes into the scene - to create the correct order of instructions.

Programming thinking

At this point you should realize that programs don't live in isolation. Indeed, each program starts with some idea or problem you want to solve. It's important to develop appropriate programming thinking and look at every problem in terms of steps needed to accomplish the goal.

  1. Think thoroughly about the task or the problem.
  2. Split the problem into granular steps and think about logical solution to each step, what you need to do to accomplish it.
  3. When you understand the solution required, think about the code and mentally build the imaginary code in your mind. You don't have to be specific about every instruction here. It's enough to understand how you want to program it.
  4. Once you know how to program it, start writing the code.

For example, imagine that you know Java already (soon!) and the customer tells you to write the program which, when executed, prints "Hello world" on the screen and terminates. That's simple, you may think. Of course, it is! When you know, everything becomes simple. It's another story, if you don't. Let's remember our programming thinking steps and apply it here.

  1. The problem is the program that has to print "Hello world" text on the screen every time it runs.
  2. The major steps are:
    • There must be executable file that the customer will be able to run.
      • We have to know how to create an executable file in Java
      • We have to know how to run an executable file in Java
    • The instructions of our executable file must print "Hello world" and terminate.
      • We have to know how to print text in Java program.
      • We have to know how to terminate the running Java program when the text has been print.

This may sound like an overkill for this simple problem, but it helps to train your mental power from the beginning and then layer by layer you will find how it helps you break down even the most complex problems to simple steps that you can chain together and deliver the outstanding result.

A journey of a thousand miles must begin with a single step.
Lao Tzu

Let's start addressing our problem step by step.

Java

In order to program and run Java programs, you have to download Java Development Kit (JDK). At the moment of writing you can get it here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Note that you have to download JDK. Depending on the operating system, follow the specific instructions there. For Windows or MacOS users it's just a matter of running the installer. For Linux users it's just a matter of unpacking the archive.

Making sure that Java installed properly

The simplest way to check if Java installed properly is to open command line prompt (terminal) and run this command:

javac --version

The result should be the current version of the JDK installed. So the command and the result should look like this:

javac --version
javac 1.7.0_45

Now let's write the code.

Create some folder where you want to store your projects and name it, for example, projects. Inside projects create another directory called introduction and open it. So now you should be located at projectsintroduction

Create the file called HelloWorld.java and write your first Java program step by step:

Step 1

HelloWorld.java
public class HelloWorld{}

Step 2

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

Step 3

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

Open command line and navigate to projectsintroduction cd projectsintroduction

Compilation

Now execute this command javac HelloWorld.java

This command compiled our program. Just remember for now that computers can't just run your HelloWorld.java because it's a human readable text and is only for humans to read and modify the code.
javac command translates this text into the instructions that Java will be able to run.

And now it's time to run our program. Run this command: java HelloWorld

The result of this command will be text Hello world printed on the new line:

java HelloWorld
Hello world

Congratulations! You have just written you first Java program. I understand that there are a lot of uncertainties yet and you may not understand how it works. The reality of being a programmer is that you spend a lot of time reading other people's code. Prepare to read a lot of code. That's why I started with the program code first to let you start developing another super-hero ability of reading and understanding other people's minds looking at their code. Let's dissect our first program and walk through line by line.

You may wonder what this Hello world means. If you have never written any programs before you may find it interesting that there's a tradition in all programming languages to demonstrate the first example as a program which just prints Hello world text in the console. You can read about it on Wiki: Hello world

First of all, let's take a look at line 3:

System.out.println("Hello world");

This code prints text Hello world on the screen. This is line of the code that is, essentially, accomplishes our goal and solves the task. Why does it look like this and how do I know that the code has to be written this way? For now just remember that in order to display a text on the screen you have to type System.out.println("Text you wand to display");

I know you feel a little bit confused now, but remember when you were a kid and your parents told you that there are some things you'll understand only when you grow up? When you were a kid, you didn't have a choice but just believe and remember a lot of things that parents tell you. You just accepted it as a fact. Later on, when you grow up, you understand a lot of details. Same thing with learning programming or any other science - in the beginning you just accept and believe what teacher tells you. You were taught that division by zero is prohibited. And you were fine with that. Then you discovered that it's actually allowed and you get infinity. But only when you were ready for that.

I'll use same approach as teaching a kid. Just remember some things have to be done in a defined way in order for a program to work.

First of all, look at our HelloWorld.java let's take a look at line 1 public class HelloWorld {

  • Every java program has to start with public class Name of the file without .java {
  • Every opening curly brace { has to be eventually matched with the corresponding closing curly brace }
    • That's why line 5 has } - the matching closing curly brace for { at line 1
  • Every java program has to have public static void main(String[] args) { and the corresponding closing }
    • That's why line 4 has } which is the closing curly brace for the opening curly brace { at line 2
  • The actual code, which in our case is only 1 instruction to print the text on the screen, must be written between { and }
    • That's why we have System.out.println("Hello world"); on the line 3 and it's inside the curly braces block { } opened at line 2 and closed at line 4.
  • Every statement (instruction) in java code has to be terminated with semicolon ;
    • That's why we have semicolon after System.out.println("Hello world");

And now let's briefly review it again

  • Our program file is called HelloWorld.java
    • That's why our code starts with public class HelloWorld
  • Opening and closing curly braces {} define a block of code where instructions has to be put at
    • That's why whe open code block at line 1 and close it at line 5
  • Java expects us to put our statements in the code block defined after public static void main(String[] args)
    • That's why we have
      public static void main(String[] args){
        System.out.println("Hello world");
      }

Let's make some other experiments and you'll feel more comfortable with what's important to remember.

Imagine that our specifications changed and we want to display 2 lines of text when we run our HelloWorld program

java HelloWorld
Hello world
My name is _YOUR NAME HERE_

Let's quickly analyze what steps we have to do abstracting from the actual code:

  • We have to display the new line with text My name is _YOUR NAME HERE_, where _YOUR NAME HERE_ will be your actual name
  • We already know how to display a text with System.out.println("SOME TEXT"); instruction
  • Thus, we just need to add the new instruction to our existing program

Open HelloWorld.java and modify it. Remember to change Sergey to your name :)

HelloWorld.java
public class HelloWorld{
    public static void main(String[] args){
      System.out.println("Hello world");
      System.out.println("My name is Sergey");
    }
}

Looks great! But let's see if the changes will make any difference. Return to your command line and rerun the program:

java HelloWorld
Hello world

Ugh. That's sad. The program doesn't print your name. And that's the point when you grow up and have to discover another truth about this world.

Remeber the first step we did when we wrote our first program: compilation. That's where the truth is concealed - every time you modify your source file HelloWorld.java, you have to compile it for changes to take into effect.

Let's compile it.

javac HelloWorld.java

And now run it

java HelloWorld
Hello world
My name is Sergey

Great! Now your program works with the changes we make. Now you, my curious reader, should ask me, "But how does Java know if the code was compiled?". That's a very good question.
And the answer to it is the javac command which compiles the code. This command creates a file HelloWorld.class

If you look in the projectsintroduction directory, you'll see 2 files there:

  • HellWorld.java - the source file with our program text
  • HelloWorld.class - the file created by javac command

And this reveals the last mystery - the understanding of java command. When you run

java HelloWorld

java command looks for HelloWorld.class file. If it finds it, it runs. If not, and error will be printed out to the console.

When we modified our source file HelloWorld.java to print new line with your name, we didn't compile it with javac command and ran the program hoping it would print our name. But the HelloWorld.class file had old compiled code with only "Hello world" text in it. That's why java command printed only this line first time we ran it. After we compiled again our source file HelloWorld.java, javac updated HelloWorld.class file and after that java command was able to see the changes.

And this leads to the conclusion of the general process of writing java programs:

  1. Create the .java source file, for example MyNewProgram.java
  2. Write code in the source file
  3. Compile the source file with javac command, for example javac MyNewProgram.java
  4. The result of the javac command is a .class file, for example MyNewProgram.class
  5. Run the program with java command, for example java MyNewProgram
  6. If you want to make changes, repeat with step 2

Exercises

  1. Create a java program that prints "I know Java!" text in the console. Name the source file IKnowJava.java

The solutions to exercises will be shown in the next consecutive chapter. You can comment your exercise solution in the comments. I'll review it and follow up with you regarding any errors.

Conclusion

In this introduction we learned how to write simple java program. Even though it was very simple and printed text lines in the console, we learned a lot of details and steps involved into writing all java programs of any complexity.

Our dictionary is now expanded with new words:

  • source file - the .java file with human readable program text
  • javac - java compiler - compiles java source and creates a .class file
  • java - runs the java program
  • code block - everything between curly braces {}
  • statement - the instruction to a computer do some work
  • ; - semicolon - multiple instructions are separated by the semicolon
In the next tutorial we'll learn how to write more sophisticated programs and do basic operations with numbers.