165

Is there an auto variable type in Java like you have in C++?

An example:

for ( auto var : object_array)
    std::cout << var << std::endl;

for( auto var : object_array)
    var.do_something_that_only_this_particular_obj_can_do();

I know that there is an enhanced for loop in Java, but is there an auto? If not, is there a hack to doing this? I am referring to the new feature in C++11.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 1
    Everything except fundamental types can be assigned to a variable of type `Object`, so for some operations, you can use `Object` where you want `auto`. – Zyx 2000 Apr 21 '13 at 15:24
  • 1
    no java has no such variable – Aliaksei Bulhak Apr 21 '13 at 15:24
  • @Zyx2000 : Then, it will use object's `to_string` function, and not the actual object in question, would it not? – Games Brainiac Apr 21 '13 at 15:26
  • 2
    @GamesBrainiac: No, it will use the overridden version, if one exists. – Keppil Apr 21 '13 at 15:26
  • 2
    The term you're looking for isn't "auto", it's "type inference". There are quite a few questions about type inference in Java, though they mostly refer to generics, so I'm not sure how to find a duplicate... –  Apr 21 '13 at 15:35

6 Answers6

118

Might be Java 10 has what you (and I) want, through the var keyword.

var list = new ArrayList<String>();  // infers ArrayList<String>
var stream = list.stream();          // infers Stream<String>

From JDK Enhancement Proposals 286


Update: Yap, that feature made it into the Java 10 release!

