Sunday, March 8, 2015

The Variable

Phew, we've hit a lot of material lately, haven't we! However, the best is yet to come. We've learned about methods, classes, objects, etc...but all of that is pretty useless without today's concept, the variable.

Remember way back when in HelloWorld.java when we used System.out.println("Hello World!")? Wouldn't it be nice if we could have it print out something other than Hello World? We could edit the quotation marks and just change it manually, but what if we want to change it on the fly? What if we don't want to find that line of code and edit it manually every time? Turns out you can do it an easier way: using a variable.

Variables are objects that can store data and show data. I'm sure you know variables from math, where we can say "x=2", now plug X into the equation "4x-3" to get a result. The same holds true for code. We can say String statement = "Hello World!", and then use System.out.println(statement).

How do we create variables? We just say the "type" of the variable, (which we'll discuss in a minute), then whatever name you want to call it, and then what value it will hold. In Java, "=" is our assignment operator. Using = means you are setting the value of the object on the left to the value on the right. If we say "String aWord = 'hey'", that works. "hey" = String aWord does not work because "hey" isn't an object we can set a value to.

In essence, variables are just objects. When we create an object, we need to tell Java what kind of object we are creating. The most basic objects are called fundamental data types. Here are the most frequently used types:

  • int: An integer, with a value limit of around +- 32,000
  • long: An integer with a massive value limit of several million.s
  • double: A double-precision decimal number.
  • String: A phrase (or 'string') of text.
  • float: A more precise decimal with larger limits
  • char: A single charachter ($, %, a, .)
It's important to note that you can assign variable's values to other variables! If I have
int x = 10;
int y = 20;

I can then do:

int x = y;

And now x has a value of 20. However, you can only do this with objects of the same type! I can't assign a String to an int, or a char to a float.

Okay, let's put this good knowledge to use! Let's write a simple program to test our variables.

//I can use two slashes to make comments! You can type whatever you want
//And the compiler will completely ignore it. 
 
public class variableTester{

public static void main(String[] args){
System.out.println(statement);
System.out.println(number);
}

//Variables we use in our classes are called "instance fields"!
//Because we can make an object of our class and have more than one 'instance' of it.

String statement = "Low Key Coding is Bae";
int numberOfBlogViews = 67;
}

If we run this program, it will print out:

Low Key Coding is Bae
67

Perfect! That's the variable in a nutshell. Have fun!

~N

No comments:

Post a Comment