Java Tutorial – Variables

You’re probably reading this post because you want to know how to work with variables in Java. Or maybe you’re just curious.

Well, you’ve come to the right place (or post if you will, hehe.)

You should know the following to be able to understand this tutorial:

  • The class template/structure
  • What classes are
  • How to use an IDE
  • How to write

I’ll talk about variables first.

What is a variable?

In simple terms, a variable is something that can contain a value. A good analogy is the box analogy. Imagine that a variable is a box. This box can contain something. Anything. You can also label the box anything you want, but it should be common sense to label it to something that’s relevant to its contents.

You wouldn’t give a box full of teddy bears a label that says “Equipment”. That wouldn’t make any sense! Therefore, when naming variables, you should follow conventions.

Let’s go back to the box analogy. Now imagine that there are only 8 types of boxes and each box can only contain an item of a category. For instance, a teddy type box can only contain teddy bears. That is basically what a variable is.

How to use variables

Enough with the teddy bears. Let’s get on to how to declare variables which is what you do when you want to store some sort of value.

Let’s start out by defining our class and the main method. Inside the main method, we’ll declare our very first variable!

public class Calculator {

public static void main(String[] args) {

private int num1 = 3;

System.out.println(num1);
}

}

NOTE: When naming variables, you can’t start the variable name off with a number. You should also start the name with a lowercase.

As you can see in the code snippet, a lot of stuff is happening here. We declared our variable inside our main method which every program needs in order to run.

public static void main(String[] args) {

This is how you define the main method. It’s quite important that you define the main method exactly like the code snippet above because this is what the computer will be looking for when you run the program.

Anything between the curly braces is code inside that particular method. You can also create your own methods, but I won’t go into detail on that yet.

As you can see in my first code snippet, I declared a variable called num1 and I assigned it a value of three.

So, the syntax for the decleration of a variable is as follows:

modifier variabletype variableName;

NOTE: You don’t need to give the variable a number unless you are going to use the variable for something. It makes sense that if you try to multiply two variables where one of them doesn’t even have a value, you’ll get an error, right?

Does that look complicated? What is a modifier? What are variable types? What is the semi-colon at the end? I’ll answer those questions right now.

First, the modifier. The modifier tells the computer who can access this variable. For instance, can other classes access this variable or just the class in which the declaration of the variable is in.

There are various different modifiers, but we’ll use public and private for the moment. We’ll move on to the others later on.

There exists conventions for the use of modifiers. Unless needed, variables should be private most of the time. This means that the variable can only be accessed from the class it was declared in, which in our case is the Calculator class.

The semi-colon at the end just marks the end of that line of code.

Variable Types

Let’s talk about what types of variables that exist.

These are all the variable types:

  • int
  • float
  • double
  • char
  • long
  • short
  • boolean
  • byte

Let’s start with the int type. This type of variable can have whole numbers from a range of -2,147,483,648 . 2,147,483,647. If you didn’t notice, this is the type I used to declare my num1 variable. Since I’m making a calculator, I’ll use int since it can hold fairly large numbers.

Let’s move on to the byte type. It has a minimum value of -128 to 127. That is a very small range, and I highly suggest refraining from using that data type if you want to make calculations with large numbers because that won’t work. Use int or long instead.

The long variable can hold whole numbers from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

The short data type can hold whole numbers from -32,768 to 32,767,

If you want to store numbers with decimals, you can use either float or double.

The float data type is normally used to save memory space because it’s less accurate, but shouldn’t be used if you want to make calculations as accurate as possible.

The double, on the other hand, is a data type which is usually used for precise calculations. You’d rather represent pi in a double data type than a float type since the double can have more decimal digits.

Now, the only data type here that can hold an actual character is the char type. This can hold one letter or digit. However, whatever you are assigning it, make sure the value is between double quotes.

Last not but least, let’s talk about the boolean variable which is actually just 1 or 0. True or false. You usually use this variable to check whether a certain condition is true or not. Here’s an example where you use the boolean variable to return true if the other variable has a value over 1 and false if it doesn’t.

public class Calculator {

public static void main(String[] args) {

private boolean numIsOver1;

private int num = 3;

if (num > 1) {
numIsOver1 = true;
} else {
numIsOver1 = false;
}
}
}

In this little code snippet, I used something called if-conditions. I won’t go into detail on what it is, but it’s used to check whether certain conditions are true or not. (I’m sorry if that was painfully obvious.)

Naming Conventions

There are certain “rules” that you should follow when naming your variable(s) as I mentioned earlier. First, when naming a variable you need to start the name with a lowercase letter. Variable names cannot start with a number.

If your variable needs a name that contains more than one name, you should write in camelCase. You start the name of the variable with a lowercase letter, then every next word starts with a capital letter.

There are exceptions for when it comes to starting a variable name with a lowercase letter. When declaring constants in Java, you should use only uppercase letters and separate every word with an underscore. Constants are basically variables that can’t change.

If you want to declare a constant, you must put the keyword final after the modifier. I’ll declare a constant which will hold how many hours there are in a day.

public class Calculator {

public static void main(String[] args) {

private final int HOURS_IN_A_DAY = 24; // Anything behind the two slashes are recognized as comments. They can be used to mark sections of the code, and for other documenting purposes.

}

}

Using conventions are important because it improves the readability of the document by a vast amount. That way, when other people reads your code, they’ll understand the code faster.

Using comments in Java is also a good idea because you can write what each variable is for, if needed. Although, some variables might be self-explanatory for as to why they are there.

This all might be a little complicated at the moment, but if you stick at it, it’ll become easier after some time. Just keep in mind that you only need to learn this once.

:)

Read More Post