[Part 2] Intro to Java - Variables

Before you read:

You should have read my first tutorial BEFORE reading this one! Some things will not make sense if you don't!

Now that you have completed a basic application, why don't we get into a major building block of coding; variables! Variables as mentioned in my previous tutorial are ways to store information for later use, much like in math. The difference from math is that they can store many kinds of information. Form strings of text to numbers, to even pictures, variables store information so you can manipulate or use the data later.

Step 1: Creating Variables

Variables can be created in Java with one simple line of code. For instance if I wanted to store my name in a variable, I would use:

String name = "mattrickcode";

Lets break this up:


This tells Java what type of variable. In this case its a string which is a string of text.


This is the name of the variable. It can be anything, but there cannot be two different variables with the same name.


Self explanatory tells Java that the variable equals the next value.


The actual value the variable is storing. It is in quotes because Strings need to be in quotes so Java knows its a string. You should know what the semi-colon means by now.

Step 2: Using Variables

Ok so thats great and all right? But what is the point of storing it if you don't use it? Using variables is actually very simple! All you need to do is type the name of the variable when you want to use it. For instance if I wanted to use the variable I set earlier, I would simply type "name" where I wanted to use it. Also keep in mind that variables are case sensitive.

Step 3: Now to the Coding!

Ok so you understand the basics of variables now. But what about using them in code? Why don't we take the example code from my last tutorial.

First off lets create a variable:

Under "public static void main(String args[]) {" put

String helloworld = "Hello World!";

and replace "System.out.println("Hello World!");" with:


And that's it! There may be many variables just like it, but that one is yours! You should get the idea of variables now.

Step 4: Umm...Whats the Point???

Now you may be wondering why at all you would use a variable? In this case, yes it is more efficient to do it the way in the first tutorial (it would make very, very, very little difference though). However, when you need to use the same number or string multiple times it can be useful or when you want to manipulate the variable to exactly how you want it. They are also useful for storing user input. Variables are essential for more advanced code.

Step 5: Final Notes

So now you know how to create and use variables. If you want a challenge, see if you can make variables to do math calculations for you. Good luck!

Next Up:

Coding Efficiency and Neatness





    • Trash to Treasure

      Trash to Treasure
    • Arduino Contest 2019

      Arduino Contest 2019
    • Tape Contest

      Tape Contest