Java beginner course – A free and comprehensive guide to the basics of Java

Java beginner course – A free and comprehensive guide to the basics of Java

Java beginner course

Java is one of the most highly sought after programming languages, not to mention one of the two official languages for Android development. In this Java beginner course, we’ll go over the basics to provide you with a solid foundation and understanding of how the language works and what you can do with it.

Prerequisites

This Java beginner course assumes that you have no prior background in programming. In order to follow along however, you will need to use an online compiler. This will provide a terminal where you can enter Java code and then test your projects.

A good example can be found here: Repl.it. Otherwise, you can also find a number of Java compilers in the Google Play Store and Apple App Store.

Chosen your editor? Great, let’s get started!

Java beginner course part 1: Hello world!

Traditionally, when learning any new programming language, the first thing a tutorial should demonstrate, is how to print “Hello World!” to the screen. Depending on your chosen programming language, this can be a simple or complex process! Unfortunately, Java leans a little more toward the latter camp.

To achieve this seemingly basic task, you will need to enter the following code:

class Main {

  public static void main(String[] args) {

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

  }

}

Chances are you won’t need to write any of this though, seeing as most Java editors will populate new files with something to this effect for you. So, what does all this mean?

First, we are creating a “class” called “main.” Classes are chunks of code that are primarily used to create “data objects.” Data objects are comprised of properties and functions. For example, you could use a class to create a “bad guy” object in a program, and that would consist of its properties (2 legs, green color, lazer gun) and functions (walking, shooting, exploding). In Java, blocks of code that perform functions are called “methods.”

Also read: Java tutorial for beginners: write a simple app with no experience

However, classes can also be used to house sequences of statements that are carried out sequentially to make up a program. To define a class as the “main” class, the one that loads first when you hit run, it must also contain a method called “main”.

In Java, you group lines of code together using curly brackets and indentations. So if we say:

class Main {

Everything following that first curly bracket will be part of the main class and should be indented. We do the same thing for our main method, which means everything that is contained within both the class and the method will be double-indented. The method in this code is the block of code that starts “public static void”. The name that follows is what we want to call our method.

The code block ends when we use the opposite curly bracket. It’s important to remember how many curly brackets we opened, to ensure that we use the same number of closing brackets!

Arguments and syntax

You’ll notice that the method title is followed by a number of words in brackets. These are called “arguments” and they allow us to pass values in and out of the function. You don’t need to worry about that right now, just know that there always must be a “main” method, and that the main method must include those arguments.

Finally, we can use the statement (command) that prints “Hello world!” to the screen. We end that line with a semi-colon, which is how you end every line that doesn’t end with a curly bracket in Java. If you want to learn more about Java syntax and why it is the way it is, check our introduction to Java syntax for Android development.

Doing a thing: introducing variables

So, we’re 500 words into this Java beginner course and we’ve yet to write a line of code. Time to rectify that!

We’re just going to add two lines, and change one of the lines to say something new:

class Main {

  public static void main(String[] args) {

    String name;

    name = "Mr Pimples";

    System.out.println("Hello " + name);

  }

}

What we have done here, is to create a new “string” with the title “name” and the value “Mr Pimples”. A string is a type of variable, which is essentially a word that can represent a piece of data. Variables come in all shapes and sizes; including “integers” which are whole numbers, and “floats” which are numbers with decimal points.

You may remember variables from math, where:

“if a + 5 = 7, a = 2”

Here, “a” represents a value (2) and can thus stand-in for that value.

Why is this useful? Because it then allows us to change what our code does, simply by changing the value of the variable. For example:

import java.util.Scanner;


class Main {

  public static void main(String[] args) {

    String name;

    System.out.println("What's yer name??");

    Scanner reader = new Scanner(System.in);

    name = reader.next();

    System.out.println("Hello " + name);

  }

}

Scanner reader is an object that lets us get information from the user input. Here, we are asking the user to input their name then assigning the “name” string the text they enter. We can respond to the user using that name, rather than just displaying a generic message!

Notice that the variable sits outside of the quotation marks, showing that we want the value of that string, rather than the word “name”.

(Wondering what “import java.util.Scanner” does? We’ll get there in a moment, but well done for being observant!)

Using methods

Now you have an idea of what a variable is, it’s time this Java beginner course moved on to methods!

A method is essentially a block of code that performs one or more jobs. The usefulness of a method, comes from the fact it can be called from anywhere in your code. This means you can perform the same job multiple times, without needing to write the code repeatedly. That also means that you can more easily make changes to your program – as you only need to change that code once.

To see how this works, let’s write another variation of our “Hello World!” code:

class Main {

