Java Tutorial
Variables
Introduction.
Variables are probaly the most usefull thing that you will have in any of your programs, whatever the laungage they are written in. A variable is simply a symbol(or word) that is assigned a value, the same as you would in a maths equation. These can be used to store data so that it can be accessed later in the program or so that checks can be performed on it in if and while statements(see late page).
Data Types
There are 8 data types in Java:- Integer: this is probly the most used. It stores a integral numerical(whole number) value between -2,147,483,648 and +2,147,483,647 so any number you are likley to store within your program will probably use this
- Byte: this is also for whole number values but is limited to 8bits of the memory so can only store values between -128 and 127. In reality you will never need to use this as your programs are unlikely to need to save memory by using less memory for variables.
- Short is the same but stores values between 32,767 and -32,768.
- long can hold much more and is given 64 bits meaning it can hold number between a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807
- float and double are used for decimal values, genrally double is best as it offers more decimal places.
- Char: this is the data type for holding characters such as 'h'. It can only hold one character and values are quoted in single quotation marks (') . For longer items of text use the object String which allows any length of data(see later)
- boolean: this is a logic data type which holds the value true or false.
Declaring Variables
Normally variables are declared in the first part of a program, before any of the functions but after the program has been defined, variables here can be accessed by any part of the program. You can also declared variables within the functions of the program. These cannot usually be accessed by other parts of the program unless they are defined as public.To declare a variable, on a new line put, the data type (note integer uses int) and then the name of the variable, remember that every line must end in a semi colon (;)
import java.io.*;
public class variables
{
//here we are going to define our variabes
int myInteger;
byte meByte;
double myDouble;
char myChar;
String myString = new String() //note when using string put = new String() when you declare it
public static void main(String[] args)
{
//we will now give our variable some values
myInteger = 2;
myByte = 7;
myDouble = 5.7;
myChar = 'h' //note put characters in single quotation marks (')
myString = “hello world” //note put strings in double quotation marks (“)
//we will now write our variables to the screen
System.out.println(“myinteger is: “ + myInteger);
System.out.println(“mybyte is: “ + mybyte);
System.out.println(“mydouble is: “ + mydouble);
System.out.println(“mychar is: “ + mychar);
System.out.println(“mystring is: “ + myString);
}
}
bravenet.com