Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Java vs. TypeScript: Variable Declaration

This lesson is built with resources from youtube.com, baeldung.com and 1 more site.

Hello! Welcome back to the course.

In our last lesson, we set up your entire Java development environment. You now have the JDK, Maven, and IntelliJ ready to go. We also demystified the compilation process, seeing how your Main.java source code was compiled into Main.class bytecode, which was then executed by the JVM.

Today, we'll write some more Java code and dive into one of the most fundamental concepts of the language: its type system. We'll explore the critical distinction between primitive and reference types, something that has profound implications for performance and memory management. This is a key difference from how languages like JavaScript and TypeScript operate, and understanding it is crucial for writing efficient, professional Java code.

1. The Great Divide: Value vs. Reference Types

In TypeScript, you're used to types like number, string, boolean, and object types. While JavaScript has a concept of primitives and objects, the distinction is often blurred. In Java, this separation is explicit, enforced by the compiler, and has direct consequences on how your program runs.

Java's type system is split into two categories:

  1. Primitive Types: These hold a single, simple value directly. They are stored in the fastest available memory, the stack, for local variables.
  2. Reference Types: These don't hold the data directly. Instead, they hold a memory address (a "reference") that points to where the actual object data is stored. Objects live in a larger memory area called the heap.

To get a clear visual of this, watch the following video. It does an excellent job of explaining this core concept using simple analogies.

Primitive Types and Reference Types in Java

The video 'Primitive Types and Reference Types in Java' provides a foundational explanation of how Java stores and handles these two kinds of variables in memory. Pay close attention to the diagrams showing 'boxes' for variables.

Watch from the beginning until 6:14. Focus on: How primitive variables (like int) directly contain their value. How reference variables (like String) contain a memory address that points to the object's value. The critical difference in behavior when you assign one variable to another for both types.

Memory: Stack vs. Heap

The video you just watched alludes to different memory areas. In Java, the two we care about most are the Stack and the Heap.

  • Stack: A highly organized and fast memory region. Each time a method is called, a new "frame" is pushed onto the stack to hold its local variables (primitives) and references to objects. When the method finishes, its frame is popped off, and the memory is reclaimed.
  • Heap: A large, less organized pool of memory where all objects are created (e.g., using new). Memory in the heap is managed by the Garbage Collector, which automatically cleans up objects that are no longer referenced.

This image perfectly illustrates the concept:

Stack Vs Heap Memory Allocation
Local variables and method calls live on the Stack. The `int id` is a primitive. The `Emp reference` is a reference variable on the stack pointing to an `Emp object` that lives on the Heap. The `string reference` points to a string in a special part of the heap called the string pool.

MERN-to-Java Mapping: Types and Memory

This is a major conceptual shift from your MERN background:

  • In JavaScript/TypeScript, every object, array, or function is a reference type. Primitives like number, string, boolean, null, and undefined exist, but the memory model is largely hidden from you.
  • In Java, this distinction is front and center. Declaring int vs. Integer is a deliberate choice with performance and memory consequences. When you pass a variable to a method, knowing whether you're passing a copy of a value (int) or a copy of a reference (String) is essential for debugging.

2. Java's Primitive Types

Java provides eight primitive types. You must choose the one that fits your data, as each has a specific size and purpose.

Type Size (bits) Description Default Value TypeScript Equivalent
boolean JVM-specific true or false false boolean
char 16 A single Unicode character \u0000 string (length 1)
byte 8 -128 to 127 0 number
short 16 -32,768 to 32,767 0 number
int 32 ~-2.1 billion to ~2.1 billion 0 number
long 64 Very large integers 0L bigint / number
float 32 Single-precision decimal 0.0f number
double 64 Double-precision decimal 0.0d number

Notice how TypeScript's single number type covers byte, short, int, long, float, and double. Java requires you to be more precise, which allows for more efficient memory usage. In modern backend development, you'll most often use int, long, double, and boolean.

For a detailed look at how TypeScript types are mapped to Java, especially in the context of a web application, the following resource is invaluable.

Type conversion between Java & TypeScript | Vaadin Hilla

The document 'Type conversion between Java & TypeScript' from Vaadin Hilla provides a detailed reference for how types are converted when data is sent from a frontend to a Java backend. We will focus on the primitive types section.

Skim the table under the 'Primitive Types' heading. You don't need to memorize it, but observe the level of detail. Note how a single TypeScript number can be deserialized into different Java numeric types, and what happens in cases of overflow.


3. The Bridge: Wrapper Classes and Autoboxing

