Java programming for beginners - Lesson 1 - Variables

in #programming6 years ago (edited)

Hello everyone, welcome to the second lesson in my Java programming for beginners tutorials series. The first lesson(lesson - 0) - IDE/Hello World can be found at - https://steemit.com/programming/@robertlyon/java-programming-for-beginners-lesson-0-ide-hello-world

This lesson will be focusing on Java variable and primitive data types. The aim of the lesson is to make you familiar with what a variable is and the different data types that are used in the Java language. I will also leave a challenge at the end for you to complete at the end of the lesson so you are able to test your knowledge.

For any further tutorials, I will assume that you are comfortable with the information from the previous tutorials.

Variables

What is a variable?

In programming, a variable is simply a place in memory that holds a specific value.

public class Variables {
    public static void main(String[] args)
    {
        int variableOne = 1; 
    }
}

So as can be seen above focusing on the line
int variableOne = 1;

This line of code creates a variable named variableOne and assigns the value of 1 to that variable name.
What this actually means is that a space in the computer's memory has been created, this piece of memory that has been created now holds the value 1.
Now the reason that the variable has a name is so that it is easier for us(the programmer to use that variable). So take a look at the code below to see what I mean.

public class Variables {
    public static void main(String[] args)
    {
        int variableOne = 1;
        System.out.println(variableOne);
    }
}

Thinking back to the previous lesson we know that System.out.println(); prints whatever is placed between the brackets to the console.

So if we think about the fact that I have placed the variable variableOne in between the brackets, it should come as no surprise that the output from this program is going to be 1.

Now onto the reason for the variable to have a name. When we create a variable it is because we want to store some data that we want to use in the future. This means that we need to remember where that data is when I comes time to utilise it. Now if we use an easy to understand name that is in a human language it is easier for us as humans to read and there is less chance of us making a mistake.
If we contrast this with how the computer actually stores this data in binary digits, this would make it extremely difficult for us to understand which variable we want to use.

Variable names

When it comes to naming variables Java has a few syntax rules to be aware of.

  • Case sensitive
    The Java programming language is case sensitive this means that variableOne and Variableone are two completely different variables and java will treat them as such.

  • Forbidden starting characters
    A java variable must start with a letter, the $(dollar sign) sign or an _ (underscore). Although the dollar sign and underscore are legal characters, they should generally be avoided.

  • Keywords
    A Java variable must not be a keyword, a list of keywords can be found and we will touch on most of these throughout the series. https://en.wikipedia.org/wiki/List_of_Java_keywords

  • Whitespace
    A variable name can not contain any whitespace, once whitespace has been introduced then the variable name has ended for example

int variable One = 1;

this would result in an error as "variable" and "One" are two separate words.

  • camelCase
    This is not a rule enforced by java but is a common naming convention used by most programmers. the rule is variable names start with a lowercase letter and each word in the variable name. Look below for an example.
int thisIsAnExample = 1;

As we progress I will introduce more conventions that will help to make your code more readable.

Primitive Data types

The Java programming language is what is known as a strongly types language, what this means is you have to tell Java how much memory you want to allocate to each variable. For example, if I want to store the value 1, it is going to take a lot less memory to hold that than the value 64545464.0098665.

To achieve this we use what is known as data types and below I am going to talk about the primitive data types that are used in the Java programming language.

Below is a table of all the different primitive types, plus String which is not a primitive data type but I will come on to that a bit later.

Data TypeValueMemory Allocation
byte-128 to 1278 bit
short-32,768 to 32,76716 bit
int-231 to 231-132 bit
long-263 to 263-164bit
float0.0f32 bit floating point
double0.0d64 bit floating point
booltrue or false-
char''\u0000'16 bit
Stringnull-

We will now take a closer look at each data type.

byte/short/int/long

These data types are all types of Integer, an integer can be thought of as a whole number. This is numbers such as 1, 5, -10, 99, numbers which do not have any fractional parts to them.
As you can see from the table above these integers all have different ranges for values that they can hold, for example, a byte is made up of 8 bits and if you know how to count in binary we know that a byte is 28 which equals 256. This means that a byte can hold 256 different values. As we can see above the byte data type starts at -128 and continues through to 127. Now if we add 127 to 128 and include 0 we get 256 different values. This logic applies to the other integer values as well.

The reason we have different values is so that we can make decisions about how we want our data stored, for example, if we want to store the value 10 in a variable and we know that the value is never going to go above 127 and never going to go below -128, we would want to store that value in a byte as this would only take up 8 bits in memory as opposed to creating a double every time and using 64 bits of memory, which is 8 times more memory.

