0% found this document useful (0 votes)
19 views46 pages

3.2 Variables

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views46 pages

3.2 Variables

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Variables

By Upekha Vandebona
What is a Variable?
 The variable is the basic unit of storage
in a Java program.
A variable is defined by the
combination of an identifier, a type,
and an optional initializer.
 In addition, all variables have a scope,
which defines their visibility, and a
lifetime.
Variable Declaration
In Java, all variables must be
declared before they can be
used.
The basic form of a variable
declaration is:

type identifier [ = value ][, identifier [= value ]


…];
Variable Declaration
 Type is one of Java’s primitive types, or the name
of a class or interface.
 The identifier is the name of the variable.
 You can initialize the variable by specifying an
equal sign and a value.
 Initialization expression must result in a value of the
same (or compatible) type as that specified for the
variable.
 Todeclare more than one variable of the specified
type, use a comma-separated list.

type identifier [ = value ][, identifier [= value ]


…];
Dynamic Initialization
Java allows variables to be
initialized dynamically, using any
expression valid at the time the
variable is declared.
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);

System.out.println("Hypotenuse is " + c);


}
}
Three local variables—a, b, and c—are declared. The
first two, a and b, are initialized by constants.
However, c is initialized dynamically to the length of the
hypotenuse.
The program uses another of Java’s built-in methods,
sqrt(), which is a member of the Math class, to compute
the square root of its argument.
The Scope and Lifetime of
Variables
 Java allows variables to be declared within any
block.
 A block defines a scope.
 Each time you start a new block, you are
creating a new scope.
 A scope determines what objects are visible to
other parts of your program.
 It also determines the lifetime of those objects.
The Scope and Lifetime of
Variables
 As a general rule, variables declared inside
a scope are not visible (that is, accessible)
to code that is defined outside that scope.
 Scopes can be nested.
 When this occurs, the outer scope encloses the
inner scope.
 This means that objects declared in the outer
scope will be visible to code within the inner
scope. However, the reverse is not true.
 Objects declared within the inner scope will not
be visible outside it.
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main

x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block

// x and y both known here.


System.out.println("x and y: " + x + " " +
y);
x = y * 2;
}
// y = 100; // Error! y not known here

// x is still known here.


System.out.println("x is " + x);
}
}
The Scope and Lifetime of
Variables
 Within a block, variables can be declared at
any point, but are valid only after they
are declared.
 If you define a variable at the start of a
method, it is available to all of the code
within that method.
 Conversely, if you declare a variable at the
end of a block, it is effectively useless,
because no code will have access to it.
For example, this fragment is invalid because count
cannot be used prior to its declaration:

// This fragment is wrong!


count = 100; // oops! cannot use count before it is
declared!
int count;
The Scope and Lifetime of
Variables
 Variables are created when their scope is
entered, and destroyed when their scope is
left.
 This means that a variable will not hold its
value once it has gone out of scope.
 Also, a variable declared within a block will
lose its value when the block is left.
 Thus, the lifetime of a variable is confined to its
scope.
Although blocks can be nested, you cannot
declare a variable to have the same name as
one in an outer scope. For example, the
following program is illegal:
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already
defined!
}
}
}
Type Conversion and Casting
Type Conversion and Casting
When assigning a value of one type
to a variable of another type, if the
two types are compatible, then Java
will perform the conversion
automatically.
For example, it is always possible to
assign an int value to a long variable.
Type Conversion and Casting
 However, not all types are compatible, and
thus, not all type conversions are implicitly
allowed.
 For instance, there is no automatic
conversion defined from double to byte.
 Fortunately, it is still possible to obtain a
conversion between incompatible types.
 To do so, you must use a cast, which
performs an explicit conversion between
incompatible types.
Java’s Automatic Conversions
When one type of data is assigned to
another type of variable, an
automatic type conversion will take
place if the following two conditions
are met:
 The two types are compatible.
 The destination type is larger than the
source type.
Widening Conversion
When these two conditions are met,
a widening conversion takes
place.
For example, the int type is always
large enough to hold all valid byte
values, so no explicit cast statement is
required.
Casting Incompatible Types
What if you want to
assign an int value
to a byte variable?
Casting Incompatible Types
This conversion will not be performed
automatically, because a byte is smaller
than an int.
This kind of conversion is sometimes
called a narrowing conversion, since
you are explicitly making the value
narrower so that it will fit into the target
type.
Narrowing Conversion
To create a conversion between two
incompatible types, you must use a
cast.
A cast is simply an explicit type
conversion.
It has this general form:

(target-
type) value
Here, target-type specifies the desired type to
convert the specified value to.
For example, the following fragment casts an int
to a byte. If the integer’s value is larger than the
range of a byte, it will be reduced modulo (the
remainder of an integer division by the) byte’s
range.

int a = 7;
byte b;
// …
b = (byte) a;
Cast Operator
To force the compiler to jam the
value of a bigger primitive variable
into a smaller one, you can use the
cast operator. It looks like this:
 long y = 42; // so far so good
 int x = (int) y; // x = 42 cool!
class MyFirstApp{
public static void main(String args[]) {
int a= 257;
byte b = (byte)a;
System.out.println(b);
}
}
Output?
Truncation
A different type of conversion will occur when a
floating-point value is assigned to an integer
type: truncation.
 As you know, integers do not have fractional
components. Thus, when a floating-point value
is assigned to an integer type, the fractional
component is lost.
 For example, if the value 1.23 is assigned to an
integer, the resulting value will simply be 1.
 The 0.23 will have been truncated.
Truncation
If the size of the whole number
component is too large to fit into the
target integer type, then that value
will be reduced modulo the target
type’s range.
Automatic Type Promotion in
Expressions
Inaddition to assignments, there is
another place where certain type
conversions may occur: in
expressions.
byte a = 40;
byte b = 50; The result of the intermediate term a*
byte c = 100; b easily exceeds the range of
either of its byte operands.
int d = (a * b) / c; To handle this kind of problem, Java
automatically promotes each byte,
short,
or char operand to int when
evaluating an expression.
This means that the subexpression
a*b is performed using integers—not
bytes.
Thus, 2,000, the result of the
intermediate
expression, 50*40, is legal even though
a and b are both specified as type byte.
Automatic Type Promotion in
Expressions
As useful as the automatic
promotions are, they can cause
confusing compile-time errors.
For example, this seemingly correct
code causes a problem:

byte b = 50;
b = b * 2; // Error! Cannot assign an int to a
byte!
Automatic Type Promotion in
Expressions
In cases where you understand the
consequences of overflow, you
should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of
100.
The Type Promotion Rules
 Java defines several type promotion rules that
apply to expressions.
 They are as follows:
 First, all byte, short, and char values are promoted
to int, as just described.
 Then, if one operand is a long, the whole
expression is promoted to long.
 If one operand is a float, the entire expression is
promoted to float.
 If any of the operands are double, the result is
double.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d *
s));
System.out.println("result = " + result);
}
}
Math.PI has a double
value
Thank You!

You might also like