sorrymissjackson
  • 2,395
  • 1
  • 19
  • 18
  • 9
    Ya its an improvement, but that keyword can only work with local variables. Not as powerful as C++ auto type inference – SwiftMango Feb 27 '18 at 05:43
  • 10
    Minor nit-pick: `var` is not a keyword! From the [JLS](https://docs.oracle.com/javase/specs/jls/se10/html/jls-3.html#jls-3.9): "var is not a keyword, but rather an identifier with special meaning as the type of a local variable declaration". Thus, unlike keywords, there is nothing to stop you calling a variable or a method "var". – Klitos Kyriacou Dec 21 '18 at 11:49
  • 2
    Good point @KlitosKyriacou. Yet, if I imagine to replace 'keyword' with 'identifier' - or even 'identifier with special meaning as the type of a local variable declaration' - the answer would be less clear I think. But yeah, `var` indeed is not in the list of keywords. – sorrymissjackson Jan 08 '19 at 09:00
  • 1
    It's not a keyword merely for backward compatibility. Besides the fact that you can have an identifier with this name, var serves a role of a keyword. – facetus Jan 25 '20 at 19:36
  • Finally, sad that it took this long. So can we expect type aliasing in another 20 years or so? – David Bradley Aug 26 '20 at 02:56
69

Java 10 introduced a var identifier which is like C++ auto; see sorrymissjackson's answer.

Prior to Java 10, there was no equivalent to the auto keyword. The same loop can be achieved as:

for ( Object var : object_array)
  System.out.println(var);

Java has local variables, whose scope is within the block where they have been defined. Similar to C and C++, but there is no auto or register keyword. However, the Java compiler will not allow the usage of a not-explicitly-initialized local variable and will give a compilation error (unlike C and C++ where the compiler will usually only give a warning). Courtesy: Wikipedia.

There wasn't any mainstream type-inference in Java like C++ . There was an RFE but this was closed as "Will not fix". The given was:

Humans benefit from the redundancy of the type declaration in two ways. First, the redundant type serves as valuable documentation - readers do not have to search for the declaration of getMap() to find out what type it returns. Second, the redundancy allows the programmer to declare the intended type, and thereby benefit from a cross check performed by the compiler.

mic
  • 1,190
  • 1
  • 17
  • 29
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • True, but then would Object not use it's `to_string` function instead of the actual object in question? – Games Brainiac Apr 21 '13 at 15:29
  • 10
    @GamesBrainiac No, method calls are always polymorphic in Java. However, many other things (e.g. overload resolution, or any operation not defined on `Object`) can't be done like this. This is not really a good answer, it only happens to work because the example in the question is weak. –  Apr 21 '13 at 15:32
  • 1
    Then you need to cast it to its original type. – AllTooSir Apr 21 '13 at 15:33
  • 10
    This question is about the type inference in C++11, not about the old use of `auto` in C and pre-C++11. Your edit is off topic. –  Apr 21 '13 at 15:33
  • @NoobUnChained : Thats not what I meant, once you type cast it to an `Object`, it will give you Object's `to_string`. Yes, this is a weak example, but ideally, Object is not a full proof alternative, is it? – Games Brainiac Apr 21 '13 at 15:38
  • I downvoted because this is quite incorrect. Firstly, C, C++, and Java all have identical ideas of local variables. Secondly, it's quite legal in C++ not to explicitly initialize many types, which can safely default-initialize themselves. – Puppy Apr 21 '13 at 15:48
  • @delnan : Changed the question, does it make it a stronger example? – Games Brainiac Apr 21 '13 at 15:54
  • 4
    " Thats not what I meant, once you type cast it to an Object, it will give you Object's to_string" False. Absolutely 100% false. – Louis Wasserman Apr 21 '13 at 18:33
  • By the way that comment by Gilad Bracha on the closed bug was from 2001. His perception on this might have changed in 12 years! – ebruchez Nov 14 '13 at 22:44
  • 1
    Question is about auto type not scope keyword – Gelldur Jul 16 '14 at 09:16
  • 159
    "Humans benefit from the redundancy." It's true. Every morning I wake up and think "how can I make my code more redundant?". Because of the benefits. – ahoffer Apr 28 '15 at 19:23
  • 2
    Moreover this answer is obsolete because `var` is a reserved keyword since Java 9. – 6infinity8 Apr 19 '19 at 14:13
  • 3
    The most ridiculous reason to not implement such a handy feature, Now I figure out why my non-developer friends call me typist. – Saleh May 30 '20 at 09:33
28

Java 7 introduces the diamond syntax

Box<Integer> integerBox = new Box<>(); // Java 7

As compared to old java

Box<Integer> integerBox = new Box<Integer>(); // Before Java 7

The critical reader will notice that this new syntax doesn't help with writing the for loops in the original question. That's correct and fully intentional it seems. See the other answer that cites Oracle's bug database.

Tarrasch
  • 10,199
  • 6
  • 41
  • 57
  • 5
    True, but what he (and I) are looking for is something like: `auto integerBox = new Box();`, this is usually used for getting a return value from a functions which sometimes can be complexed like `HashMap>>` – Roee Gavirel Oct 28 '14 at 14:52
  • 1
    That concern is exactly what I addressed after the code samples. The conclusion was that Java doesn't do that, and that's on purpose. – Tarrasch Oct 30 '14 at 12:43
  • 1
    This addition completely puzzled me when I learned of it. It's completely backwards of what you would expect and provides modest benefit. – David Bradley Aug 26 '20 at 02:58
19

In Java 8, you can use lambda type inference to avoid declaring the type. The analogue to the questioner's examples would be:

object_array.forEach(obj -> System.out.println(obj)); 
object_array.forEach(obj -> obj.do_something_that_only_this_particular_obj_can_do());

both of which can also be simplified using method references:

object_array.forEach(System.out::println); 
object_array.forEach(ObjectType::do_something_that_only_this_particular_obj_can_do);
mic
  • 1,190
  • 1
  • 17
  • 29
Ajit George
  • 3,239
  • 1
  • 19
  • 10
8

In short, no, there is no auto type. If all you are doing is printing the value though, you could just refer to the value as an Object.

SimonC
  • 6,590
  • 1
  • 23
  • 40
  • or computing `hashCode`s, or collecting class names, or... you got the idea ;) The list is short, though. See [Object class' docs](http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html) (comment meant for beginners, I'm sure you knew it SimonC) – Alexander Malakhov Jul 12 '13 at 04:18
8

It's not a pure Java solution, however adding a library called lombok will enable the magic below to compile and work very much similar to auto keyword in C++

List<String> strList = Arrays.asList("foo", "bar", "baz");
for (val s: strList){
    System.out.println(s.length());
}
samvel1024
  • 1,123
  • 4
  • 15
  • 39