Variables in Java


A variable is a symbolic name for a location in memory. Memory is used to store string or numeric data. The value stored in memory (represented by a variable) can be modified and read during the execution of the Java program. To use a variable in Java, it must first be defined.

Defining a variable in Java is done by stating the variable type and by giving it a variable name (identifier).


Declaring Variables

Example Icon Example

To create an Integer {type} variable in Java with the variable name {identifier} of age, write the following code:

int age;

Alternatively, you can create many variables of the same type at once, as shown below:

int age, studNum, intNum, mark;


JAVA Variable Types

boolean Boolean value  1 only TRUE or FALSE
byte   1 0 to 255
char characters 2 all displayable ASCII characters
short integers (no decimals) 2 -32,767 to +32,767
int integers (no decimals)
(larger range)
4 -2,147,483,647 to +2,147,483,647
long integers (no decimals)
(larger range)
8 -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
float real numbers (decimal #) 4 virtually infinite
double real numbers (decimal #)
(larger range and precision)
8 virtually infinite





Scope of a Variable

When using variables in Java, it is important to know the SCOPE of the variables you are using.

The SCOPE of a variable refers to WHERE and WHEN a variable can be USED.

GLOBAL VARIABLES are variables that:

  • are declared in a global context outside of functions or blocks of code.
  • may be used anywhere in the program and can be used in all functions or blocks of code.

LOCAL VARIABLES are variables that:

  • MUST be declared in the context (method) that they are used in.
  • can be used only in the context (method) they are declared in.
  • are lost when their context is completed.


Simple Arithmetic in Java

Using the +, -, * and / operators (plus, minus, times and divide).

Generally, you will store the result of the mathematical expression in a memory location represented by a variable.

An assignment statement is used to store a value or string in memory or to perform a calculation and store the result in memory by using the assignment operator (=), which causes the operand (the variable) on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator.

Example Icon Example

The expressions...

age = 21;

avg = (80 + 56 + 75 + 82)/4;

NOTE: Be careful not to confuse the assignment operator (=) with the test for equivalence(= =) discussed later in the course.

The Modulus Operator

The division of two integers like 27 divided by 5 will result in an answer of 5. The modulus operator tells you the remainder. To find the remainder of the division of two integers like 27 divided by 5, you would use the modulus division operator %.

Example Icon Example

remainder = 27 % 5; // divides 27 by 5 and determines the remainder.

This would result in the 2 being placed in a variable called remainder.

Auto Incrementing and Auto Decrementing Variables

The most common mathematical formula used in programming languages is to take a variable and add (or subtract) the value 1 to it, and then store the result in the same variable. Adding 1 is called incrementing. Decreasing by 1 is called decrementing.

  • The increment operator (++) increases the value of the variable by 1.
  • The decrement operator (--) decreases the value of the variable by 1.

Example Icon Example

If you have a variable x and you want to increment it, you would use this statement:

x++; // increases the value stored in x by one. This is the same as the statement x=x+1;

If you have a variable x and you want to decrement it, you would use this statement:

x--; // decreases the value stored in x by one. This is the same as the statement x=x-1;

Visit Sun Microsystems for more on Java Operators.

Strings in Java

A String is a data type that can hold one or more ASCII characters (letters, numbers or special characters such as !).

It is possible to store no characters at all in a string - this is called the null string "".

To define a string variable use the same process as defining a numeric (int, double, etc.) variable as follows: Type Identifier;

Example Icon Example

To define a String {type} variable in Java with the variable name {identifier} of lastName:

String lastName;

This results in a String memory location (named lastName) being set aside for use later in the Java program.

Alternatively, you can create many String variables at once, for example:

String lastName, firstName, address, city;

String Literals vs. String Variables

In Java, there are String Variables and String Literals.

String Literals are Strings that are constant (they do not change) and are not stored in a variable. They are used to pass data into a method or to set the value of a variable. String literals are used all the time in methods:

For example ...
... where the word "hello" is a string literal passed into the println method.

String Variables are variables that can hold one or more ASCII characters (or none). String variables are used to store data that is non-numeric—you cannot do math operations on that data. Like every other variable in Java, you must create the String variable before you are able to use it.

Example Icon Example

String teamName;   
// creates a String variable called teamName ** Note: String has a capital S

teamName = "Ottawa Senators ";          
// sets the value of the String variable

System.out.println("Ottawa's team is the " + teamName);        
// displays "A great team is the Toronto Maple Leafs"

To store data in a String, that data must come from:

  • a string literal (e.g., name1 = "Ottawa";)
  • another string (e.g., name2 = name1;)
  • a joining of other strings (e.g., name = name1 + name2;)

Example Icon Example

name1 = "Ottawa";
name2 = "Senators";
name = name1 + name2;
//Displays Ottawa Senators




You may put all of these in one project if you like.

Assignment 1.6  - Area of a Circle
Find the area of a circle with a radius of 15 cm. Use variables to store the radius, pi, and area.
Calculate the Area using the formula Area = pi * radius * radius

Display the answer in sentence form using variables

The area of a circle with a radius of 15 cm is 706.5 cm(2)


Now Change the radius to 25, using the same variable.

Recalculate and Print.

Assignment 1.7 - Craig Anderson
Create a program that stores the string "Craig Anderson" in a string variable and stores 41 in an int variable. The program should display:
Craig Anderson is number 41 (using the variables)

Now change the Variables to different values and reprint.

Assignment 1.8 - Area of a Rectangle
Find the area of a 5.7 by 4.8 rectangle. Use variables to store the width, height, and area. Caclulate the area using a formula. Display the width, height, and area all on separate lines using variables.

Area of a Rectangle
width= 4.8
height= 5.7
The area is 27.36

Now change the Variables to different values and reprint.

Assignment 1.9 - Net Pay
Find the net pay(n) for an employee who works 40 hours (h) at $12.00 per hour (w) and has $5.00 (i) deducted for insurance and must pay 22% for tax (t). Display your answer in sentence form.

Assignment 1.10 - Carpet
Find the cost to carpet a room 8.5 m by 6 m if the carpet has a price of $19.95 per square meter. Display the answer in sentence form and use variables that are appropriate for the items you are storing.

Assignment 1.11 - Bill of sale
Write a Java program to calculate and print a bill of sale based on the following:

A shirt was purchased for $12.49 and was paid with a $20 bill.
Assign variables for the purchase price and amount given to the clerk.
Calculate taxes, (HST = 13%), total bill, and change.

Output the entire bill showing purchased price, taxes, total, and change.

Now add 2 additional items to your bill

Formating Dollar amounts

import java.text.DecimalFormat;

DecimalFormat df = new DecimalFormat("0.00");

DecimalFormat df = new DecimalFormat("$###,###.##");

output: $12,345.68


double pi = 3.141593

System.out.printf("%f %n ", pi); // --> "3.141593"
System.out.printf("%.3f %n", pi); // --> "3.142"
System.out.printf("%20s %.2f %n","The value of pi is", pi ); // --> "3.14"




Posting your work

1. Upload the Java Projects to your Gravelle Folder (Share with me only) and insert the Drive Folder (Insert > Drive Folder)

2. Upload your code image to your Gravelle Folder and embed on your site

3. Take a screenshot of your console output and embed on your site

4. Upload the rubric to your Google Drive Gravelle Folder and post at the top of your subpage

JAR files which are executable java files do not work on projects without a display so we will not use them in this assignment.