Using Variables

April 13th, 2009 | Tags:

Tutorial Description:

Learn how to use variables in your Java scripts.

Ok, now that we have a little feel of what a java program consists of, and how to print some text on the screen. We shall experiment with variables.

public class Variables undefined

Ok, by now your thinking, “Thats a doozy” or maybe you are thinking “How dumb does this guy think I am?”

int myInteger;
double myDouble;

These 2 lines mean that we are declaring (NOT INITIALIZING!) two variables. One of the variables is an int, the other a double [int = number; double = long number]

The name’s of the int is myInteger. The name of the double is myDouble. int, and double are called data types. They store certain kinds of data. Int variables hold variables with no decimals. Doubles hold whole numbers and decimals.

You can Google aata types and java to find out more of the data types. We will be working mainly with ints and doubles.

myInteger = 34;
myDouble = 23.32;

In these two lines we INITIALIZE the variables, setting them equal to numbers. Notice all of our statements end with simicolons. Note that if you would have done something like
myInteger = 34.1, this would bring up a compile error.
myDouble = 2, this would not bring up a compile error.

System.out.println("myInteger");    //This is a comment.
System.out.println(myInteger);    //Comments are ignored

In this line, we are going to print myInteger. Notice in the first line there are quotes around our variables. In the first case, it would print:
myInteger

But in the second case it would print:
34

This is because quotes print whatever you put inside of them. (there are a few exceptions)

The same thing goes for

System.out.println(myDouble);
System.out.println("myDouble");

Ok, now this line of code is a bit trickier:

System.out.println("My Numbers Added " + myInteger + myDouble); //prints 3423.32
System.out.println(myInteger + myDouble + " My Numbers Added");   //prints 57.32

In the first println, it will print 3423.32. This is because there is a string literal before our variables. The compiler thinks of these as strings, and just attaches them, one after another. Though in the second case, the variables come first, thus they are added together.

To fix the first one, we would have to put paranthesis around what we want added. Thus we’d use:

System.out.println("My Numbers Added " + (myInteger + myDouble));
No comments yet.
TOP