Learn computer programming in 20 minutes
There’s always an increasing amount of things to learn about everything. The internet is an awesome place to begin.
In this tutorial you will learn basic computer programming with no prior knowledge required. Ready to jump?
Let’s get started.
Computers do
Computers don’t really understand. They are complex calculators that can store and manipulate data.
Data, like words or characters, are stored inside the computer’s memory as numbers. As an example, the character ‘A’ is stored as ‘65’ or as a sequence of 0s and 1s.
In the same fashion, if we send an Emoji from a device to another, say an iPhone to a Samsung device, the icon will differ slightly on both devices. This happens because Apple and Samsung agree that a certain number is a smiley face, but they don’t all agree how it should be displayed 😊.
Thankfully, modern computer programming is done without complicated mathematics, we let the computer do the job. We mostly use words from the English language to tell the computer what to do.
Human readable code
We write human readable code for ease of use. The computer understand operations such as ‘print the character A’ or ‘change this pixel to yellow’. This works because certain sequences of numbers in the computers memory do certain operations.
Let’s dive into the more interesting stuff.
You can follow this tutorial by creating a new Java project inside Eclipse or IntellIJ IDEA.
Data types
A computer can manipulate many types of data, such as numbers and text. We need to tell the computer how to differentiate numbers from text.
string = text
integer = number
Let’s build a model called Human that uses a string to store it’s name.
Adding onto this idea, we’ll add a way to store an age.
Create an integer (shortened as int) named ‘age’ :
We can set the value of name and age :
Great, you are learning to read computer code!
Object model
This current model is fine if we only have a single Human. But in the future, we’ll use this model to represent every human in our program and they probably won’t all be named Alex and aged 19.
To fix this problem, we will use a constructor. A constructor is a way to tell the computer how to create an object. When creating the object, we will give it it’s name and age.
Now, we can create a human using this code :
new Human("Alex", 19);
And another :
new Human("Mike", 30);
In this way, we set the properties of the model so that is can be reused.
Let’s learn more.
Object reference
Say our human has a dog.
Create the Dog class (a new object).
We’ll do the same thing we did with Human and give it a name and age property, and a constructor.
This way, we can create a Dog exactly the same way we create a Human, giving it a name and an age.
new Dog("Luna", 4);
We link a dog to a human this way :
So we can use :
Human mike = new Human("Mike", 30, new Dog("Luna", 4));
If this is confusing, we can achieve the same thing if we type it this way :
Dog luna = new Dog("Luna", 4);Human mike = new Human("Mike", 30, luna);
The ‘luna’ keyword is in a way, a reference to the Dog object we created. Think of it as a leash we give mike to hold his dog.
This also means we can give the same dog to two people :
Dog luna = new Dog("Luna", 4);Human mike = new Human("Mike", 30, luna);
Human bobby = new Human("Bobby", 6, luna);
Changing properties
Today is Luna’s birthday. We can use a point to change the age of luna like so :
luna.age = 5
Now, let’s take a step back to look at what we’ve learned. This might not look like much, but these are the building blocks of every modern application.
Supertypes
Such as in the real world, humans and dogs are both animals. This means they share a common parent.
Create a new class called Animal.
Remove name and age from Human and Dog, and let them extend Animal.
This concept is called inheritance. For every other animal model we create, we can extend Animal and it will automatically have a name and an age property.
We say that Human and Dog are subclasses of Animal, since they inherit of all the properties of an Animal.
Just like branches in a family tree, we can keep adding layers. This principle is used to build complex systems. To keep going, we could create many more classes, ranging from the kingdom to the genus, all extending the preceding.
But let’s not do that.
Instead, we’ll now learn interesting stuff we’ll actually use. Our code does not do anything, yet.
Main entry
Let’s create a class Main to use as our entry point of the program.
That exact sequence of words tells the computer that this is actually the entry point of our program.
We can now run this program!
The computer will print something like this :
Exit code 0 is a good thing. It means no errors.
Since the entry point of the program is blank, nothing happens. Let’s remediate!
This creates a dog in the memory of the computer.
Let’s create a Mike and give him a dog.
In Java, we use the following code to print stuff to the console :
System.out.println(“Hello”);
The result :
Hello Mike!
Rerun the program :
Booleans and conditions (if that, do this.)
Let’s learn some more value types…
Boolean is a type that can only be true or false, nothing else.
Let’s add a ‘is a good dog’ property to Dog :
And set it to final and true…
This means that no matter what, every Dog that is created will be a good dog. At least, in this program.
Since the computer won’t allow to set isAGoodDog to false, we can use final to set constants, that is, properties that can never change.
Let’s learn about conditions.
> : is larger than
The if statement will execute if the condition inside the parentheses is true. Here is some more conditions :
< : is smaller than
>= : is larger or equal
<= : is smaller or equal
== : is equal
!= : is not equal
We can have two or more conditions like this :
&& : both conditions are true (and)
|| : either conditions are true (or)
Let’s say we store a condition in a boolean like so :
boolean isAYoungPup = age < 3;
Comments
Notice the //? These are comments. We can add notes to our code that the computer will ignore. We can use the following for multi-line comments :
Let’s resume.
If condition is false, we’ll reach this else statement :
We can stack if statements :
And add if statements inside of other if statements :
To handle every situation possible.
Functions
Let’s remove some of the bloat and move the code to a function.
This code will behave exactly the same way as before. Since functions can be used more than once, putting code inside functions is a great way to reuse code.
Here’s what ‘public void’ means :
- public means Mike has access to the function. If it were private, only luna could use the function.
- void means the function returns nothing.
A function can return something :
This means in the Human class we can write the following :
If we rerun, our program now prints :
My dog Luna is a doggo.
This is great and all but at the moment, if we create a Human, we need to give it a dog. Some humans don’t have dogs. Let’s remove dog from the constructor, and add a function giveDog(Dog) to Human.
And change our main function:
This code is now more flexible. It allows for a human to not have a dog.
List
Human can have more than one Dog. Instead of a single Dog, we’ll have a List of Dogs.
Let’s give another dog to Mike :
For loop
Let’s say hello to the dogs, using a for loop.
The for loop can be read as :
Create a new Dog named dog for each Dogs in mike.dogs
The output is as desired :
For loops are useful because we can manipulate lists with them :
Notice the ‘null’. We’ll get back to that soon.
Comparing Strings
In Java, we use .equals() instead of == to compare strings. If we use ==, we compare the memory location (reference). Here’s an example :
String dogsName = "Luna"; // Create a new string that stores "Luna"dogsName.equals(“Luna”); // is truedogsName == dogsName; // is always truedogsName == “Luna”; // is false, since the two strings are stored in different memory locations
When handling String values, you’ll always want to use .equals().
Null Exceptions
Also notice how we return ‘null’ when we can’t find the dog in the list. In Java, null means a missing reference. You can’t do anything with null references. If we try to get the name of a null dog :
Dog lou = mike.getDogByName("Lou");
String name = lou.name;
This happens :
This is an error message. It contains important information :
The type of the exception is NullPointerException. If go to Main.java at line 28 (click on the blue link), we are sent to the line that caused the problem.
We can fix this by having a simple if statement like so :
if (lou != null) { // if lou is not nullString name = lou.name;}
If you understand this code, let’s keep going. We’re almost done!
Override
Let’s try to print a dog object like so :
System.out.println(dog);
We get “Dog@1c53fd30”.
Where could that be coming from?
Object
A class called Object is the base for every object in Java. In the same way that Dog extends Animal, every object extend the Object.java class.
You can change this function by adding this to the dog class :
And now it will print :
Luna, 5
Notice the @Override annotation? This keyword states that we override an existing function from another class that we are extending from.
Object has a lot of functions, but we don’t usually want to override them. We can read in the comment left by developers that ‘it is recommended that all subclasses override this function’.
Implementation
In real life, both humans and dogs eat. In the same way we added properties in Animal, we can add functions :
This means that both humans and dogs can eat(). Since dogs do not eat the same way as we do, let’s implement two different eat methods.
Notice, again, the @Override annotation.
Let’s learn why subclasses are important. Let’s add a phone number to Human :
In the main function, create the human like this :
Human mike = new Human("Mike", 30, "613-555-0104");
Now, let’s create a List of Animals inside Main :
And add our human to this list :
animals.add(mike);
If we iterate trough the list :
for (Animal animal : animals) {
System.out.println("The animal's name is " + animal.name + ".");
}
We can check if this animal is a human this way :
for (Animal animal : animals) {System.out.println("The animal's name is " + animal.name + ".");if (animal instanceof Human) {
System.out.println(animal.name + " is a human.");
}
}
And write the following code :
Human human = (Human) animal;
To get a Human from that animal.
We can now access the phone number :
This principle is called polymorphism. What we have done on line 29 is called casting.
In short, we can add any object to our list of animals as long as it extends Animal.
Now, let’s make the animals eat.
If we run this, Mike will say :
I prefer it medium.
And the dogs :
animals.add(luna);
animals.add(milou);
Will say :
I like my meat raw!
Static
Let’s learn what ‘static’ means. Inside Human, add this property :
static int daysInAYear = 365;
This means that every Human object created will have the same reference to the same object. If we change Mike’s daysInAYear, then Bobby’s daysInAYear will also change.
Since the actual number of days in a year can’t change, let’s make it a constant. It is convention to make the constants name uppercase and make it public, static and final :
It is good practice to not overuse static since it can lead to spaggethi code.
We’ve gone a far way from our simple Human class. If you understand everything above, you can read the majority of code on the internet.
Abstract classes
Abstract classes are classes that only exist to be overriden.
Our Animal class can be an abstract class.
Let’s replace our method :
public void eat() {}
with this :
public abstract void eat();
Now, every subclass of Animal must have a eat() method, or else we’ll get an error :
This forces Dog to implement eat(). This is the purpose of an abstract classes.
Interfaces
In Java, an interface is like an abstract class, but it cannot contain any implemented function. Let’s create a new interface called Eater :
Notice that it is very similar to an abstract class.
Let’s make Animal implement Eater :
The difference between abstract classes and interfaces is as follows :
Abstract class can have functions that do something, and interfaces can only define functions that must be implemented.
If you understand the above, you can read most of the code of Java programs on the internet.
Keep on learning
Arrays :
Tutorials usually teach arrays as soon as possible. We haven’t looked at arrays because we used ArrayList instead. Arrays are a native way to store lists of objects. I recommend you learn arrays because you will see them all the time. They look like this :
String[] array = new String[2];
array[0] = “Hey!”;
array[1] = “This is an array.”;
Exceptions :
We have looked at preventing exception (NullPointerException), but not how to handle them. If your code has an exception, you can catch it like this :
try {
// Problematic code here
} catch (Exception e) {
e.printStackTrace(); // Prints the red error text to the console
// Handle the problem
}
Threads :
Computers can run two or more processes simultaneously (in parallel). You should learn threading if you want your program to run fast, like games.
Remember : the best way to learn is to have fun!
If you have any questions, please write a comment. Thank you!