[Java] About java var

less than 1 minute read

java variable declaration var

An organized memo for studying Java Silver…

How to use var

  • Introduced from SE10
  • Local variable type inference -Data type is inferred according to the value on the right side

var v1 = "hoge"; // Treated as a String
var v2 = 123; // treated as an int
  • Since it is variable type inference, declaration only cannot be done -> type inference cannot be performed unless a value is assigned -Therefore, null assignment is not possible
var v3; // this is a compilation error
var v4 = "huga"; //ok
var v5 = null; // Again a compilation error
  • Cannot declare multiple variables

int i1 = 1, i2 = 2, i3 = 3; //ok
var v6 = 6, v7 = 7, v8 = 8; // compilation error
  • Cannot be used as a method parameter type

String piyo(var val){
...
// compilation error
}