  public static void main(String[] args) {

    helloMethod();

  }

  public static void helloMethod() {

    System.out.println("Hello World!");

  }


}

This version of the program does the exact same thing it did before. The only difference is that the actual act of saying “Hello World!” is carried out in a separate method. This means we can repeatedly show the message to the screen by doing this:

public static void main(String[] args) {

    helloMethod();

    helloMethod();

    helloMethod();

  }

Sure saves time!

The other great thing about methods that you need to learn on this Java beginner course though, is that they can behave differently each time.

This is where “arguments” come in. Basically, an argument is a variable that you pass over to a method, which can then change the way the method acts. When you define the method, you simply create new variables and insert them in the brackets. As before, we do this by writing the type of variable (String) and then its name (userName).

Now, when we call the helloMethod method, we need to put a string inside those brackets. Now we can do this:

import java.util.Scanner;


class Main {

  public static void main(String[] args) {

    String name;

    System.out.println("What's yer name??");

    Scanner reader = new Scanner(System.in);

    name = reader.next();

    helloMethod(name);

  }


  public static void helloMethod(String userName) {

    System.out.println("Hello " + userName);

  }


}

Or this:

helloMethod("Mr Pimples");

helloMethod("Mrs Mumples");

helloMethod("Johnny");

Using classes

In the next part of this Java beginner course, we’re going to do something completely different: build a rabbit!

To do that, you’re going to create a new class outside of all the curly brackets so far:

class Rabbit {


  public String rabbitName;

  public String rabbitColor;

  public int rabbitWeight;


  public Rabbit(String name, String color, int weight) {

    rabbitName = name;

    rabbitColor = color;

    rabbitWeight = weight;

  }


  public void feed() {

    rabbitWeight = rabbitWeight + 10;

  }


}

Whenever you create a new class other than your main class, you will need to use a Method called a “constructor.” This constructor is used to define the properties of the “object” you are going to create. Remember: classes exist predominantly to create data objects, and in this case, we are creating a rabbit.

We therefore need to define a bunch of different variables for our rabbit, which we do outside of the method. Then we need to assign values to those variables by using them as arguments in our constructor. What this allows us to do is determine what our rabbit will be like.

(Notice that integers use the lower-case “int” whereas “String” is in upper case – this is unique to the String variable).

Now, back in the Main class and main method, we’re going to do the following:

Rabbit bunny1 = new Rabbit("Barry", "Brown", 10);

Rabbit bunny2 = new Rabbit("Jerry", "Black", 11);

System.out.println(bunny1.rabitName);

Basically, we’re using the constructor to make two separate “data objects” of the type “Rabbit.” We do this in just the same way we created our variables earlier, except that we’re using the constructor to assign multiple values.

The great thing about creating objects using classes is that you can build multiple objects from a single class. Here, the class works like a “blueprint.” So we can create two different rabbits with different names, different colors, and different weights!

Public methods

The other thing you may have noticed, is that we have a method in our Rabbit class called “feed.” Feed is a method that let’s us feed our rabbits, and all it does is add a pound in weight to our rabbitWeight variable.

Remember: objects have properties and functions. Or to put it another way: variables and methods!

So if we say:

System.out.println(bunny1.rabbitWeight);

bunny1.feed();

System.out.println(bunny1.rabbitWeight);

We’ll see that our bunny is one heavier when it prints out the second line!

Now, making data rabbits is not all that useful of course. But what would be useful would be to make a score counter in a computer game, to make users in a contact management tool, or to make any number of other abstract constructs.

The power of Java

Java course for beginne

The reason I really wanted to explain classes and objects in this Java beginner course, is that it will help you to better understand the nuts and bolts of Java and many other programming languages.

Because whenever you look at a piece of Java code, you will likely see many statements that rely on methods and variables from other classes. Java has a bunch of classes “built-in” and it’s easy to add more as you need them.

For instance: when we print to the screen by using:

System.out.println(bunny1.rabbitName);

We are referring to a class called System and then using its print line method! We’re then passing the string we want to print as an argument. That’s why we need so many words and full stops to achieve something seemingly quite simple.

The reason that “String” is capitalized, is that this is actually an object, rather than a “primitive type.” Hence, we can do things like String.length in order to find out how long the string is! Classes are generally capitalized.

Additional libraries and classes

We can easily extend the capabilities of Java without writing lots of extra code, by “importing” additional classes. This is what we did in order to get the input from the user:

import java.util.Scanner;

The importance of classes and objects also explains a lot of the “boilerplate” code (code that you write over and over again). The reason we say “public” is that we are telling Java we want other classes to be able to access the method. The opposite is “private” which means that the method is confined to the class, usually because it is concerned with some inner-workings that shouldn’t be tampered with.

The phrase “static” meanwhile tells Java that a method acts on the program as a whole, rather than an “instance” of a particular object. Our “feed”

Don’t worry if this isn’t all clicking just yet. It can take quite a while before Java starts making sense! But hopefully this gives you at least some idea as to what you’re looking at when you read any page of Java code.

Returning values

So, what does “void” mean?

Void tells us that a method doesn’t return any kind of value. This is as compared with methods that return a variable.

For example: what happens if we want to talk to our rabbit? In that case, we might create a method that returns a string, where that string contains the message that the bunny wants to share:

