Java Reference
In-Depth Information
tells the compiler to allocate appropriate memory space for the variable based on its data type.
The syntax for declaring a variable is
datatype variableName;
Here are some examples of variable declarations:
int
count;
// Declare count to be an integer variable
double
radius;
// Declare radius to be a double variable
double
interestRate;
// Declare interestRate to be a double variable
declare variable
These examples use the data types
int
and
double
. Later you will be introduced to addi-
tional data types, such as
byte
,
short
,
long
,
float
,
char
, and
boolean
.
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variablen;
The variables are separated by commas. For example,
int
i, j, k;
// Declare i, j, and k as int variables
Variables often have initial values. You can declare a variable and initialize it in one step.
Consider, for instance, the following code:
initialize variables
int
count =
1
;
This is equivalent to the next two statements:
int
count;
count =
1
;
You can also use a shorthand form to declare and initialize variables of the same type
together. For example,
int
i =
1
, j =
2
;
Tip
A variable must be declared before it can be assigned a value. A variable declared in a
method must be assigned a value before it can be used.
Whenever possible, declare a variable and assign its initial value in one step. This will
make the program easy to read and avoid programming errors.
Every variable has a scope. The
scope of a variable
is the part of the program where the
variable can be referenced. The rules that define the scope of a variable will be introduced
gradually later in the topic. For now, all you need to know is that a variable must be declared
and initialized before it can be used.
2.5
✓
✓
Identify and fix the errors in the following code:
Check
Point
1
public class
Test {
2
public static void main
(String[] args) {
3
int
i = k +
2
;
4 System.out.println(i);
5 }
6 }
Expressions
An assignment statement designates a value for a variable. An assignment statement
can be used as an expression in Java.
Key
Point
Search WWH ::
Custom Search