DEV Community

Cover image for Variables and Data Types in Java
Ricardo Caselati
Ricardo Caselati

Posted on

Variables and Data Types in Java

In Java, a strongly-typed and statically-typed language, the data we use in code has well-defined types. This means you must declare the data type when creating a variable.
For example:

int answerToEverything = 42;
System.out.println(answerToEverything);

Enter fullscreen mode Exit fullscreen mode

Here, the variable answerToEverything is of type int, meaning it can only store integer values.

Primitive and Non-Primitive Types

Java data types are categorized into primitive and non-primitive types. Primitive types include int, byte, and boolean, while non-primitive types are used to represent objects and more complex structures, such as classes and arrays.
An important distinction is that primitive types store values directly, while non-primitive types store references to the data.

Details of Primitive Types

Primitive types are essential for storing simple data and performing fast operations. Each has a specific size and range:

Image description

They are ideal for numerical calculations and manipulations. A practical example of using byte is:

byte age = 25;
System.out.println(age);
Enter fullscreen mode Exit fullscreen mode

Usage Tips

Use consistent types in operations (e.g., avoid mixing int with short).
For numbers larger than int, use long with the suffix L at the end:

long population = 7_900_000_000L;
System.out.println(population);
Enter fullscreen mode Exit fullscreen mode

Java allows underscores (_) to improve the readability of large numbers, as shown above. This feature was introduced in Java 7 and does not affect the actual value of the number.

Pro Tip

Always prefer an uppercase L for long suffixes to avoid confusion with the number 1, especially in fonts where the two characters look similar.

This practical and structured approach to data types helps create more efficient and readable programs!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs