One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?
-
4`val` (or `var`) if you use a particular "Java replacement" language ;-) – Dec 14 '10 at 19:27
-
7@pst: that would be Scala? Hm yes, it is. – rsenna Dec 14 '10 at 21:20
-
For IntelliJ, I submitted this as a feature request: http://youtrack.jetbrains.com/issue/IDEA-102808 The IDE could collapse code to show val or var even though the underlying code wouldn't have it. – Jon Onstott Mar 10 '13 at 19:26
-
@Jon I've hacked something together for IntelliJ, see my [answer](http://stackoverflow.com/a/16002535/115866). – balpha Apr 14 '13 at 18:10
-
There's still no var keyword / type inference in Java 8, correct? http://leftoblique.net/wp/2013/07/25/java-8-a-k-a-oracle-finally-catches-up-to-net-framework-3-0 – Max Jun 30 '14 at 14:55
-
3There is now a proposal for this feature to be included in Java - http://openjdk.java.net/jeps/286 – McGin Mar 13 '16 at 10:02
-
Perhaps you can try Kotlin https://kotlinlang.org/ Great talk about Kotlin. https://youtu.be/R0J_Jl7bKY8 – Arturo Mejia Mar 15 '17 at 00:40
-
@McGin [It's now alive](https://stackoverflow.com/questions/3443858/what-is-the-equivalent-of-the-c-sharp-var-keyword-in-java/48933006#48933006). – Maroun Mar 26 '18 at 16:59
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;

- 90,105
- 23
- 150
- 161

- 14,351
- 4
- 49
- 77
-
1And to be fair also; 1. it's only recent in C#, so Arturo can't be blaming "creators" and 2. it's only due to some other features that weren't in the 1.0 of either language that its become an idea that is useful rather than a great way to make code less clear and more bug-prone. It's needed in C#3.0, and would have a few useful cases in C#2.0, but would have been a bad thing in C#1.0. – Jon Hanna Aug 09 '10 at 22:13
-
1@Mike Caron: and because of certain very long types (without `var`, that would make Linq practically unusable). – rsenna Dec 14 '10 at 21:18
-
@pst What does implicit typing have to do with polymorphism? The `var` keyword is 100% identical to declaring a variable with the exact type of the expression. That's all. – Mike Caron Dec 15 '10 at 19:30
-
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 as `SuperX p = new X(); p.Z()` for all X and and SuperX, even though `X : SuperX`. With `var` the *static* type of `p` is always `X` in first example above, but always `SuperX` in the second example. A subtle but important difference to be aware of. But your answer is very correct :-) – Dec 15 '10 at 20:10
-
209@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 example `UserCollection collection = new userRepository.GetUsers();` rather more naturally turns into `var users = userRepository.GetUsers();`). If you think `var` is unclear it is just because unused to it. – Martin Odhelius Jul 06 '12 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 a `RadioButton` `radioButton` in the case of a factory or helper method where the only thing significant about the button was that it was a `RadioButton`, otherwise that's madness with or without `var`. – Jon Hanna Jul 06 '12 at 10:32
-
7@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. – Martin Odhelius Jul 06 '12 at 11:51
-
2@MartinOdhelius Who said I was critical of var? One of my favourite things about SharpDevelop2.0 was that it had a feature that would turn typing e.g. `? x = a.CompareTo(b);` into `int x = a.CompareTo(b);` and so on, which is the closest we could have to `var` without language support. So I was using `var` before there was `var`. – Jon Hanna Jul 06 '12 at 13:43
-
I'm sorry, but "var currentUser = User.GetCurrent();" is not inherently obvious what you're getting back. You may likely get an instance of the User class, but you could also easily be getting the user's name as a string or a user ID as an integer, or any combination of things. You correctly point this out in your text, but this particular example actually demonstrates how var can grossly obfuscate a situation rather than clarify it. – Syndog Oct 20 '17 at 23:00
-
5You're confusing [var](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var) with [anonymous types](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/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. – Robear Jan 23 '18 at 19:51
-
3Java 10 is expected to have type inference, see https://blog.codefx.org/java/java-10-var-type-inference/ – Amedee Van Gasse Feb 02 '18 at 14:55
-
@Robear The only place where it may (but doesn't have to) cause confusion is where you can't use your IDE to point out proper type. For instance, take code review boards. – Asunez Mar 23 '18 at 06:21
-
Heavy use of var is great because then when something isn't typed as a var it's a hint that something interesting is about to happen related to typing. It functions as a "pay attention to this next bit" when used well. – Drew Delano Aug 25 '23 at 06:27
If you add Lombok to your project you can use its val keyword.

- 63,782
- 15
- 129
- 193

- 2,205
- 1
- 15
- 17
-
1@rightfold: Objects whose reference is `final` are not necessarily immutable. Consider `final StringBuilder strB = new StringBuilder("My reference is final"); strB.append("I'm not immutable");` – Matthias Braun Mar 24 '14 at 16:52
-
1Since lombok v1.16.12 there is also experimental support for `var`. https://projectlombok.org/features/experimental/var.html – Roel Spilker May 29 '17 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. – Andzej Maciusovic Aug 11 '17 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>

- 3,707
- 30
- 18
-
-
@PeterMortensen Yes. JEP 286 has been accepted and published in JDK 10 (see 286 under Features at http://openjdk.java.net/projects/jdk/10/). – Justin Albano Apr 01 '18 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.

- 3,809
- 2
- 24
- 51
-
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? – user1306322 Apr 04 '18 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 makes `var` 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 using `var` in Java. – Justin Albano Apr 04 '18 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. – user1306322 Apr 04 '18 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 as `public 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 behind `var` in Java and its differences with `var` in C#. – Justin Albano Apr 04 '18 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.

- 50,022
- 18
- 110
- 131
-
It'd be great to have a keyboard shortcut to fold/unfold declaration types in the current editor. Great plugin though. – hotkey Aug 17 '15 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 '15 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 ==> []

- 94,125
- 30
- 188
- 241
-
3Beware, the code you provided (before/after `var`) is not equivalent. In the `var` example `list` is of type `ArrayList`, not a `List`. – Gili Jul 27 '18 at 02: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!

- 30,738
- 21
- 105
- 131

- 7,559
- 6
- 45
- 49
-
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...) – BrainSlugs83 Sep 23 '14 at 05: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 – JonnyRaa Sep 23 '14 at 08:05
As of Java 10, the equivalent is ... var
.

- 90,105
- 23
- 150
- 161
-
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. – user1306322 Apr 02 '18 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. – Brian Goetz Apr 02 '18 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. – user1306322 Apr 02 '18 at 15:24
-
4Kotlin has val and var. val is equivelent to declaring a variable final in java, var allows reassignment. – samlewis Nov 06 '17 at 12:50
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.

- 167,066
- 35
- 309
- 487
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.

- 59
- 3
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
.

- 17,329
- 10
- 113
- 185
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.

- 1,369
- 1
- 10
- 21
-
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. – Brian Goetz Aug 04 '18 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);

- 44
- 6
-
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. – user1306322 Apr 02 '18 at 11:45
-
@user1306322 what's the problem in my answer! can u elaborate? can't we use Object class for all data type? – Aditya Kumar Apr 02 '18 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); – Aditya Kumar Apr 02 '18 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. – user1306322 Apr 04 '18 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

- 1,199
- 12
- 11