← Back to list

Java var (Local-Variable Type Inference)

For when you’re too lazy to write String but still want to pretend you’re working hard!

M Business Solutions in Dev Genius · 2024-09-19 15:39 · 1 claps · 1.6 min read paywalled
#java #java10 #java-tutorial #java-var #javafeatures
Open on Medium ↗
Wiki topics: OPS · LLMOps & Inference

Java var

For when you’re too lazy to write String but still want to pretend you’re working hard!

In Java, the var (Local-Variable Type Inference) is like having Java figure out the type of a variable for you, so you don’t have to write it yourself. It’s a shortcut for declaring variables without explicitly specifying their type.

Imagine going to a pizza place, and instead of telling the cashier what type of pizza you want (like cheese, pepperoni, etc.), you just say, “Give me whatever fits best,” and the cashier figures out the pizza type based on what you meant. That’s var!

How It Works:

  • Before var: You had to be specific about what type of value a variable would hold, like this:
String message = "Hello!";
int number = 10;
  • With var: Java will guess the type of the variable based on the value you assign to it:
var message = "Hello!";  // Java knows it's a String
var number = 10;         // Java knows it's an int

The key thing is, Java is still strongly typed. It knows exactly what type the variable is; you just don’t need to explicitly write it. It’s not dynamic typing like in JavaScript — it just saves you from typing long type names.

Example of var:

Here’s a before-and-after example:

Without var (Old School):

String name = "John";
int age = 30;
Map<String, Integer> myMap = new HashMap<>();

With var (Modern Java):

var name = "John";               // Java knows it's a String
var age = 30;                    // Java knows it's an int
var myMap = new HashMap<String, Integer>(); // Java knows it's a Map<String, Integer>

In this example:

  • var name becomes a String.
  • var age becomes an int.
  • var myMap becomes a Map<String, Integer>.

When to Use var:

  • When the type is obvious: If it’s clear from the context what the type is (like var name = "John";), use var.
  • Avoid for complex types: If the type is too complicated and hard to understand without explicitly declaring it, you might want to skip var.

If you found this blog helpful, please give it a clap 👏 and follow 🔔 for more insights and updates! Your support keeps the knowledge flowing!


메타데이터
post_id
6e2233d29be3
slug
java-var-6e2233d29be3
url
https://blog.devgenius.io/java-var-6e2233d29be3
canonical_url
https://blog.devgenius.io/java-var-6e2233d29be3
author_url
https://medium.com/@mbusinesssolutions
status
ok
fetched_at
2026-07-22 19:30:19