![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name is its identifier
Definition: A variableis a container in your program that is used to hold data of a particular type.
. You use the variable name to refer to the data it contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration
, which generally looks like this:
In addition to the name and type that you explicitly give a variable, a variable also has scopetype name. Scope is the life-span of the variable, it determines what sections of code can use the variable. The location of the variable declaration, that is, where the declaration appears in relation to other code elements, determines its scope.
The
MaxVariablesDemo
program, shown below, declares eight variables of different types within its
main
method. The variable declarations are red:The following sections elaborate on the various aspects of variables.public class MaxVariablesDemo { public static void main(String args[]) { // integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = true; // display them all System.out.println("The largest byte value is " + largestByte); System.out.println("The largest short value is " + largestShort); System.out.println("The largest integer value is " + largestInteger); System.out.println("The largest long value is " + largestLong); System.out.println("The largest float value is " + largestFloat); System.out.println("The largest double value is " + largestDouble); if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("The value of aBoolean is " + aBoolean); } }You will learn about the
- Data Types
- Variable Names
- Scope
- Variable Initialization
- Final Variables
- Summary of Variables
- Questions and Exercises: Variables
if
-else
statement used in theMaxVariablesDemo
program in the Control Flow Statementssection later in this lesson.
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |