One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?
15 Answers
There is none. Alas, you have to type out the full type name.
Edit: 7 years after being posted, type inference for local variables (with var
) was added in Java 10.
Edit: 6 years after being posted, to collect some of the comments from below:
The reason C# has the
var
keyword is because it's possible to have Types that have no name in .NET. Eg:var myData = new { a = 1, b = "2" };
In this case, it would be impossible to give a proper type to
myData
. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.var
is not the same asdynamic
.var
iables are still 100% statically typed. This will not compile:var myString = "foo"; myString = 3;
var
is also useful when the type is obvious from context. For example:var currentUser = User.GetCurrent();
I can say that in any code that I am responsible for,
currentUser
has aUser
or derived class in it. Obviously, if your implementation ofUser.GetCurrent
return an int, then maybe this is a detriment to you.This has nothing to do with
var
, but if you have weird inheritance hierarchies where you shadow methods with other methods (egnew public void DoAThing()
), don't forget that non-virtual methods are affected by the Type they are cast as.I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
class Foo { public void Non() {} public virtual void Virt() {} } class Bar : Foo { public new void Non() {} public override void Virt() {} } class Baz { public static Foo GetFoo() { return new Bar(); } } var foo = Baz.GetFoo(); foo.Non(); // <- Foo.Non, not Bar.Non foo.Virt(); // <- Bar.Virt var bar = (Bar)foo; bar.Non(); // <- Bar.Non, not Foo.Non bar.Virt(); // <- Still Bar.Virt
As indicated, virtual methods are not affected by this.
No, there is no non-clumsy way to initialize a
var
without an actual variable.var foo1 = "bar"; //good var foo2; //bad, what type? var foo3 = null; //bad, null doesn't have a type var foo4 = default(var); //what? var foo5 = (object)null; //legal, but go home, you're drunk
In this case, just do it the old fashioned way:
object foo6;
-
11@Mike Caron: C# has [default] non-virtual calls and operators are not virtual so...
var p = new X(); p.Z()
is not the same asSuperX p = new X(); p.Z()
for all X and and SuperX, even thoughX : SuperX
. Withvar
the static type ofp
is alwaysX
in first example above, but alwaysSuperX
in the second example. A subtle but important difference to be aware of. But your answer is very correct :-)– user166390Dec 15, 2010 at 20:10 -
206@Jon Hanna:
var
does not make the code less clear. Rather the opposite in my opinion. Why for example write the type two (or even three) times on the same row when you declare and instantiate it (RadioButton radioButton = new RadioButton();
)?var
makes you rather think twice when you are naming your variables because it turns the focus on the functionality rather than the type (for exampleUserCollection collection = new userRepository.GetUsers();
rather more naturally turns intovar users = userRepository.GetUsers();
). If you thinkvar
is unclear it is just because unused to it. Jul 6, 2012 at 10:19 -
4@MartinOdhelius
var
very definitely can make code clear used well, but it can also make it unclear too used badly; like many formatting options. The balance differs depending on how much you use anonymous objects and generics, neither of which existed in .NET 1.0, making it less useful as a hypothetical keyword in the first version of C♯. I would only name aRadioButton
radioButton
in the case of a factory or helper method where the only thing significant about the button was that it was aRadioButton
, otherwise that's madness with or withoutvar
. Jul 6, 2012 at 10:32 -
6@Jon Hanna: I was once as critical to
var
as you, if not more, but I have changed my opinion, and perhaps it is as simple as an question of different opinions, because I still think you are wrong when you say it is a matter how much you are using anonymous objects and generics ;) The type declaration is most often just code noise, if you can not understand the code without it the code is probably unclear in either case. Jul 6, 2012 at 11:51 -
4You're confusing var with anonymous types.
var
itself simply asks the compiler to infer the type from the assignment; it's syntactic sugar. I was skeptical of it at first, but I use it religiously and have yet to encounter a time where it caused confusion. It removes redundancy when instantiating and removes the need to check the type when referencing. There is no JAVA equivalent as of JAVA 9.– RobearJan 23, 2018 at 19:51
If you add Lombok to your project you can use its val keyword.
-
1@rightfold: Objects whose reference is
final
are not necessarily immutable. Considerfinal StringBuilder strB = new StringBuilder("My reference is final"); strB.append("I'm not immutable");
Mar 24, 2014 at 16:52 -
1Since lombok v1.16.12 there is also experimental support for
var
. projectlombok.org/features/experimental/var.html May 29, 2017 at 18:26 -
@MatthiasBraun your example is wrong. In this case StringBuilder class itself is immutable, you just adding string value to its internal structure using method, this is totally legal. Aug 11, 2017 at 11:04
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>
-
-
@PeterMortensen Yes. JEP 286 has been accepted and published in JDK 10 (see 286 under Features at openjdk.java.net/projects/jdk/10). Apr 1, 2018 at 12:42
With the release of JDK 10 on March 20, Java now includes a var
reserved type name (not a keyword—see below) as specified in JEP 286. For local variables, the following is now valid in Java 10 or higher:
var map = new HashMap<String, Integer>();
The var
reserved type name in Java is nearly identical to the var
keyword in C# in that both allow for implicit typing (see below for important differences). var
in Java can only be used for implicit type inference in the following contexts (as enumerated in JEP 286: Goals):
- local variables with initializers
- indexes in the enhanced for-loop
- locals declared in a traditional for-loop
Therefore var
cannot be used for fields, return types, class names, or interface names. Its rationale is to remove the need for including long type names when declaring and defining local variables, as stated in JEP 286 (authored by Brian Goetz):
We seek to improve the developer experience by reducing the ceremony associated with writing Java code, while maintaining Java's commitment to static type safety, by allowing developers to elide the often-unnecessary manifest declaration of local variable types.
var
Scoping in Java
It should be noted that var
is not a keyword in Java, but rather a reserved type name. As quoted from JEP 286:
The identifier var is not a keyword; instead it is a reserved type name. This means that code that uses var as a variable, method, or package name will not be affected; code that uses var as a class or interface name will be affected (but these names are rare in practice, since they violate usual naming conventions).
Note that since var
is a reserved type name and not a keyword, it can still be used for package names, method names, and variable names (along with its new type-interference role). For example, the following are all examples of valid uses of var
in Java:
var i = 0;
var var = 1;
for (var i = 0; i < 10; i++) { /* ... */ }
public int var() { return 0; }
package var;
As quoted from JEP 286:
This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.
Differences Between var
in Java & C
This is one notable difference between var
in C# and Java include the following: var
can be used as a type name in C# but cannot be used as a class name or interface name in Java. According to the C# documentation (Implicitly Typed Local Variables):
If a type named
var
is in scope, then thevar
keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.
The ability to use var
as a type name in C# creates some complexity and introduces some intricate resolution rules, which are avoided by var
in Java by disallowing var
as a class or interface name. For information on the complexities of var
type names in C#, see Restrictions apply to implicitly-typed variable declarations. For more information on the rationale behind the scoping decision for `var in Java, see JEP 286: Scoping Choices.
-
Is there any difference between Java and c# in that you can't use
var
for fields or return types? Why is it important to note? Apr 4, 2018 at 10:47 -
@user1306322 In that context, no.
var
in Java cannot be used for fields or return types. This is important because this restriction makesvar
context-sensitive, where it can only be used in some contexts (local variables) and not others. This is not necessarily a difference between Java and C# that should be noted, but an important restriction in general when usingvar
in Java. Apr 4, 2018 at 11:15 -
I just looked up and it seems like in c# you can make
var
a class name and use it as such. Technically it is a "context keyword" in case of c#, but in Java it seems that you can't do the same. Correct me if I'm wrong. Apr 4, 2018 at 11:21 -
1You are correct. You cannot use
var
as a class name or an interface name in Java (which is not common anyway), but you can use it for variable names, method names, and package names. For example,var var = 1;
is a valid Java statement but trying to declare a class aspublic class var {}
results in an error:as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations
. I've updated the answer above to go into more detail on the rationale behindvar
in Java and its differences withvar
in C#. Apr 4, 2018 at 13:30
I have cooked up a plugin for IntelliJ that – in a way – gives you var
in Java. It's a hack, so the usual disclaimers apply, but if you use IntelliJ for your Java development and want to try it out, it's at https://bitbucket.org/balpha/varsity.
-
It'd be great to have a keyboard shortcut to fold/unfold declaration types in the current editor. Great plugin though.– hotkeyAug 17, 2015 at 14:50
-
2@hotkey This uses IntelliJ's built-in code folding, so you can unfold everything with Ctrl-Shift-NumPadPlus. When the cursor is on a line that contains a folded variable declaration, you can Ctrl-NumPadPlus and Ctrl-NumPadMinus to fold/unfold the declarations in the current method. Folding all declarations is a bit awkward, you have fold everything (Ctrl-Shift-NumPadMinus) and then unfold everything again (Ctrl-Shift-NumPadPlus).– balpha ♦Aug 17, 2015 at 14:57
It will be supported in JDK 10. It's even possible to see it in action in the early access build.
The JEP 286:
Enhance the Java Language to extend type inference to declarations of local variables with initializers.
So now instead of writing:
List<> list = new ArrayList<String>();
Stream<> stream = myStream();
You write:
var list = new ArrayList<String>();
var stream = myStream();
Notes:
var
is now a reserved type name- Java is still commitment to static typing!
- It can be only used in local variable declarations
If you want to give it a try without installing Java on your local system, I created a Docker image with JDK 10 installed on it:
$ docker run -it marounbassam/ubuntu-java10 bash
root@299d86f1c39a:/# jdk-10/bin/jshell
Mar 30, 2018 9:07:07 PM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
| Welcome to JShell -- Version 10
| For an introduction type: /help intro
jshell> var list = new ArrayList<String>();
list ==> []
-
3Beware, the code you provided (before/after
var
) is not equivalent. In thevar
examplelist
is of typeArrayList
, not aList
.– GiliJul 27, 2018 at 2:55
A simple solution (assuming you're using a decent IDE) is to just type 'int' everywhere and then get it to set the type for you.
I actually just added a class called 'var' so I don't have to type something different.
The code is still too verbose, but at least you don't have to type it!
-
When you say "decent IDE" is Eclipse* excluded? -- this does not appear to work in Luna (at least when I just tried it with
int
) -- am I missing something? (*: while I would never call Eclipse a decent IDE, I can't judge for others...) Sep 23, 2014 at 5:00 -
@BrainSlugs83 dunno I'm using IDEA, not really used eclipse before. Doesn't it correct types for you? I'm used to c#/visual studio/resharper which is like IDEA except it actually works properly! In all the jetbrains' ones you can press alt-enter to get a list of suggestions when there's an error - so setting type to int introduces an error you can alt-enter on and get it to sort the type out– JonnyRaaSep 23, 2014 at 8:05
As of Java 10, the equivalent is ... var
.
-
Are there any differences? I mean you know better than to write short answers like this, what with your rep level n all. And surely there must be some differences. Apr 2, 2018 at 13:13
-
1@user1306322 That's a wholly separate question! You might check the java-10 tag, as many aspects of this have already been asked. Apr 2, 2018 at 13:17
-
Well, this is the question to look at if you're googling this, as it comes first and is linked to in every related post in the sidebar. So I suppose if you know that separate question which answers it, you might be able to at least link to it or include parts of it into your answer. Apr 2, 2018 at 15:24
Java 10 did get local variable type inference, so now it has var
which is pretty much equivalent to the C# one (so far as I am aware).
It can also infer non-denotable types (types which couldn't be named in that place by the programmer; though which types are non-denotable is different). See e.g. Tricks with var
and anonymous classes (that you should never use at work).
The one difference I could find is that in C#,
In Java 10 var
is not a legal type name.
I know this is older but why not create a var class and create constructors with different types and depending on what constructors gets invoked you get var with different type. You could even build in methods to convert one type to another.
Lombok
supports var but it's still classified as experimental:
import lombok.experimental.var;
var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);
Here is a pitfall to avoid when trying to use it in IntelliJ IDEA
. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.
Note that val
is support by Lombok
as well without modifying or creating a lombok.config
.
You can, in Java 10, but only for Local variables, meaning,
You can,
var anum = 10; var aString = "Var";
But can't,
var anull = null; // Since the type can't be inferred in this case
Check out the spec for more info.
-
2This is incorrect.
var
can be used for many forms of non-denotable types, including capture types, intersection types, and anonymous class types. And, as of Java 11, it can also be applied to lambda parameters. Aug 4, 2018 at 15:45
In general you can use Object class for any type, but you have do type casting later!
eg:-
Object object = 12;
Object object1 = "Aditya";
Object object2 = 12.12;
System.out.println(Integer.parseInt(object.toString()) + 2);
System.out.println(object1.toString() + " Kumar");
System.out.println(Double.parseDouble(object2.toString()) + 2.12);
-
Aditya, please check all your other answers. Many of them have -1 and probably for a good reason. Don't just post whatever if you're not sure it's correct. Apr 2, 2018 at 11:45
-
@user1306322 what's the problem in my answer! can u elaborate? can't we use Object class for all data type? Apr 2, 2018 at 12:08
-
Object object = 12; Object object1 = "Aditya"; Object object2 = 12.12; System.out.println(Integer.parseInt(object.toString()) + 2); System.out.println(object1.toString() + " Kumar"); System.out.println(Double.parseDouble(object2.toString()) + 2.12); Apr 2, 2018 at 12:12
-
The problem is you didn't understand the question. The question was not "how to make this work", but "is there a thing like this". You answer the wrong question. With the
var
word now officially in the language, your answer is also referring to the now old fashioned way. Apr 4, 2018 at 10:44
This feature is now available in Java SE 10. The static, type-safe var has finally made it into the java world :)
source: https://www.oracle.com/corporate/pressrelease/Java-10-032018.html
val
(orvar
) if you use a particular "Java replacement" language ;-)