It indicates that the variable
x is of type
7 also happens to have type
int, therefore the example is not that interesting.
Consider a more interesting example:
List<String> myList = new ArrayList<>();
Here, the compiler could infer that the type of
new ArrayList<>() on the right hand side is
ArrayList<String>. However, we might want to hide the concrete implementing class
ArrayList, and instead declare
myList to be of a more general type
List<String>, which is a supertype of
ArrayList<String>. This is useful if we want to prevent abstraction leak from the members of a class, or if we use
myList as a local variable, and for some reason want to set it to an
That's all I had to say on the question itself, but I want to give some context, and I want to argue that Java's current syntax is actually not too bad.
This syntax might seem verbose, one might think that one can often omit the type declaration on the left hand side. However, consider a language with stronger type inference.
For example, a closely related statically strongly typed language Scala tends to rely more on type inference. For example, if you write
var myList = List("foo", "bar")
it will automatically infer that
myList is a variable of type
But this often leads to unwanted results. For example, given the assignment
var myList = List.empty
the Scala compiler would happily infer that the right hand side is a
Nothing is a special type that signifies absurd impossible results "returned" by thrown Exceptions and Errors which break the normal program flow. You can't do anything with this variable. In order to make this variable useful, we have to write:
var myList: List[String] = List.empty
Now Scala compiler would understand that
myList is supposed to be
List[String], which is more general than the type inferred from the right hand side. As you can see: now you have both
val keyword and an additional
List[String]-type declaration on the left hand side, which is not necessarily much shorter than the corresponding Java version. It is actually longer, despite all the fancy type-inference magic. So, Java's syntax for variable declarations is... OK, at least it's not trivial to make it much better.