The Java variables tutorial – J012

by May 1, 2015




DeegeU Java Course

This video “The Java variables tutorial” is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Try at home

  1. Type in a program with different integer types
  2. Try creating smaller variable types, and then cause a widening conversion
  3. Try creating larger variable types, and then cause a narrowing conversion
  4. Try creating errors in your program and compiling it

Transcript – Java variables tutorial

We need to store values in our programs. These values can change based on the input from the program. Since the values can change, we need a symbol to represent them. We call the symbol a variable. So what I want to show you in this Java variables tutorial is what are variables in programming, and how do you use variables in a Java program.

what is a variable - java variables tutorial video - Free Java Course Online

A variable is just the concept you learned in Algebra applied to computers.

In this lesson, we’re going to look at what is a variable and how to create them. We’ve done this before, but we never called it out. We’ll also introduce a very important concept that you will see often in this course. Immutability. We’ll also look at constants, and how they differ from variables and immutable variables. And finally we’ll learn about casting variables to other types.

So lets start with what is a variable. We’ve already seen variables, although we weren’t calling them by that name. When we defined primitive values, we always used the pattern type, name, and value. The name is a variable in Java. Just like in algebra, the variable is a placeholder for a value. In this case, x is our variable. Just from looking at it, we know x represents 1. If 1 + x equaled 43, we’d know that x represented 42.

The variable can represent only one value at a time. It can’t be 5 and 42 at the same time. We can change the value, but the value can only be one value at a time.

You can think of a variable as a mailbox. Pretend a mailbox can hold only one piece of mail. Every box has a number. In Java, the mailbox address is called the reference. You’ll rarely ever need to know the actual reference value. That’s because we give variables a name. You just need to know the name of the variable you create.

A variable can be created to hold any primitive. That isn’t to say a variable can hold any primitive. When you define the variable with a type, that means for the life of the program, the variable is of that type. So once created an int, it is always an int. You can also have variables that hold other references. We’ll cover that later when we cover other Java types. Here we have an integer variable named i, an double variable named d, and a boolean variable named b.

java variable examples - java variables tutorial video - Free Java Course Online

Variables should be named to identify the concept it’s modeling. “x” is not a good variable name.

So the first part of any variable declaration is the type. In this case, int is the type. We give it a name. The name is the symbol for the variable. Now i is not a very good name. You want to give your variables a descriptive name, so it’s clear what the value represents. Most IDEs will autocomplete your variable names, so you’re not saving any typing by using short names.

So my i variable name here really should be something like count of widgets, numberOfDays, or mySpecialVariable.

As we saw in previous lessons, you can initialize your variable to a value like this. This is optional. You can provide a value later, but you should never use a variable until you know you’ve initialized it. For most cases, a variable will be initialized to a zero value. In some cases which we’ll cover later, it’s an error to use the variable before initializing it. If you know the value when you’re creating your variable, add it.

You can also set a variable to the value of another variable. That looks like this.

Another thing to do is, if you know your variable will never change for the life of the variable you’ll want to make it final. It’s like the gameshow who wants to be a millionaire. When you add the keyword “final”, you’re saying this is your final value. It’s not going to change. When a variable can’t change, it’s said to be immutable. You’ll want to remember that word. It’s going to come up often in this class. Immutable means the value cannot change once it’s set. Normal variables can change as often as you need. So you’re probably wondering, where’s the value in this example?

Well, you just define it like we have already. You can assign it to the value you want, when you create the immutable variable.

You can also define a final variable, and delay the variable assignment to later in the code. In this course, when you see a block like the blue one here, that means pretend there’s lots more Java code here, but the exact code is not relevant to the discussion. So in this example we’re setting the variable value much later after the definition.

Still you can only set it once.

Let’s try this in code. We’re going to define a variable called handCount. We have two hands. Now look at what happens when we try to change the value. We get the error cannot assign a value to the final variable handCount. Now we might not know the number of hands in advance. But once we do, it shouldn’t change. We can modify the code to declare the variable. Then we’ll add another dummy variable in between. And now we’ll assign 2 to handCount. That works. If I try to change it on the next line, we’ll get the error again.

