Zum Hauptinhalt springen

Basics

What is the difference between and abstract class and and interface and when to use which one?

In Java, every class implicitly inherits from a specific root class. Which class is it, and what is the default behavior of its '.equals()' method?

The 'Object' class; it checks if two references point to the same memory location. All Java classes descend from Object, which uses the '==' operator logic for its default equality check.

Is it a best practice to always use Long type for database table id columns in Java entity class?

The decision to use Long versus int for an ID property in a Java entity class depends on the underlying database schema and scalability requirements, rather than a universal rule. Since an entity class serves as a data holder for a row, the Java type must safely accommodate the database column's value range. If the database column is bigint or unsigned int, the entity property must be Long. This is critical because Java's int is a signed 32-bit value; a database unsigned int can exceed the positive range of a Java int, potentially causing overflow errors. While using int in the entity is technically sufficient for a standard signed 32-bit int column, developers often default to Long to future-proof the application. If a table grows significantly and requires migration to bigint later, having Long already defined avoids extensive refactoring across the codebase. However, blindly declaring Long for every entity is unnecessary. For static lookup tables with fixed, low cardinality - such as gender, country, or state - the ID values will never exceed the integer limit, making int the appropriate and semantic choice.

Why do we need an empty (no-argument) constructor in models when using Spring Boot?

This practice is required by the underlying libraries Spring Boot uses, specifically JPA (API for ORM frameworks like Hibernate) and Jackson (JSON processor for JAVA).

JPA and Jackson function by using Reflection (a mechanism that allows a running program to examine and modify its own internal structure, such as classes, methods, and fields): they must first create an instance of our class before they can fill it with data from the database or a web request. To do this, they call the "no-argument" constructor.

  • By default, if we write a class with no constructor, Java automatically provides a default empty one.
  • As soon as we add a constructor with arguments (e.g., to easily create object in our code), Java removes the default empty one.
  • So we need to add the empty one back. Without it, JPA or Jackson will throw an InstantiationException because they don't know which values to pass into our custom constructor to create the object.