  public String rabbitSays() {

    String iSay = "Hi, my name is " + rabbitName;

    return iSay;

  }

When we define the method as a String, it’s important that it uses the return statement as the last line in order to return that string.

Now, we can treat that method as though it were any other string:

System.out.println(bunny1.rabbitSays());

Flow control

Before we wrap up this Java beginner course, there’s one more concept that’s important to understand: flow control.

Flow control means that we can change the code that runs depending on the value of a variable. This allows us to respond to the interactions provided by the user, or to other factors such as the time of day, external files, or how long the program has been running.

For example, we might assume that our bunny is hungry if he’s below a certain weight. He would therefore want to tell us to feed him!

This is where an “if” statement comes in handy. If statements are code blocks that run only when certain conditions are met. These conditions are placed inside brackets. So:

String iSay;

    if (rabbitWeight < 11) {

      iSay = "I'm hungry! Feed me!"; 

    }

Note that the symbol “<” means “less than.” Therefore, we only run the code in the code block if the rabbit’s weight is less than 11.

Another useful statement is “else” which we can use immediately after an “if” statement in order to define what happens when the conditions are not met:

  String iSay;

    if (rabbitWeight < 11) {

      iSay = "I'm hungry! Feed me!";  

    } else {

      iSay = "Hi, my name is " + rabbitName;

    }

Now our rabbits will tell us they’re hungry until they get fed. Once they are over 10lbs, they’ll stop telling us to feed them and tell us their names instead.

Here’s the entire code:

class Main {

  public static void main(String[] args) {

    Rabbit bunny1 = new Rabbit("Barry", "Brown", 10);

    Rabbit bunny2 = new Rabbit("Jerry", "Black", 11);

    

    System.out.println(bunny1.rabbitSays());

    bunny1.feed();

    System.out.println(bunny1.rabbitSays());


  }


}

class Rabbit {


  public String rabbitName;

  public String rabbitColor;

  public int rabbitWeight;

  public Rabbit(String name, String color, int weight) {

    rabbitName = name;

    rabbitColor = color;

    rabbitWeight = weight;

  }


  public void feed() {

    rabbitWeight = rabbitWeight + 1;

  }


  public String rabbitSays() {

    String iSay;

    if (rabbitWeight < 11) {

      iSay = "I'm hungry! Feed me!";  

    } else {

      iSay = "Hi, my name is " + rabbitName;

    }

    return iSay;

  }


}

While this particular program is little more than a novelty, it’s easy to see how you might adapt this into a full “pet simulator” like a Tamagotchi. Except – and I’m just spitballing here – the challenge would be that we have multiple different rabbits to manage. Add a “poop” function to make them hungry again, let them procreate, and you have a fun little management game.

Add some graphics and you’re onto a winner! Not bad for a Java beginner course!

Wrapping up the Java beginner course

Learn java development

All that is a lot to take in in one go, so you shouldn’t worry if you’re struggling to get your head around it all. That said, these are the most important concepts in Java and, once you grasp them, you’re well on your way to creating more useful apps.

In fact, that’s the best way to learn: choose a good starter project and get stuck in. Research what you don’t know and add to your knowledge as you go! Hopefully, you’ll find that it all makes a little more sense thanks to this Java beginner course.

OR you could check out our list of the best free and paid Android app development courses. There, you’ll not only learn everything you need to know about Java, but also how to use the Android SDK that bridges the gap between Java and the Android platform!


For more developer news, features, and tutorials from Android Authority, don’t miss signing up for the monthly newsletter below!

Stay up to date on all things Android Development

Join our developer crew to get a monthly developers newsletter curated by in-house experts!

By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.


source https://www.androidauthority.com/java-beginners-course-1146854/
Previous Post
Next Post

post written by:

0 Comments: