2. Objectives
On completion of this period, you would be able to
know :
• To declare variables
• To initialize variables
2
3. Recap
• Classify data types in Java
• What is a literal?
• How many types of literals are in Java?
3
4. Declaration of Variables
• In Java, variables are the names of storage
locations
• After designing variables,we must declare them
4
5. Contd..
Declaration of Variables
• Declaration does three things
• It tells the compiler what the variable name is
• It specifies what type of data the variable will hold
• The place of declaration decides the scope of the
variable
5
6. Contd..
Declaration of Variables
• The syntax of declaration of a variable is
• type variable1,variable2,variable3,…,variableN;
• Here, type specifies the data type of which kind
and variables are separated by commas
• A declaration statement ends with a semicolon
eg. : int d, m;
6
7. Initialization of Variables
• A variable must be given a value after it has been
declared but before it is used in an expression
• This can be done in two ways
• By using an assignment statement
• By using a read statement
7
8. By Using an Assignment Statement
• A simple method of giving values to a variable is
through the assignment statement as follows
variable_name = value;
eg. : n=9,p=18;
8
9. Contd..
By Using an Assignment Statement
• It is also possible to assign a value to a variable at
the time of it’s declaration this in the form of
type variable_name = value;
• The process of giving initial values to variables is
known as ‘Initialization’
9
10. By Using Read Statement
• We may also give values to variables to the
keyboard using the readLine( ) method
eg. import java.io.DataInputStream;
class Example
{
public static void main(String args[])
{
DataInputStream in = new
DataInputStream(System.in);
int d=0;
10
11. Contd..
By Using Read Statement
double m=0.0
try
{
system.out.println(“ Enter any integer value”);
d = Integer. parseInt
( in.readLine());
system. out. println (“enter any double value”);
m = Double. valueOf
( in.readLine() ).doubleValue();
}
11
12. Contd..
By Using Read Statement
catch (Exception e)
{
}
System .out. println (“The integer value is”+d);
System.out.println(“The double value is”+m);
}
}
12
13. Contd..
By Using Read Statement
• The readLine() method reads the input from the
keyboard as a string and is converted to the
corresponding data type using the data type
• The keywords try and catch used to handle any
exceptions that occur during the reading process
13
14. Summary
• In this class we have discussed declaration and
initialization of variables
14
15. Quiz
1.Initialization of a variable can be done by using
a) an assignment operator
b) a read statement
c) both of the above
15