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!

Top comments (0)