You might be thinking, "If primitives are so fast, why would I ever use anything else?" There are two main reasons:

  1. Collections and Generics: Java's collection framework (e.g., List, Map) can only store objects, not primitives.
  2. Nullability: A primitive int must have a value; its default is 0. What if you need to represent a value that hasn't been set yet? A database ID that doesn't exist? A primitive can't be null.

To solve this, Java provides a wrapper class for each primitive type. These are reference types that "wrap" a primitive value inside an object.

Primitive Wrapper Class
int Integer
long Long
double Double
boolean Boolean
...etc. ...etc.

The process of converting a primitive to its wrapper is called boxing, and the reverse is unboxing. Modern Java does this for you automatically, a feature called autoboxing and auto-unboxing.

This next video explains this concept and its practical applications very clearly.

#60 Wrapper Class in Java

The video '#60 Wrapper Class in Java' by Telusko explains why wrapper classes are necessary and demonstrates how autoboxing and unboxing work. It also shows a common practical use case.

Watch from the beginning until 8:04. Focus on: Why wrapper classes are needed for frameworks and collections (0:00-2:15). The concepts of boxing, unboxing, and the automatic versions (2:15-6:26). The practical example of using Integer.parseInt() to convert a String to an int (6:26-8:04).


4. Hands-On: Declaring Variables

Let's apply these concepts. Open the Main.java file from our last lesson (blog-platform-java-intro/src/main/java/com/blogplatform/Main.java) in IntelliJ IDEA.

Replace the content of the main method with the following code. As you type, notice IntelliJ's code completion and type checking.

// --- Primitive Types ---
int postViews = 10500;
double postRating = 4.5;
boolean isPublished = true;
// A primitive cannot be null. This line would cause a compilation error:
// int totalLikes = null; 

System.out.println("Post Views (primitive int): " + postViews);
System.out.println("Post Rating (primitive double): " + postRating);
System.out.println("Is Published (primitive boolean): " + isPublished);

System.out.println("\n--------------------------------\n");

// --- Reference Types (Wrappers) ---
Integer totalLikes = 250; // Autoboxing: Java converts the primitive 250 to an Integer object.
Integer uninitializedLikes = null; // A wrapper type CAN be null.

System.out.println("Total Likes (Wrapper Integer): " + totalLikes);
System.out.println("Uninitialized Likes (Wrapper Integer): " + uninitializedLikes);

// Auto-unboxing: The Integer 'totalLikes' is converted back to a primitive int for the calculation.
int newLikes = totalLikes + 5; 
System.out.println("Likes after calculation: " + newLikes);

// Be careful! Unboxing a null reference will cause a runtime crash.
// The following line will throw a NullPointerException:
// int crash = uninitializedLikes + 1; 

// The String class is another common reference type.
String authorName = "Alex";
String anotherAuthorRef = authorName; // Both variables point to the SAME "Alex" object in memory.

System.out.println("Author Name (Reference String): " + authorName);

Run this code by clicking the green play button next to the main method in IntelliJ. Observe the output and read the comments carefully. They highlight the key differences and potential pitfalls, like the NullPointerException, which is one of the most common bugs in Java.


5. When to Use Which? The Professional's Choice

So, what's the rule of thumb?

Java Primitives Versus Objects | Baeldung

The article 'Java Primitives Versus Objects' from Baeldung dives into the performance, memory, and default value differences. It provides the 'why' behind choosing one over the other.

Read the sections '2. Java Type System', '3. Pros and Cons' (just read the intro and subsection '3.4. Default Values'), and '4. Usage'. This will solidify your understanding of the trade-offs.

The general guideline for a senior developer is:

  • Prefer primitives (int, double, etc.) in method variables, loops, and performance-sensitive code. They are significantly faster and use less memory.
  • Use wrapper classes (Integer, Double, etc.) when you must. The most common reasons are:
    • You need to represent a null value (e.g., a database column that can be empty).
    • You are using Java's collections or generics (e.g., List<Integer>).

Conclusion

In this lesson, we dissected a core pillar of the Java language. You now understand the fundamental and practical differences between primitive and reference types.

Key Takeaways:

  • Java's type system is split into primitives (value types) which are fast and live on the stack, and reference types (objects) which are more flexible and live on the heap.
  • Your TypeScript background with number maps to several more specific numeric types in Java (int, long, double, etc.), requiring more deliberate choices.
  • Wrapper classes like Integer act as a bridge, allowing primitives to be treated as objects, enabling null values and use in collections.
  • Autoboxing handles the conversion automatically but isn't free—it has a performance cost. A NullPointerException is a common runtime error when unboxing a null wrapper.

In our next lesson, we will build on this foundation. We'll learn how to define our own custom reference types using the class keyword, which will form the domain model for our blog platform (e.g., a User class, a Post class).