Your first program

Today we are going to see the most complex and biggest post in all the course (I hope, because I need a lot of time to writhe these) because I introdouce a lot of new concepts in one big pill. These concepts will follow us along all the course, so if there is something that you don’t understand, maybe in the next post all will be clear (or you can comment). And at the same time, if you dont understand the base of something in other post, come back here.

First steps:

Before coding, we will create the project. To do that open your editor of choice (I like Netbeans, but you can use the one fits you better) and click the button to create a new project. This will automatically create and manage the folders and files for your program.

In Netbeans you’ll have to choose a category. Choose „Java“→ „Java Application“. Press „next“ and give a name to the project (like „Proba“, „Test“, „ProgrammingCourse01“…).

You are ready to go.

Usually you will see a main class template. I will explain the basics here:

  • Java is an Object Oriented Language. What you write are „classes“ which contains variables and functions. Later, we will create objects from these classes. For example: We can have a class called “Person” with the variables “Name”, “Birth year” and “Telephone” and a function to calculate the age (we will see this later in an example). Then you create two objects of the class Person. One object has in the variable “Name” the value “John Doe”, the other one has in the same variable the value “Janina Dina”. A class is the mould, and the objects are the cakes that you do there.

  • Inside your program there is a special function: The main function. When a program starts, it begins here. When the main function ends, the program ends.

This can seem a little confusing right now, so before we start, I will explain some concepts that appeared there:

  • Variable: Its an information unit. The program takes a little memory space to storage a number, a text, etc. For the Person class from the previous example, “Birth date” and “Telephone” would be numbers and “Name” would be text.

  • Sentence: A single command (well, not really, it can have several of them, but to simplify it’s ok). This command can be some lines of text long, but it always ends in “;”. Creating a variable is a sentence. Giving to that variable a value is another sentence. Checking a variable and doing something about that is another sentence… We will cover all this in other posts.

  • Functions: When a program is long enough, you will see that some sentences are repeated a lot of times with just a few differences between repetition. To simplify the code, make it easier to read and easier to manage we create functions as a group of sentences with a specific purpose. We can see it as a machine where you introduce a pair of values and the machine generates an output, some result . For example, in the previous class Person there was a function to calculate the current age of the person. We give the function the birth year of the person, the current year and it will give us how many years old is that person. We can create some variables inside the function that will be used only there, and not outside.

We write code

With all that said, we start with the program. Write (WRITE, don’t copy-paste it or it will be harder to learn) this inside the Main function.

The main function should look like this:

Now, if you press the button that looks like a “play”, it will execute your programm and you will see:

Name: John Doe. Birth year: 86. Telephone: 666666666
BUILD SUCCESSFUL (total time: 0 seconds)

Lets analyze what have we done

As we said, the program starts at the main function. And there with the first sentence:


Sentence 1

String name = "John Doe";

Here we create a text variable (The “String” before the name), called “name”, and we give it the value “John Doe” (all the text values are between “”) Check this patron: [Data type] [Variable name] = [initial value]. It’s used in all the variables.

Try to change the value. Instead of “John Doe” write “Pepe”. If you forget the “” the program wont start. If done correctly you will see this text:

Name: Pepe. Birth year: 86. Telephone: 666666666


Sentence 2

int birthYear = 86;

This creates a number variable [int → Integer]. If you want to use a decimal number you must use other data type, like “float” (not a lot of decimals but enough to almost everything) or “double” (double precision float, for scientific purposes). Check that the name hasn’t any space. Thats because the variable names are converted by the program to computer language and if the name has two or more words with space, it will recognize only the first. The second will give an error. Therefore we write a very large word, and to make it easier to read we write the first letter from every word as a capital letter.

Try to write “1976” instead of 86.


Sentence 3

int telephone = 666666666;

The same as the previous one.


Sentence 4

This sentence is special: It is 2 lines long (and could have more) but it has only one “;”, therefore it is only one sentence.

Here we call a special class from Java (System.out) which helps us to write text output. It has a lot of functions to do that, like “print” or “println”. The difference is that the text that it writes with println is in another line, but with print we have to manage the lines manually.

Inside this “()” is the value that we give to the function. This function, this machine, needs only one value of the text type to work. All the text is inside the quotation marks. With the “+” we “paste” one text after another, and with the variable name we read the value stored in the variable. Therefore we send only a big text, made from little text followed with the text stored in the variables.

Try to change something.

We upgrade the program and add a function

We will create the function that we said in the first examples to calculate the age of the person.

Remember: A function is a machine where we introduce some values and we receive another value (or not and the function is only to pack some sentences to make the code easier to read)

So we write this:

Lets see the first line:

  • The first word is to say if the function is public or private. If it’s public, when we create an object we can call this function like we did to “println()”. If it’s private, we wont be able to see it outside this class and it will be used to hide complexity for the outside, so there will be harder to make a mistake.

  • The second word, Static, is used here because we are in the same class as main() and the function will be used inside of main. If that is not the case we dont need to use it. Something static means that you don’t need to create an object to use the function, like (again) “println()”: We didn’t created an out object, we just called the class and his function.

  • “int” tells us that the function will give an Integer. If we want to receive a text, it will be “String”. If it don’t return anything, we use “void”.

  • GetAge is the function’s name. When I want to call this function, I will write this name.

  • (int birth, int currentYear) :Thats the values that we give to the function.

Then comes the function’s content:

  • We create an int variable, called Age, and we give it an initial value of 0.

  • We give to Age the value of substract to currentYear the value of birth. This won’t modify the value of currentYear or the value of birth, it will only read the data, calculate the answer and give the new value to Age, that it’s the only one to be modified. Try to add a “*2” at the end to multiply by 2… Which value? (Answer: Only the one near the “*”. This takes mathematics rules. If you want to multiply the answer you have to substract first and then multiply, and you can do that making the substraction inside the brackets “()”).

  • With return we say to the function what value give as result. In this case we will return Age.

Ok. Its ready to work… almost. It’s not optimizied. This is important. When we optimize the program it will run faster. In this little program it’s not the case, but we will optimize it at the end to learn something about it.

Now we add the function to the main function. Write this in main:

Now we are calling to the function getAge() inside the function println() inside of the function main(). That’s abstraction. What we are doing is adding to the text the value returned by the function. It’s an int, like the telephone, so it works the same as using a variable directly. We can give the values to the function using a variable, like birthYear, or a direct value like “2015”. Remember that this won’t modify the value inside birthYear, it will only read it.

Try to execute again the program. This time you will see at the end the age. Other way to make this is to create a new variable, give to this variable the value returned by the function, and then call the variable in println like the other ones. For example:

int Age = getAge(birthYear, 2020);

Optimizing the Function

At the first line we give to the variable a value, and in the second like we give to the same variable a new value. We can give the second value directly:

int Age = currentYear - birth;

Ath the last line we return the value of Age and in the previows one we give a value to Age. What if we return directly the value and we dont store it in Age?

With all this we have only one line, the program has less operations and will run faster. Like we said, this is a very little example and we wont see it, but if we make a program that checks thousands/ millions persons, and with the previous function we needed 10 minutes, maybe with this optimization we would only need 7 (its an exaggeration, but you see the point).

Conclusion:

Now you know some common datatypes (int, string, float and double. There are more like boolean, byte, and a pair more. We will cover them later ), how a program works, functions, etc.

Really you know almost everything to make little programs or simple scripts. You should try to make new functions here and see the results. For example, try to make a function to see the age in some years (tip: the first line of the function can be something like “public static int futureAge(int currentAge, int years)” ).

In our next post I will cover the classes, inheritance, polymorphism, etc.

Leave a Reply