You want to do this every time you’re working with a variable you know won’t change while you’re using it. This allows Java to make some optimizations, and possibly make your application faster.

java constant example - java variables tutorial video - Free Java Course Online

π is an example of a constant that will not change over the life of your program.

Sometimes there’s the case where you know the variable will never change. Like the constant pi. It’s always going to be 3.1415. It’s not going to change in your program ever. For this, you’ll want to use a constant. Now it would have been nice if Java used a keyword like const, but they didn’t. They reserved the keyword, but it doesn’t do anything. No, to declare a constant you’ll need to use the keyword “static” with the keyword “final“. “static final” means constant in Java. Static really means this is set at compile time. But in this case, think of “static final” as meaning constant. If you know your variable value will never change ever, tell Java it’s a constant. The difference between an immutable variable and a constant is, you know the value of a constant at compile time. An immutable variable isn’t known until runtime.

Now I said earlier that once you give a variable a type, you can’t change it. That’s because Java is a statically typed language. This means the value is typed at compile time. It cannot change, and if you want to treat it as a different type, you have to explicitly tell Java to do so.

The opposite of statically typed is dynamically typed. That means the variable can change type at runtime. An example would be Perl. The reason Java chose to be statically typed, is because you can detect many stupid type errors at compile time. I say stupid, because you usually never want to change the type of a variable. If you did change it, that’s likely a typo error.

There are cases where you want to change the type. For example, you have a short, but you’re trying to use it somewhere that expects a long. You can tell Java, hey pretend this integer is a long using something called casting. When you go from smaller data type to bigger data type, you’re making a widening conversion. This always works for the number types. So if you start somewhere in these arrows and move to the right, Java will do it without complaint.

The other direction is another story. Going from bigger to smaller is called a narrowing conversion. For example, you start with a long and try to put it into a short. It doesn’t matter if the number is small enough. Java will give you a compile error. You’ll get the lossy conversion error we saw in previous lesson.

Let’s look at this in code. We’ll create a long value, call it meaningOfLife. We’ll assign the value 42. Then we’ll create a short, called shortVersion, and try to give it the value of meaningOfLife. And Java complains. We can’t compile. So what do we do?

When you know it’s ok, you can tell Java “hey, man, I know what I’m doing here”. We do that with a cast. To cast a variable, we put the type we want in parentheses. So in this case, we are casting our long to a short.

Let’s go fix our code. So this won’t compile. But if we add a cast to short, it works. We’re telling Java, we are in control. Now this also means Java is giving you enough rope to hang yourself. Lets see what happens when we try to put a really big number into a short. We run it, and we get a result that isn’t what we wanted. Basically, Java accepted that we knew what we were doing, and tried to stuff it in there. It didn’t work out. So we get the bits that did fit.

floats vs ints  - java variables tutorial video - Free Java Course Online

Floats and ints are the same size, but they really are not interchangeable.

There’s one other thing to show you. Remember ints and floats are stored differently. Even though they both fit into 32 bits, they are represented differently and have different ranges.

So if we take a big integer like 1234567890, and stuff it into a float, it works. Java won’t even protest. So let’s print out the difference between the two. The answer should be 0. And we get -46. Lesson learned. Be careful when converting between integer
and floating point numbers.

So that wraps up variables. We’ve looked at how to define them, how we can make them immutable, and how we can make them a constant.







Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • Image: Hand Puddles (S. Hodgson)
    https://www.flickr.com/photos/craiglea/3260608582 – CC 2.0

Music: “Daily Beetle” Kevin MacLeod (incompetech.com)
Licensed under Creative Commons: By Attribution 3.0
http://creativecommons.org/licenses/by/3.0/

Get the code

The source code for “Java variables tutorial video” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don’t miss another video!

New videos come out every week. Make sure you subscribe!

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This