var keyword in Java

  • We declare local variables in a method with its data type.
        







  • From Java 10 or higher version onwards , we can use var keyword to declare local variables in a method. Same variables can be declared with var keyword like below.









  • Java compiler takes the variables type from it's initializer. 20 is integer value, so age data type is int. 
  • You can use var keyword to declare reference variables.




  • You can use var to declare variable inside for loop, forEach loop.

 

  • You can use var keyword as variable name also.








Restrictions :

  • You can't use var to declare a variable without initializing it. You can't use with null variables.
    










  • You can't use var to declare multiple variables in single declaration.
    




  • You can't use var to declare array initializer .
    




  • You can't use var to declare class level instance , static variables.










  • You can't use var keyword to declare method parameters.






  • You can't use var as method return type.










Conclusion:

var keyword is good addition to Java programming language. It shortens the variables declaration. This is all for today. Happy Coding 😀




2 comments:

Different ways to run Spring boot App

 What are the different ways to run Spring boot app ?