Variables & Types
Static typing vs dynamic typing
Introduction
In this lesson, you'll learn about variables & types in Java. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with static typing vs dynamic typing.
Java has its own approach to static typing vs dynamic typing, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
String name = "Alice";
int age = 30;
double score = 9.5;
boolean active = true;
// Types cannot change after declaration
int value = 42;
// value = "string"; // compile error!
final int MAX = 100; // like JS const
// var (Java 10+) — infers type
var city = "Istanbul"; // inferred as StringComparing to JavaScript
Here's how you might have written similar code in JavaScript:
let name = "Alice";
let age = 30;
let score = 9.5;
let active = true;
// Types can change
let value = 42;
value = "now a string"; // valid in JS
const MAX = 100;You may be used to different syntax or behavior.
Java is statically typed — types are fixed at compile time
You may be used to different syntax or behavior.
JS let/const → Java type declarations (String, int, etc.)
You may be used to different syntax or behavior.
JS variables can change type; Java variables cannot
You may be used to different syntax or behavior.
Java final = JS const; Java var = type inference (Java 10+)
Step-by-Step Breakdown
1. Explicit Types
Java requires you to declare the type of every variable. The compiler catches type mismatches before the program runs.
let age = 30;int age = 30;2. Primitive vs Object Types
Java has primitive types (int, double, boolean) and object wrappers (Integer, Double, Boolean). Primitives are more efficient.
int x = 5; // primitive
Integer y = 5; // object wrapper (nullable)
double d = 3.14;
String s = "hello"; // always an object3. final and var
Java's final prevents reassignment like JS const. Java 10+ var infers the type from the right side.
const MAX = 100;
let city = "Istanbul";final int MAX = 100;
var city = "Istanbul"; // String inferredCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- Java is statically typed — types are fixed at compile time
- JS let/const → Java type declarations (String, int, etc.)
- JS variables can change type; Java variables cannot
Key Takeaways
- Java types are fixed at declaration; JS types are dynamic
- Java final = JS const
- Java primitives: int, double, boolean, char
- var in Java 10+ infers types like JS let