[Java][Beginner]Working with Variables

Find tutorials on programming in here!

[Java][Beginner]Working with Variables

Postby Joe on Sun Aug 17, 2008 6:57 pm

In most programs, variables are an absolute necessity. I will be going over a few uses of variables in Java and how they can help benefit your program.

To explain different variables, I am going to quote one of my programming assignments I wrote previously this year.

Byte: -128 to +27 (Byte is a unit of measurement of information storage in the memory, it is 8 bits.)
Integer: -2,147,483,648 to + 2,147,483,647 (This stores whole numbers, it does not hold decimal places)

Long Integer: -9,223,372,036,854,775,808 to + 9,223,372,036,854,775,807 (this similar to Integer only can hold

more)

Float: -3.4 x 10¬¬38 to +3.4 x 1038 (This can stores a small amount of numerical data with decimal places)

Double: -1.7 x 10308 to +1.7 x 10308 (Similar to Float only can store more data)

Boolean: true \ false (This stores one or the other, some languages will have yes/no, or 1/0)

String: Strings are normally restrained to the maximum possible. (A string is a one dimensional array of ASCII

characters, although in some languages it may use things such as Unicode)

Char: \u0000 to \uffff (Char stores one letter at a time)


So as you can see, there are a few different variable types (data types) which we can use.

We will be focussing on most of them in this tutorial and also introduce some new things in Java.

First of all lets make a new class called myInfo and declare the variables.
Code: Select all
public class myInfo{

int age;
String name;
char initial;
boolean alive;
double bankBalance;

}


Above basically declares the variables and gives them a name.

Now lets add a constructor and give the variables a value.

Code: Select all
public myInfo(){
      age = 16;
      name = "Joe";
      initial = 'J';
      alive = true;
      bankBalance = 1000000;
   }

I may have exaggerated a bit on the last one, but as you can see the rest are values which represent myself.

Each one of the variables now has a value, so if we were to write the following piece of code:
Code: Select all
System.out.println(age);

16 would then be shown in the console.

So it may seem a bit pointless, you could just write 16 instead of wasting memory on a variable. But what if we were to get the information from another source? What if we were to get this information from a text file, or have the user enter their own information?

That could make these variables useful.

So lets make it so when the program runs, a window appears asking for a name.
To do this, we need to import a class into our own. To do this, add the following code on the very first line.

Code: Select all
import javax.swing.*;

public class myInfo {



This tells Java to import from the package javax and then a "sub package" of swing. It then tells Java to import all classes from that.

To keep things tidy we are going to tell Java exactly what class we wish to use. So change the first line to:
Code: Select all
import javax.swing.JOptionPane;


We now have access to use the JOptionPane class within our own program. This is great, it means we can use it instead of writing all of the code for it ourselves.

We need to edit our constructor to have the code which will ask you for your name.

Code: Select all
public myInfo(){
      name = JOptionPane.showInputDialog(null, "Please enter your name");
      age = 16;
      initial = 'J';
      alive = true;
      bankBalance = 1000000;
      System.out.println(name);
   }


As you can see, in the first line of the constructor we make name (our String we declared earlier) equal the Input Dialog we use from the JOptionPane class (showInputDialog is the method within the class), the showInputDialog has two parameters, one wants to know the parent of the dialog (in this case there isn't one, so we put null) and the other wants to know the text you wish to appear.

Now this code is in place, we need to make a main method and test out what we have done.

Code: Select all
   public static void main(String[] arg0){
      myInfo info = new myInfo();
   }


Once that code is in place, run your program and you should see a dialog asking you for your name, enter it and press "Ok" Now check the console and you should see whatever you typed in. This is a simple program with no validation, so it is possible to put in a null value.

You will notice if you try to do this with the age variable, you will get an error. This is because the InputDialog only wishes to work with Strings. This might not be great though, say you wanted to make a simple calculator which adds two values together after you input them, a String is not capable of doing this, but an int is.

Let's make a new class, and call it calculator. For this piece of code, a constructor is not required (a constructor will be in every class, if we code it or not, Java will put one in if there isn't one. It will be blank)

Code: Select all
import javax.swing.JOptionPane;
public class calculator{

public static void main(String[] arg0){

String first, second;
int one,two, total;


}

}


As you will notice, we have used a new way to declare variables, we have used a comma (,) to separate the names, this way we can have multiple String variables without repeating ourselves.
So now we have the variables we will use, we can have the InputDialogs appear and ask for our values

Code: Select all
first = JOptionPane.showInputDialog(null, "Please enter your first number");
second = JOptionPane.showInputDialog(null, "Please enter your second number");


But the problem still remains, we can't add these two variables together because they are both a String variable. This is where our int variables come in useful, Java has a built in method which allows us to convert from Strings to int.

This can be done by the following piece of code

Code: Select all
one = Integer.parseInt(first);
two = Integer.parseInt(second);


The variables one and two will now be equal to the input in first and second. This means we can then do something mathematically based with the input.

We can use the total variable to add the two together quite simply by writing this:

Code: Select all
total = one + two;


The variable named total will now hold the value of one + two (which isn't three :P.. unless you enter 1 and 2 in the original input dialogs)

This is great, but we have no way of showing the total to the user, we could simply use
Code: Select all
System.out.print(total);
but this isn't very user friendly. Instead we can use a MessageDialog (which is part of the JOptionPane class)

This is done by doing the following:

Code: Select all
JOptionPane.showMessageDialog(null, total);


Now when we run our program, we will have an input box appear on our screens asking for our first number, in my program I entered 5 and pressed Ok. I then received another input box appear and asked me for my second number, I entered 4 and pressed Ok. A message box then appeared telling me 9.

This is great, but 9 means nothing to me, I've entered my second number and then immediately left my computer for a few hours and forgot what I was doing, what if we could display what 9 actually meant? Well, we can, this is actually quite simple and can be done like this:

Code: Select all
JOptionPane.showMessageDialog(null, "Your first number was: "+one+" and your second number was: "+two+". "+one"+"+two+"="+total);


Displays the exact steps you took to receive your total. Notice when I used the variables in the MessageDialog I closed the " and immediately added a + this is because I wished to carry on the String, I then added another + after the variable I use if I had more to add. The + won't actually add anything up in the Message.

There is no validation on this simple calculator, which means if you enter anything other then numbers, your program will crash and you will get a NFE (Number Format Exception). I will tell you how to use Exception Handling in another tutorial.

Please post any questions or comments below.
Swivvet needs your help! If you wish to be a moderator on the forums. Please visit the hiring staff announcement topic for more information. Any help is appreciated.

Currently Learning:
Java [Experienced]
VBA[Dislike]
PHP[Average]
Wish to Learn:
C
C++
Experienced With:
HTML
CSS
Hardware
User avatar
Joe
Site Admin
 
Posts: 25
Joined: Wed Aug 13, 2008 7:45 pm
Location: Thetford, England

Return to Programming Tutorials

Who is online

Users browsing this forum: No registered users and 0 guests

cron