0

My question can seem stupid... to me it really seems stupid. But I was shocked to see var keyword in a java code in video tutorial about android, you can see it here, on 38 minute for example...

So my question is, how it is possible to have var in java code and what does it mean in java, where we cannot have references without specific type?

Andranik
  • 2,729
  • 1
  • 29
  • 45

3 Answers3

8

The tutorial you're seeing is using Xamarin, which means they're writing the Android apps using C#, not Java.

There's no var keyword in Java before Java 10.

From Java 10 and on, you can use var to define local variables in methods and specific scopes.

Some examples:

var list = new ArrayList<String>();
list.add("Hello world");

Consumer<String> reader = s -> {
    var data = s.split("\\s+"); //data is of type String[]
    //use data...
    //...
}

You cannot do the following:

  • To define attributes of a class. Example

    class MyClass {
        private var foo = 5; //compile error
    }
    
  • As arguments in methods. Example

    public void method(var foo) { } //compile error
    
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
6

Actually, now that JDK 10 had been released on 2018/03/20 java supports the use of the var keyword to perform Local variable type inference.

This means that instead of doing this: String myName = "steeltoe";

You can just do var myName = "steeltoe";

Java will then infer that it is a string and as such is equivalent to the previous version just with less typing.

It should be noted that this does not break static typing as java still makes myName a String and as such will not allow you to break static typing by assigning it to a integer, like this myName = 1234;

SteelToe
  • 2,477
  • 1
  • 17
  • 28
0

// similar post:

C# var keyword equivalent in java?


JEP - JDK Enhancement-Proposal

http://openjdk.java.net/jeps/286

JEP 286: Local-Variable Type Inference

Author Brian Goetz

// Goals:
var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>
blueberry0xff
  • 3,707
  • 30
  • 18