untitled
viviti

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: Often people use Strings as a data type, although they are not technically one you can usually treat them like one – especially in simple programs like were going to be writing.

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);
	}

}
top^^
Page by David woodford

Web Hosting · Blog · Guestbooks · Message Forums · Mailing Lists
Easiest Website Builder ever! · Build your own toolbar · Free Talking Character · Email Marketing
powered by a free webtools company bravenet.com