Local Variable in Java

Profile picture for user arilio666

In Java, a local variable is declared inside a method or a code block, such as a loop or a conditional statement. Local variables are only accessible within the block's scope in which they are declared. Local variables must be declared with a specific data type, such as int, double, or String. An initial value may be assigned to the variable at the declaration or later.

public void method() {
   int x = 10; 
   System.out.println(x); 
}

Here local variable is x which is defined within the method's scope.

Static Local Variable

public void method(){
static String test = "Luffy"; 
}

This will throw compile time error As we cannot declare a static local variable inside a non-static method.
Because it is directly associated with class level.

Static Local Variable Inside Static Method

public static void method(){
static String test = "Luffy";
}

Even though a static variable is declared inside a static method, the same compile-time error occurs.

Final

public void method(){
final String test = "Luffy";
}

We can define a final local variable inside the method. We need to associate the final with it.

Example

public class Calculator {
    public static void main(String[] args) {
        Calculator cal = new Calculator();
        String result = Calculator.test();
        System.out.println("result is  ::" + result);
    }
    public static String test() {
        String name = "luffy";
        return name;
    }
}

Here we are creating a static method and then calling the method after creating an object for the class.

package week1.day2;
public class Calculator {
    public static void main(String[] args) {
        Calculator cal = new Calculator();
        String result = Calculator.test("Luffy");
        System.out.println("result is  ::" + result);
    }
    public static String test(String onepiece) {
        String name = onepiece;
        return name;
    }
}

Here we created a method with a parameter string to be passed while calling the method.

Conclusion:

Local variables are essential, as we can see from this article.

Tags