Local Variable in Java

This entry is part 6 of 34 in the series Core Java Course

Let’s learn more about local variables in Java. Variables that are declared inside Methods in a Java program are called local variables.

Rule for Local Variable

  • Local variables cannot use any of the access level since its scope is only inside the method.
  • Final is the Only Non Access Modifier that can be applied to a local variable.
  • Local variables are not assigned a default value, hence they need to be initialized.

 Example of Local Variable

 

Naming Convention

There are no specific rules for naming a local variable. All the rules of variables are applied to local variables.

Below mentioned are the rules for naming a local variable.

  • Variable names are case sensitive.
  • There is no limitation on the length of a local variable.
  • If a variable name is of one word only then all characters should be in lower case.

Bullet Point

  • Local variables can not use any of the access levels as they exist inside the Method only.
  • Final is the only non access modifier that can be applied to local variable.
  • Local variables don’t get a default value, hence local variables need to be initiated before they can be used.
Series Navigation<< Variables in JavaInstance Variable in Java >>

11 Comments Local Variable in Java

  1. Murari Varma

    Hello Mr. Gautam,

    At first, I would like to appreciate for the good work with your website. Well done.

    In the second program with class UserController String initialization is given 0. Isn’t that necessary to be given in double codes “0” ?

    String localVariable = 0;
    String localVariable = “0”;

    Murari Varma

    Reply
    1. Vivekanand Gautam

      Hi Murari,

      Thanks for your comment. I agree with you, it should be “0”.
      Article has been updated as per your suggestion.
      Do let me know if you find more typo error.

      Regards

      Reply
    1. Vivekanand Gautam

      Local variables are specific to Method only. Their lifecycle ends once execution of method competes. Hence their is no way we can access a local variable from other method in any way.

      Thannks

      Reply
  2. venkatareddy

    Can we call local variables are constants variables in a method (in java) ? both constants and local variables can’t changed……..dvrtechnopark.com

    Reply
  3. akhil

    hello,
    gautam
    in 2nd example datatype used string and we given integer value ,can we give like that.

    Reply
    1. J Singh

      Hi Akhil,

      You can definitely do that. Here “0” will be treated as String and not integer. And all operation will work like it is an String and not Integer. If you want it to treat like Integer you have to convert it in Integer first.

      Regards

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *