Declaration
Declaration of local variables is similar to C/C++. A local variable can be declared anywhere in a method or block and can be initialized during declaration. It is not must to initialize a local variable during declaration but it must be initialized in the same block in which it is declared before the first use. More than one variables of the same type can be declared using single declaration statement by separating the variable names with comma.
Examples:
long x, y, z;
float d;
int a=0, b=10, c=5;
Example: The following program demonstrates the declaration and use of local variables.
Step 1: Open a new file named Local.java and type the following Java Program
class LocalVarDemo{
public static void main(String args[]){
int num1;
int num2 = 10;
int sum, product;
float f1 = 3.5f; f2 = 6.9f, sumf;
num1 = 15;
sum = num1+num2;
System.out.println("Sum of two integer values = " + sum);
sumf = f1+f2;
System.out.println("Sum of two floating point values = " + sumf);
}
}
Step 2: Compile above Java program using command javac Local.java in the command window.
Step 3: Execute the program using command java LocalVarDemo in the command window.
The output of the program will be:
Sum of two integer values = 25
Sum of two floating point values = 10.4
Declaration of local variables is similar to C/C++. A local variable can be declared anywhere in a method or block and can be initialized during declaration. It is not must to initialize a local variable during declaration but it must be initialized in the same block in which it is declared before the first use. More than one variables of the same type can be declared using single declaration statement by separating the variable names with comma.
Examples:
long x, y, z;
float d;
int a=0, b=10, c=5;
Example: The following program demonstrates the declaration and use of local variables.
Step 1: Open a new file named Local.java and type the following Java Program
class LocalVarDemo{
public static void main(String args[]){
int num1;
int num2 = 10;
int sum, product;
float f1 = 3.5f; f2 = 6.9f, sumf;
num1 = 15;
sum = num1+num2;
System.out.println("Sum of two integer values = " + sum);
sumf = f1+f2;
System.out.println("Sum of two floating point values = " + sumf);
}
}
Step 2: Compile above Java program using command javac Local.java in the command window.
Step 3: Execute the program using command java LocalVarDemo in the command window.
The output of the program will be:
Sum of two integer values = 25
Sum of two floating point values = 10.4
No comments:
Post a Comment