Welcome back to Java Code Online. You must have used local variables a multiple number of times in your Java Code. Today we will discuss what actually is a local variable in Java.
A local variable in Java is one which is defined in a "method". Whenever you write your code, you make methods to do things in Java. Then you call those methods and perform the necessary operations. Any variable that is declared within a method is called a local variable.
I will take an example here:-
class JavaCode{
public int code(){
int codeLength = 20;
System.out.println("The Java Code length is:-"+codeLength);
return codeLength;
}
}
This is simple Java Code for declaring a class called JavaCode with a method called code(), which returns an integer. Here you can see that the variable "codeLength" is declared within method and is therefore a local variable.
Whenever you have to judge that a variable is local or not in Java, just ask yourself, that is the variable local to a method or not. If a variable is defined in a method or is local to a method, then it is a local variable otherwise not.
One more very important feature of local variable in Java is that they do not have an initial value. So if you declare a local variable in your code and do not initialize it, then that local variable can not be used. Mark my words here, if you use a local variable in Java before initializing it then it will give a compile time exception.
So to summarize the whole thing, there are two properties of a local variable in Java. They are:-
1. A local variable must be defined within a method.
2. A local variable must be initialized before using it in your code.
I hope the article helped you understand what is a local variable in Java. If you liked the article then do leave a comment. For more info on Java, keep buzzing Java Code Online.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.