Understanding Variables and Data Types in Java

Java Introduction: Part III

Marcelo Domingues
devdomain
9 min readJun 30, 2024

--

Reference Image

Introduction

Variables and Data types are some of the significant concepts of Java that make us able to store and handle data. So, in terms of richness in data types, Java has two categories: primitive data types and reference data types. A Java programmer should know those data types and, above all, the best way of using them effectively. The article considers primitive data types, reference data types, and data type conversion and casting in Java.

Primitive Data Types

There are eight primitive data types built into the Java language, each with a unique role and occupying a fixed amount of memory. These primitive types are the most basic form of storing data and fundamental building blocks in manipulating data in Java.

1. int: Used for integer values. This type is suitable for storing whole numbers without decimals.

  • Memory: 32 bits
  • Range: -2,147,483,648 to 2,147,483,647
  • Example: int age = 25;

2. byte: Used for small integer values. This type is useful when you need to save memory in large arrays.

  • Memory: 8 bits
  • Range: -128 to 127
  • Example: byte smallNumber = 10;

3. short: Used for slightly larger integer values than byte. It is also useful for saving memory in large arrays.

  • Memory: 16 bits
  • Range: -32,768 to 32,767
  • Example: short mediumNumber = 32000;

4. long: Used for very large integer values. This type is necessary when int is not large enough.

  • Memory: 64 bits
  • Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  • Example: long largeNumber = 10000000000L;

5. float: Used for single-precision floating-point values. This type is suitable for saving memory in large arrays of floating-point numbers.

  • Memory: 32 bits
  • Range: Approximately ±3.40282347E+38F (6–7 significant decimal digits)
  • Example: float height = 5.75f;

6. double: Used for double-precision floating-point values. This type is generally used as the default data type for decimal values.

  • Memory: 64 bits
  • Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)
  • Example: double distance = 12345.6789;

7. char: Used for single 16-bit Unicode characters. This type is useful for storing any character.

  • Memory: 16 bits
  • Range: ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive)
  • Example: char letter = 'A';

8. boolean: Used for true/false values. This type is useful for simple flags that track true/false conditions.

  • Memory: 1 bit (but size depends on JVM)
  • Values: true or false
  • Example: boolean isJavaFun = true;

Examples of Primitive Data Types

A primitive data type also represents a simple value, where the fundamental types of data are defined in the language itself with a particular reserved keyword being its name. Primitive data types hold simple values and are memory-saving and efficient in performance compared to the reference types. Let’s examine three common primitive data types with more elaborate examples.

int Example:

The type int is a 32-bit signed two’s complement integer. This data type is generally used for numbers that do not contain any decimal points. The int data type is commonly applied in numeric calculations, counting, and indexing.

public class PrimitiveInt {
public static void main(String[] args) {
int number = 100; // Declaring an integer variable and assigning it a value
System.out.println("Value of int: " + number); // Printing the value of the integer variable
}
}

In this example, we declare an integer variable numberand initialize it to hold the value 100. The intdata type is very versatile in various situations and is quite commonly used when dealing with numbers that do not have decimal values. The storage in memory allocated to the intis 32 bits and can hold values between -2,147,483,648 and 2,147,483,647. If we were to print the value of the numberto the console using the statement System.out.println, the output would be:

Value of int: 100

char Example:

Charis a data type that stores one single 16-bit Unicode character. It is used to store individual characters — both letters and characters. Each charcan represent any character of Unicode, which makes it adequate for internationalization.

public class PrimitiveChar {
public static void main(String[] args) {
char letter = 'A'; // Declaring a character variable and assigning it a value
System.out.println("Value of char: " + letter); // Printing the value of the character variable
}
}

Here, I’ll declare a character variable letterand assign it a value of ‘A.’ The chartype turns out to be quite helpful when it comes to working with individual characters. For example, it can be applied to cases like checking the first letter of a name, text files while processing where characters need to be read one at a time, or working with characters in games and applications. The memory allocated for a charis 16 bits. Therefore it can easily represent characters from ‘\u0000’ up to ‘\uffff’.. If we print the value of the variable letterto the console, the output will be:

Value of char: A

boolean Example:

The booleandata type has only two truth values, namely trueand false. It is used mainly for simple flags to keep track of actual/false conditions and, more often, in control flow statements, such as if-else and loops.

public class PrimitiveBoolean {
public static void main(String[] args) {
boolean isJavaFun = true; // Declaring a boolean variable and assigning it a value
System.out.println("Is Java fun? " + isJavaFun); // Printing the value of the boolean variable
}
}

The booleantype is one of the most primitive and is widely used within programming regarding decision-making and program flow control. This type is usually found as a condition for if-else statements, while loops, and for loops. The memory of the booleanvariable is not well defined. However, the JVM optimizes it to consume less memory. If we print isJavaFuninto the console, the output is:

Is Java fun? true
Summary of Primitive Data Types:

Reference Data Types

There are three reference data types in Java: class types, interface types, and array types. Primitive types are used to store values, while reference types are used to store references to the values. This will make the data more advanced and used in object-oriented programming.

Classes

Objects are created from classes. A class is a template for creating objects, describing what an object represents or which methods the object can use. A class is what holds fields and methods to describe the properties and behavior of objects.

Example:

public class Car {
String model;
int year;

public static void main(String[] args) {
Car myCar = new Car();
myCar.model = "Tesla Model 3";
myCar.year = 2020;
System.out.println("Car Model: " + myCar.model);
System.out.println("Car Year: " + myCar.year);
}
}

