Monday, March 26, 2018

Local variable in Java With Examples

In this post you will learn how to declare local variable and their behavior in the java program.In Java, there are many places to declare variables. You can declare them at the start of the program, within the main method, inside classes, and inside methods or functions. Depending on where they are defined, other parts of your code may or may not be able to access them.

 A local variable is a variable declared inside a method body, block or constructor. It means variable is only accessible inside the method, block or constructor that declared it.

Declaration of local variable:

Every local variable declaration statement is contained by a block ({ … }). We can also declare the local variables in the header of a “for” statement. In this case it is executed in the same manner as if it were part of a local variable declaration statement.

For example: for(int i=0;i<=5;i++){……}

In above example int i=0 is a local variable declaration. Its scope is only limited to the for loop.

Syntax:

methodname()
{
data type  localvarname;
-----------
-----------
}

Here method name is the name of method, Data Type refers to data type of variable like int, float etc and localvar Name is the name of local variable.

can we use local variables before they are initialized?Consider following program.

class LocalVariable
{
     public static void main(String[] args)
     {
          int a;
          System.out.println(a);
          a=10;
     }
}
If you try to compile above program, you will get a compile time error : i may not have been initialized. Because, any variable, global or local, should have some value before they are used. If you don’t initialize global variables explicitly, they take default values. But, If you don’t initialize local variables explicitly, they don’t take default values. They remain uninitialized until you initialize them explicitly. Therefore, local variables will not be having any value until they are initialized explicitly. Therefore, when you use local variables before they are initialized, you get compile time error. That’s why we can’t use local variables before they are initialized.

Note: To make the above program error free, put a=10 before System.out.println(a).

Important points to remember:

Access modifiers cannot be used for declaring local variables.
Default values are not assigned to a local variables in Java.
Local variables are declared in a blocks, methods or constructors.
Local variables are created when the block, method or constructor is started and the variable will be destroyed once it exits the block, method or constructor.

 

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...