Check out a free preview of the full Java Fundamentals course
The "Local Variable Type Inference" Lesson is part of the full, Java Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:
Angie discusses inferring a local variable's type by declaring it using var. Global variables cannot be inferred using var.
Transcript from the "Local Variable Type Inference" Lesson
[00:00:00]
>> In Java, we talked about how lengthy things are and how verbose the language is. There is what's called local variable type inference, which is a really long phrase that basically says you can use var for data types. So instead of doing something like this, boolean isWaterWet = true;, I could say var isWaterWet = true;.
[00:00:31]
This does not make Java dynamically type, it's still static type. What it's going to do is, in var, was the data type based on whatever it is that I assigned to it? Which means I can only use var if I'm actually assigning a value to that variable, and the variable has to be local as the name implies.
[00:00:52]
It cannot be one of the global variables, okay? So this is a local variable because it's inside of a main method, right? This one is a global variable, so I would not be able to do that. We might use var sometimes. I love writing var, it's one of my favorite things.
[00:01:17]
So I just write var and then whatever it is, I don't have to think about the data type too heavily. It's great for when you're using methods that you're not really sure what the data type will be when you come back without examining the method. Var blah blah, call a method and Java knows what the data type will be, okay?
[00:01:36]
>> Doesn't that get confusing with certain data types, int versus doubles, for example, where that might matter?
>> If you assign it and then later on you like hover over it, Java will tell you like what it inferred from that. And then, if you were doing something that required a double or something like that, you'd be fine, yeah.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops