Variables
A variable is an item of data usedto store the state of
objects.
A variable has a:
data type:The
data type indicates the type of value that the variable can hold.
name:The
variable name must follow rules for identifiers.
Declaring and Initializing Variables
Declare a variable as follows:
<data type> <name> [=initial value];
Note:Values enclosed in <> are required values,
while those values in [] are optional.
Reference Variables Versus Primitive Variables
Two types of variables in Java:
Primitive
Variables
Reference
Variables
Primitive Variables:
Variables with
primitive data types such as int or long.
Stores data in
the actual memory location of where the variable is present
Reference Variables:
Variables that
store the address in the memory location
Points to
another memory location where the actual data is present
When you declare
a variable of a certain class, you are actually declaring a reference variable to the object with that certain class
Example of a reference variable and primitive variable
Suppose you have two variables with data types int and
String.
int num = 10; // primitive type
String name = "Hello"; // reference type
Example of memory handling of a reference variable and a
primitive variable
The following picture is the actual memory of your computer,
wherein you have the address of the memory cells, the variable name, and the data they hold.
Type Casting
Type Casting is the mapping type of an object to another.
Casting Primitive Types
Casting between
primitive types enables you to convert the value of one data from one type to another primitive type
Commonly occurs
between numeric types
There is one
primitive data type that you cannot do casting and that is the boolean data type
Types of
Casting:
Implicit Casting
Explicit Casting
Implicit Casting
Suppose you want to store a value of int data type to a
variable of data type double.
int numInt = 10;
double numDouble = numInt; //implicit cast
In this example, as the data type (double) of the
destination variable holds a larger value than the
data type (int) of the value, the data is implicitly
casted to the data type double of the destination variable.
Example of implicit casting:
int numInt1 = 1;
int numInt2 = 2;
//result is implicitly cast to type double
double numDouble = numInt1/numInt2;
Explicit Casting
When you convert a data that has a large type to a
smaller type, you must use an explicit cast.
Explicit casts take the following form:
(Type)valuewhere, Typeis the name of the type you are
converting to value. It is an expression that results in the value of the source type.
Explicit Casting Examples
double valDouble = 10.12;
int valInt = (int)valDouble;
//convert valDouble to int type
double x = 10.2;
int y = 2;
int result = (int)(x/y); //typecast result of operation
to int
Casting Objects
Instances of classes also can be cast into instances of
other classes, with one restriction. The source and destination classes must be related by
inheritance. One class must be a subclass of the other.
Casting objects is analogous to converting a primitive
value to a larger type. Some objects might not need to be cast explicitly.
Cast, (classname)object where, classname is the name of
the destination class and object is a reference to the source object.
Casting Objects Example
The following example casts an instance of the class
VicePresident to an instance of the class
Employee. VicePresident is a subclass of Employee with
more information, which here defines that the VicePresident has executive washroom privileges.
Employee emp = new Employee();
VicePresident vp = new VicePresident();
// no cast needed for upward use
emp = vp;
// must cast explicitly
vp = (VicePresident)emp;
Try It Out
Problem Statement:
Write a program that illustrates the implementation of
the automatic initialization of member
variables.
Code:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
public static void main(String[] args) {
Initialization app = new Initialization();
app.run();
}
// continued …
Refer File Name: Initialization.javato obtain soft copy
of the program code
How It Works:
The Initialization program illustrates the use of the automatic
initialization of member variables. It
displays the following output:
boolean: false
byte: 0
char:
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
Object: null
Tips and Tricks
List out the key points related to ‘instance’ (or member)
variables and ‘local’ variables.
Solution:
Instance (or
member) variables:
oAccessible anywhere in the class
oAutomatically initialized before invoking any
constructor
oStatic variables are initialized at class load time
oCan have the same name as the class
Local variables:
oMust be initialized explicitly and (Or, the compiler
will catch it.) Object references
can be initialized to null to make the compiler happy
oThe following code will not compile. Specify else part
or initialize the local variable explicitly.
public String testMethod(int a) {
String tmp;
if (a > 0) tmp = “Positive”;
return tmp;
}
Can have the same name as a member variable and
resolution is based on scope
Note:Here is the figure of allowable primitive conversion
byte -> short -> int ->long -> float ->
double
char
Summary
Automatic
conversion from narrow to widertype. For e.g., whenever division is
performed between a floating type and an integer type,
the integer type is
automatically converted (sometimes called promoted) to a
floating type and floating
arithmetic is performed.
Arithmetic with
boolean is not allowed.
Variables can be
initialized when declared
All Java
variables can be initialized when they are declared.
Member (or
instance) variablesare automatically initialized
If the
programmer doesn't initialize the variables declared inside the class but
outside of a method (often referred to as member variables as
opposed to local variables), they are automatically initialized to a default value.
The default
value for a boolean member variable is false.
Local variables
are not automatically initialized
Unlike instance
(or member) variables, if you fail to initialize a local variable, the variable is not automatically initialized.
Must initialize
or assign value to all local variables
Thus, the
programmer is responsible for either initializing all local variables, or assigning a value to them before attempting to access
their value with code later in the program.
Cannot access
value from uninitialized local variable
If you attempt
to access and use the value from an uninitialized local variable before you assign a value to
it, you will get a compiler error.
No comments:
Post a Comment