What is the difference between Local and Instance variable in Java?

Instance variable are declared inside a class but not within a method

Instance variables always get a default value. If you don’t explicitly

public class AddressBook {

  String firstName;
  String lastName;
  String phoneNumber;
  
}

Local variable are declared within a method or block of code

// firstName, lastName, street,locality, pincode, address are all local variable
public static String formAddress(String firstName, String lastName, String street, String locality, String pincode) {
  String address = firstName+" "+lastName +",\n"+street+", "+locality+",\n"+pincode;
  return address;
}

Local variable must be initialized before use!

Local variable do not get a default value! The compiler complains if you try to use a local variable before the variable is initialized. Let’s see an example on how the main() method have initialized the variables while calling the formAddress() method.

public class TestVariables {
  
  public static void main(String[] args) {
    String address = TestVariables.formAddress("John", "Kennedy", "Premium Street", "San Jose", "738727");
    System.out.println(address);
  }

  // firstName, lastName, street,locality, pincode, address are all local variable
  public static String formAddress(String firstName, String lastName, String street, String locality, String pincode) {
    String address = firstName+" "+lastName +",\n"+street+",\n"+locality+",\n"+pincode;
    return address;
  }
}

Output

John Kennedy,
Premium Street,
San Jose,
738727

 

 

Please follow and like us: