+ 3

Var keyword in java?

What is the use of var keyword in Java?I learnt Java 8 but it is introduced in Java 10 and I am feeling rusty in Java....So PLZZ tell where var can be used ..I used to declare instance variables but it says var not allowed here.... https://code.sololearn.com/c63XWiQy8kkJ/?ref=app

18th Mar 2019, 3:14 PM
Saksham Jain
Saksham Jain - avatar
9 ответов
+ 4
Remove line 2: var b = 4 (or add it after the main method) var b = 2 --> the compiler treats b as an integer. I have not worked with the var keyword yet, so I can not much say about it. Maybe this article helps: https://developers.redhat.com/blog/2018/05/25/simplify-local-variable-type-definition-using-the-java-10-var-keyword/
18th Mar 2019, 3:50 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Var is neither a keyword nor a data type After class we declare our instance variables →Data_type variable_name; for example int i; So var can not be used here to declare instance variable b Instead u can use int b;
18th Mar 2019, 4:41 PM
Ankit Yadav
+ 3
I have made an example code: https://code.sololearn.com/c5Ypf1x9W1E8/?ref=app you can use var instead of the datatypes. I'm not sure what happens when var is an object. Edit: I added a Test Class --> var t = new Test();
18th Mar 2019, 5:04 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
In 5th line in the website I sent to u there is written that its not really a keyword
19th Mar 2019, 3:43 PM
Ankit Yadav
+ 3
Ankit Yadav Saksham Jain I think var is in a grey area. It is not declared as a keyword: var var = 7 is possible (int int = 7 is not possible). But it is like a keyword. I think it has to do that you can use var only for local variables, but I'm not sure.
19th Mar 2019, 3:57 PM
Denise Roßberg
Denise Roßberg - avatar
19th Mar 2019, 9:42 AM
Ankit Yadav
+ 1
Ankit Yadav if var is not a keyword then what is it?
19th Mar 2019, 9:33 AM
Saksham Jain
Saksham Jain - avatar
+ 1
Denise Roßberg why declaring instance variables by var doesn't work?
19th Mar 2019, 9:37 AM
Saksham Jain
Saksham Jain - avatar
+ 1
Ankit Yadav thanks for the link but it is a keyword.
19th Mar 2019, 11:46 AM
Saksham Jain
Saksham Jain - avatar