DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • What Is Ant, Really?
  • Protecting Your Domain-Driven Design from Anemia
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations
  • Clean Unit Testing

Trending

  • Behavior-Driven Development (BDD) Framework for Terraform
  • Advanced-Data Processing With AWS Glue
  • Navigating the Digital Frontier: A Journey Through Information Technology Progress
  • RRR Retro and IPL for Rewards and Recognition
  1. DZone
  2. Coding
  3. Languages
  4. Primitives vs Objects in Java

Primitives vs Objects in Java

Are there truly any non-null issues when using primitives instead of Objects?

By 
John Vester user avatar
John Vester
DZone Core CORE ·
Jan. 02, 19 · Analysis
Like (12)
Save
Tweet
Share
147.5K Views

Join the DZone community and get the full member experience.

Join For Free

Disclaimer — in this article, I am presenting what I've found, hoping to gain some real-life feedback on the perspectives noted below. I am certainly not an expert on the aspects discussed in this article. Instead, I would enjoy hearing your feedback in the comments.

On a recent Java API project, I found myself creating entity and DTO objects to fuel a RESTful API consumed by JavaScript-based clients.

As an example, let's assume the following table and attributes were created in my SampleEntity class:

@Data
@Entity
public class SampleEntity implements Serializable {
private static final long serialVersionUID = 1L;

@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long someId;
private Integer someInteger;
private Boolean isAcive;
private String someString
private List<Object> someObject;

public SampleEntity() {}
}


On the DTO side, I created an object similar to what was listed below:

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class SampleDto {
private Long someId;
private Integer someInteger;
private Boolean isActive;
private String someString;
private List<Long> someObjectIds;

public SampleDto() {}
}


In the actual example, the DTO is a slimmed-down version of the Entity object. To keep the payload lean and only utilize what the client needs to do render the necessary data, for this example, the DTO returns a list of Long (ids) for the Objects that exist with the Entity class.

When the code went through the PR process, I was asked to change the Long , Integer , and Boolean  objects to long, int, and boolean primitives. The reason I was given this was because of the smaller memory use in using primitives over objects.

Seemed Like a Good Idea

I found this article on baeldung.com.

At first glance, it appeared to be a valid rationale, since the memory usage difference is noticeable. With thousands of clients using the application, that difference could wind up relating to performance.

Here is a diagram from the article:

Image title

In this case, none of the values would ever have null values, so I wasn't going to have to worry about handling that scenario.

Stack V. Heap

However, when I started looking deeper, I noticed there is a difference between stack and heap memory allocation, mostly after reading this page from stackoverflow.com.

It appears that primitives are always stored on the stack, where Objects are stored on the heap and pulled into the stack when needed by the JVM for processing. As a result, if my entire application utilized primitives (where possible) for every entity, DTO, services, repositories, etc., it seems as if I might have an issue with such much of the stack memory being allocated.

I understand there is garbage collection with the JVM, but is it enough to keep up with this approach, especially with larger-scale applications being utilized by thousands (or tens of thousands) of users concurrently?

null != -1

Another challenge with the primitive approach is that null is not an option.

As I noted in the case above, the someId , someInteger, or isActive  attributes could not be null based upon the database design. If there were, I would avoid switching from an Object to a primitive to avoid making assumptions when something is null.

As an example, if the long value is used to handle the record ID in the database. It is *probably* okay to set the value to -1 when there is not currently a value. Remember, null values can exist when you initially create a new record in your client. Before the request is persisted, the value is likely null.

Going with the -1 approach, somewhere you would need to look for the -1 and convert that to null so that the value of -1 is not stored in the database. Seems like just using the Object makes a lot more sense than having everyone in the development stream remember this rule, right?

Conclusion

When designing and developing applications, I always want to make sure I am taking the right approach in providing a solution. Like everything else, I want to do the right thing.

My approach was questioned via a PR, which led to some research, which then led to this article — with a hope to gain feedback from other developers who have already allocated time and energy to the primitive vs. Object option.

At the end of the PR, I did convert the Objects to primitives, but only when there wasn't a driving reason (like null values) to avoid making the change.

I am very interested in hearing your feedback!

Object (computer science) Java (programming language) Database

Opinions expressed by DZone contributors are their own.

Related

  • What Is Ant, Really?
  • Protecting Your Domain-Driven Design from Anemia
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations
  • Clean Unit Testing

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: