Variables -- declaring and assigning values (2024)


Next: Simple output Up: 1 Programming Basics Previous: Comments Contents Before discussing input and output, includingSystem.out.println(...) which you used inHello.java, it will be helpful to cover the topic of variables. Youwill have come across the idea of variables in mathematics, and theconcept of a variable in programming is similar.

A variable is associated with space in the computer's memory that canhold a value (often a number). Each variable has a name, which youchoose, and subsequently use to refer to it.

You must start by declaring the variable, this gives thevariable a name and reserves some memory space to store whatever valuethe variable takes. It also tells the compiler what you intend thevariable to represent. This is known as the variable's type.For example a variable which always takes integer values, can bedeclared astype int in Java. For example the line of code

int i;

declares an integer variable (i.e. a variable of type int)which we have chosen to call i. As an int, it canstore any integer value between -2147483648 and 2147483647.

Java provides types to represent several kinds of number,e.g. integer and floating point, non-numerical things like text, andother more abstract things. These are listed on page. Youcan give a variable a longer name if you like, and it is usually agood idea to choose a word that explains what the variable is for. Theconvention is for variables to be named using lower case letters, orif the name consists of more than one word, that a capital be used atthe start of each word other than the first. You may also use numbersor an underscore _ in your variable names, but not at the beginningof the name. Examples of some well chosen and valid variable namesmight be total,maxValue, answer1.

Exercise1.2

(1 mark)

Now try the simple program below. As it contains

public class VarTry

you must type it in to afile called `VarTry.java'.

Compile and run VarTry in the same way that you did with the Helloprogram to check it prints out the number nine. Print the output andput it in your lab book.Read the explanation that follows and try to understand how it works.

/** * Name: * Date: * Exercise: 1.2 * Purpose: To demonstrate the declaration and simple uses of variables. */public class VarTry{ public static void main(String[] argv) { int i; // declares integer variable named i i = 9; // gives i the value 9 System.out.println(i); // print the value of i to the screen }}
You will see here how each line of code must end with a semicolon,; , (if you need to write a line of code that is longer thanthe width of the window you can continue it on the next line byomitting the semicolon until the end of the statement).

The line i = 9 gives the value 9 to variable i. This isknown as assigning a value to a variable -- i isassigned the value 9. It means that the space in thecomputer's memory associated with i now holds this value. Thefirst time a variable is assigned a value, it is said to beinitialised. The = symbol is known as theassignment operator.

It is also possible to declare a variable and assign it a value in thesame line, so instead of int i and then i = 9 youcan write int i = 9 all in one go. If you have more than onevariable of the same type you can also declare them together e.g.

int i, j; // orint i=1, j, k=2;
which can be a useful way of saving space. Where necessary you shouldadd comments explaining the meaning of the variables, both so it isclear to you if you come to look at your program at a later date, andto those marking your programs.

You will of course want to use many quantities which are not integers,and there are several different variable types which cover thesepossibilities. For real numbers there are two possibilities --float and double. As double uses twice asmuch memory as float to store values, it is more accurate.For real numbers you will probably mostly want to use double.All the variable types are described below.

byte Integer variable allocated only 8 bits4 (i.e 1 byte) of memory. May store values from -128 to 127.
short Short integer, allocated only 16 bits of memory. May take values from -32768 to 32767.
int Most commonly used form of integer variable, 32 bits. May hold any value in the range -2147483648 to 2147483647.
long Used if working with particularly large integers, 64 bits. Up to nineteen digits and a sign.
float Floating point real number, which must be written in the format 3.45, or 3.0e-5 -- that is they must include a decimal place and may include the letter e. What follows e is the power of ten, so the two examples mean 3.45 and 3.0 x 10-5 respectively. A float variable is 32 bits and holds a value between Variables -- declaring and assigning values (6)1.4 x 10-45 and Variables -- declaring and assigning values (7)3.4 x 1038, to eight significant figures.
double A 16 significant figure, floating point, real number, 64 bits. Values are written as for float, e.g. 5.8e59, and may take value between Variables -- declaring and assigning values (8)4.9 x 10-324 and Variables -- declaring and assigning values (9)1.8 x 10308.
boolean May take one of only two possible values, true and false. This is a logical truth variable (1 bit).
char A single character (this may be an upper or lower case letter, number or other keyboard symbols like :, # or ! for example.)

You can also create a String of characters.A String is like a word or a line of text and can include spaces,upper and lower case letters, numbers and other keyboard symbols.Strings are created in a similar way to variables, and the doublequote symbol " is used to mark the start and end of the text.You may for example write

String name = "Bob1";
This creates a String called name which stores `Bob1'.

You should be aware that there are some words which you may not use asnames for variables (or methods or classes for that matter) as theyhave a special meaning in Java. These are:
abstract, boolean, break, byte, byvalue, case, cast, catch,char, class, const, continue, default, do, double, else, extends,false, final, finally, float, for, future, generic, goto, if,implements, import, inner, instanceof, int, interface, long, native,new, null, operator, outer, package, private, protected, public, rest,return, short, static, strictfp, super, switch, synchronized, this,throw, throws, transient, true, try, var, void, volatile, while,widefp.

Exercise1.3

(6 marks)

With reference to the section above, say what type of variable wouldbe suitable for the following, and suggest a name for it too.

It may help to think of possible values and the range which would bevalid before you choose a type.

Example: the temperature of a room in C.Room temperature is likely to vary between 15 and 35 C but it can take any value inbetween including non-integers, e.g 20.37 C, so the type must be float or double depending on the accuracy required. A suitable variable name, following the conventions described above, would be roomTemp.

(i)
the number of pages in a book;
(ii)
the number of atoms in a book;
(iii)
the length of a side of a triangle in metres;
(iv)
your name;
(v)
whether or not a nucleus has decayed;
(vi)
the probability that it could have decayed.

Next: Simple output Up: 1 Programming Basics Previous: Comments Contents
RHUL Dept. of Physics
Variables -- declaring and assigning values (2024)
Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 6674

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.