One important thing to note about Integer numbers is if you try to store a number larger than the specified value of the data type then the number will loop back around and you will get an undisired result.

Here are some examples of these data types.

public class Variables {
    public static void main(String[] args)
    {
        byte aByte = 111;
        short aShort = 7890;
        int anInt = 19191919;
        long aLong = 8746374623846;
    }
}

float/double

Floats and doubles hold what are known as floating point numbers, the best way to think about these numbers are numbers with decimal points. One important thing to note about floating point numbers is that any numbers which are too large for the data type to handle will be rounded down to the nearest decimal point.

Floating point numbers follow the same logic as integers for storing their values.

Below are a couple of examples of floating point numbers.

public class Variables {
    public static void main(String[] args)
    {
        float aFloat = 6.345f;
        double aDouble = 7534543.943352309;
    }
}

notice the prefix after the value "f" for float and "d" for double this is a convention that helps to make your code easier to read and can also be used for integer values.

Boolean

a boolean value is a value which holds either true or false. This will be used in the future for conditional statements to test whether something is true or not.

here is an example below

public class Variables {
    public static void main(String[] args)
    {
        boolean aBool = true;
    }
}

char

a char value holds a 16 bit unicode character. Unicode is a standard which is the code for different characters that can be displayed on a computer screen. For example, a char variable can hold the letter 'a' but it could also hold the Unicode code that represents that character.

here is an example of a character variable.

public class Variables {
    public static void main(String[] args)
    {
        char aChar = 'a';
    }
}

You can learn more about Unicode here http://unicode.org/standard/WhatIsUnicode.html

String

a string is not actually a primitive data type but it is so common in programming that it needs to be mentioned early on. A string is actually made up of a group of chars. I will cover strings in a little bit more depth in later lessons.

Here is an example of a string

public class Variables {
    public static void main(String[] args)
    {
        String aString = "Hello World";
    }
}

Notice the double quotes around the string compared to the single quotes around the char.

I could go into more depth about the data types but the tutorial would go on for too long I suggest that you do some additional research into these data types and see what you can find out. I am now going to provide you with a short challenge to test some of your knowledge. I will provide an answer just below the question so that you can check your work.

Challenge

This is not going to be a difficult challenge as I have only covered a tiny part of the language.
I would like you to open up a project in your IDE and create variable for one of each type and name them appropriately using the correct naming conventions.

Please see below for my answer.

public class Variables {
    public static void main(String[] args)
    {
        byte aByte = 111;
        short aShort = 7890;
        int anInt = 19191919;
        long aLong = 8746374623846;
        float aFloat = 6.345f;
        double aDouble = 7534543.943352309;
        boolean aBool = true;
        char aChar = 'a';
        String aString = "Hello World";
    }
}

Conclusion

In this lesson we have covered quite a lot of new material, you should now have a basic understanding of how to create a variable in the correct ware. You should also have an understanding of the different primitive data types that are used in the Java programming language.

The next tutorial I have planned will cover the topic Operators and Conditional Statements, this is where it should get a little bit more exciting.

These tutorials will be constantly updated as I progress through the series

This is the first time I have created a tutorial so any feedback is welcomed. If you think there is anything I have missed or that I can add, then please feel free to comment below and I will consider adding it.

Thank you for reading and I hope that someone will get some use out of these tutorials.

Sort:  

I resteemed it.
I suggest to use upvote bots after 24 hours of posting, because your post may be discovered by curators, and it can get higher reward.

Okay, thanks

Great works, I wish you success

Thank you :)

you are welcome my friend, I have a new post, do not forget to visit ya, let me add the spirit in steemit,

Congratulations @robertlyon, this post is the second most rewarded post (based on pending payouts) in the last 12 hours written by a Dust account holder (accounts that hold between 0 and 0.01 Mega Vests). The total number of posts by Dust account holders during this period was 2003 and the total pending payments to posts in this category was $233.40. To see the full list of highest paid posts across all accounts categories, click here.

If you do not wish to receive these messages in future, please reply stop to this comment.

This post has received a 1.72 % upvote from @buildawhale thanks to: @robertlyon. Send at least 1 SBD to @buildawhale with a post link in the memo field for a portion of the next vote.

To support our daily curation initiative, please vote on my owner, @themarkymark, as a Steem Witness

Congratulations @robertlyon! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Coin Marketplace

STEEM 0.32
TRX 0.11
JST 0.034
BTC 66791.24
ETH 3239.69
USDT 1.00
SBD 4.22