From the course: Java 25 for Professionals with Jetbrains AI Assistant
Unnamed variables - Java Tutorial
From the course: Java 25 for Professionals with Jetbrains AI Assistant
Unnamed variables
- [Instructor] All right, time to discuss the next feature. Unnamed Variables, indicated by the underscore. This is actually a really cool new feature, because now we have unnamed variables. They're actually not really unnamed. They are named underscore, but you can't use them. So, you can use this when you don't care about binding in a pattern, or when you'd need to specify a variable syntactically, but you'll never use it. This removes the unused variable noise, and they won't get flagged as unused anymore either. This is something you can make explicit now. Let me show you a few basic examples. So, the first one, line 10 to 14, we're having the safeDelete method, and we're having a try catch, but we'll never do something with the exception, so we name it underscore to indicate that we'll never use it. If it would've named it E, which is quite conventional, it would give me a warning that the variable was never used. Here's another one. Let's try with resources. We have var_ and we set it to the InputStream in that's sent in as an argument to this method. Since we call it underscore, we can't use it, but we don't need to, because we can use indirectly, and we do have the auto-close feature right now. So, since we already had an initialized resource, we didn't need to give it a name again, and that's why we called it underscore. Here's another one. Before each, where we don't really care about the element we're looping over, but we just need to do something for every element in the collection. I'm not going to lie, I think this still looks a little awkward, but I need to get used to it. Right now, it looks like my code turned into a fill-in-the-blank exercise, but I do definitely see the value of not having a dummy name, and being explicit about the intent to not use the variable.