This article was written for people who were programming in other languages and would like to program in Java.
Roughly speaking, it seems that var can now be used in Java as well.
There are vars in multiple languages, but here we will focus only on Java vars. var stands for "variable". As the name implies, it is used when using variables. However, in Java it can only be used for local variables. var is like a type var variable name = variable content; However, unlike other variables, the contents of the variable are always required. This is because the type of var changes depending on the contents of the variable.
Specific examples include the following.
practice.java
class Main {
public static void main(String[] args) {
var i = 5; //int type
var msg = "Hello World!"; //String type
var c = 'Ah'; //char type
System.out.println(msg+i); //Hello World!5 is displayed
System.out.println(c); //A is displayed
}
}
For i, var is treated as an integer type int because the left side is an integer. Thus, var can only be used if you can clearly guess this language on the left side.
var is a type inference type, and a fixed type seems easier to understand, but it has a big advantage. That is, you can omit the type specification.
This is also difficult to understand if it is only sentences, so I will describe two examples.
practice_list.java
List<String> Obj1 = new ArrayList<String>(); //No var
var Obj2 = new ArrayList<string>(); //with var
practice_class.java
class Main {
public static void main(String[] args) {
longname_callclass cc = new longname_callclass(); //No var
var vcc = new longname_callclass(); //with var
}
}
class longname_callclass {
public void callmethod() {
System.out.println("Successful call");
}
}
Since the left type can be omitted in this way, the sentence becomes shorter and the result becomes easier to read.
practice_number.java
var i = 1; // int
var l = 3L; // long
var d = 1.0; // double
var f = 4.2f; // float;
Integer types allow int and long to be separated with and without L, so you can see the type by looking only at the numbers.
Recommended Posts