PJModule 1 - Introduction
PJModule 1 - Introduction
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
• It is often necessary to store a value of one type into the
variable of another type.
• In these situations the value that to be stored should be
casted to destination type.
• Assigning a value of one type to a variable of another type
is known as Type Casting.
• Type casting can be done in two ways.
– Automatic Type Conversion (Widening Casting)
– Explicit Type Conversion (Narrowing Casting)
Automatic Type Conversion
• 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.
• When these two conditions are met, a widening conversion
takes place.
• Ex : byte b = 10;
int a = b;
Explicit Type Conversion
• The conversion will not be performed automatically,
between a byte and 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.
• 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.
• Ex :
int a;
byte b;
// ...
b = (byte) a;
Automatic Type Promotion in Expressions