In the following example, we have a class Car, which has two fields: model and year. In addition to that, we have a method named displayDetails that displays the details of the car. Furthermore, we created an object myCar of the type Car, assigned values to its fields, and called the method to print these values.

Interfaces

An interface in Java only contains the method definitions the class needs to implement. They provide a way to achieve abstraction and multiple inheritance in Java.

Example:

interface Vehicle {
void start();
void stop();
}

public class Bike implements Vehicle {
public void start() {
System.out.println("Bike started");
}

public void stop() {
System.out.println("Bike stopped");
}

public static void main(String[] args) {
Bike myBike = new Bike(); // Creating an object of the Bike class
myBike.start(); // Calling the start method
myBike.stop(); // Calling the stop method
}
}

In this example, we define an interface Vehicle, which has two method declarations: startand stop. Now implement this interface in the class Bike, providing the method definitions. We create an object myBikeof the Bikeclass and call the methods.

Arrays

Arrays in Java are used to store multiple values of the same type in a single variable. In other words, it is a collection of variables of the same kind, and the only difference between these variables is their index.

Example:

public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number: " + number);
}
}
}

Here, we declare an integer array numbers with five elements. We use an enhanced for loop to iterate over the array and print each element.

Summary of Reference Data Types:

Reference data types allow Java to manage complex data structures and objects, enabling the development of sophisticated applications. They provide the foundation for object-oriented programming in Java.

Summary of Reference Data Types:

Type Conversion and Casting

We have seen type conversion and casting as a way to change the data type of a variable. You can think about why it is needed: to work with different data types.

Implicit Type Conversion (Widening Conversion)

The implicit type conversion, also known as widening conversion, is a process in which the compiler converts the data type that is narrower to a wider data type without any effort on the part of the programmer. In this conversion, it can’t be dangerous, and subsequently, it will not cause data to be lost.

Implicit Type Conversion:

public class ImplicitConversion {
public static void main(String[] args) {
int num = 100;
double decimal = num; // int to double conversion
System.out.println("Value of double: " + decimal);
}
}

Here, the integer variable num is automatically converted to a double when assigned to the decimal variable. This type of conversion is called implicit or widening conversion.

Explicit Type Conversion (Narrowing Conversion or Casting)

Explicit type conversion can also be referred to as a narrowing conversion or a casting. This is where one would have to manually convert a more significant data type into a smaller one. The process might result in some data getting lost and should, therefore, be done through a cast operator.

public class ExplicitConversion {
public static void main(String[] args) {
double decimal = 9.78;
int num = (int) decimal; // double to int conversion
System.out.println("Value of int: " + num);
}
}

In the above example, we explicitly cast the double variable decimalinto an integer by prefixing (int) to the variable. This is known as explicit or narrowing conversion, which may cause loss of data.

String to Integer Conversion:

public class StringToInt {
public static void main(String[] args) {
String str = "123";
int num = Integer.parseInt(str); // String to int conversion
System.out.println("Converted integer: " + num);
}
}

Here, the Integer.parseInt method converts the string str to an integer and assigns it to the variable num.

Integer to String Conversion:

public class IntToString {
public static void main(String[] args) {
int num = 123;
String str = Integer.toString(num); // int to String conversion
System.out.println("Converted string: " + str);
}
}

In this example, the Integer.toString method converts the integer num to a string and assigns it to the variable str.

Summary of Type Conversion:

Conclusion

The knowledge of variables and data types is fundamental for any Java programmer to be good at it. This tutorial taught us the basics of primitive types, reference data types, type conversion, and casting. Now, we can declare data and manipulate it correctly in our Java programs.

Github

References

Explore More on Spring and Java Development:

Enhance your skills with our selection of articles:

  • Java Lambda Expressions: Techniques for Advanced Developers (Jun 19, 2024): Dive deep into advanced usage of lambda expressions in Java. Read More
  • Mastering Spring Security: Roles and Privileges (Jun 19, 2024): Learn the essentials of managing roles and privileges in Spring Security. Read More
  • Publishing Your Java Library to Maven Central: A Step-by-Step Tutorial (Mar 25, 2024): A comprehensive guide to making your Java library accessible to millions of developers worldwide. Read More
  • The Art of Unit Testing: Elevate Your Code with Effective Mocks (Mar 13, 2024): A complete guide to using mocks in unit testing, emphasizing the benefits of component isolation. Read More
  • Spring Beans Mastery (Dec 17, 2023): Unlock advanced application development techniques. Read More
  • JSON to Java Mapping (Dec 17, 2023): Streamline your data processing. Read More
  • Spring Rest Tools Deep Dive (Nov 15, 2023): Master client-side RESTful integration. Read More
  • Dependency Injection Insights (Nov 14, 2023): Forge better, maintainable code. Read More
  • Spring Security Migration (Sep 9, 2023): Secure your upgrade smoothly. Read More
  • Lambda DSL in Spring Security (Sep 9, 2023): Tighten security with elegance. Read More
  • Spring Framework Upgrade Guide (Sep 6, 2023): Navigate to cutting-edge performance. Read More

--

--

Marcelo Domingues
devdomain

🚀 Senior Software Engineer | Crafting Code & Words | Empowering Tech Enthusiasts ✨ 📲 LinkedIn: https://www.linkedin.com/in/marcelogdomingues/