Skip to lesson

Column types to Java types, dates and NULL

A shop bill must show exact prices, real dates and honest blanks, but every value reaches Java through a getter. Which getter keeps each column exact, and which one silently changes the value?

INT, BIGINT, VARCHAR and BOOLEAN

Type mapping is the rule for which Java type holds each MySQL column type, and so which getter reads it: INT goes to int with getInt, VARCHAR to String with getString.

Read numbers, text and booleans from the accessories, then print the Java class the driver picks for each column.

Example 1 · Numbers, text and booleans from the products table

Runs in: a Maven project with the MySQL driver and the ShopLite database

BasicTypesDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class BasicTypesDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            String sql = "SELECT product_id, sku, stock, is_active FROM products "                    + "WHERE category_id = 4 ORDER BY product_id";            try (ResultSet rs = st.executeQuery(sql)) {                while (rs.next()) {                    int id = rs.getInt("product_id");                    String sku = rs.getString("sku");                    int stock = rs.getInt("stock");                    boolean active = rs.getBoolean("is_active");                    System.out.println(id + " " + sku + " stock=" + stock + (active ? "" : " (not on sale)"));                }            }
            // COUNT(*) comes back as BIGINT, so read it as a long            try (ResultSet rs = st.executeQuery("SELECT COUNT(*) AS item_rows FROM order_items")) {                rs.next();                long itemRows = rs.getLong("item_rows");                System.out.println("order_items rows: " + itemRows);            }
            // getObject shows the Java type the driver picks for each column            try (ResultSet rs = st.executeQuery(                    "SELECT product_id, sku, price, is_active, (SELECT COUNT(*) FROM orders) AS orders "                            + "FROM products WHERE product_id = 1")) {                rs.next();                for (int i = 1; i <= 5; i++) {                    System.out.println(rs.getMetaData().getColumnLabel(i) + " -> "                            + rs.getObject(i).getClass().getSimpleName());                }            }        }    }}
Output
6 ACC-AD141 stock=120
7 ACC-PB20K stock=60
8 ACC-M331 stock=0
15 ACC-USBC1 stock=0 (not on sale)
order_items rows: 28
product_id -> Integer
sku -> String
price -> BigDecimal
is_active -> Boolean
orders -> Long

What this code does

  • Each getter matches its column: getInt for INT, getString for VARCHAR, getBoolean for the TINYINT(1) column is_active.
  • COUNT(*) is a BIGINT, so it is read with getLong. The last loop prints the Java class the driver chose for each column, including Long for the count.
  • Only the USB-C cable has is_active = FALSE, so only it prints (not on sale).

BIGINT goes to long with getLong. MySQL has no real true/false type: BOOLEAN is another name for TINYINT(1), a tiny number that holds 0 or 1, and the driver turns it into a boolean.

COUNT(*) comes back as BIGINT, because a count can grow past the int limit of about 2.1 billion. (SUM of an INT column comes back as DECIMAL; getLong reads it fine when you want a whole number.)

DECIMAL to BigDecimal: money is never double

BigDecimal is the Java type for exact decimal numbers, and the right type for money. getBigDecimal reads a DECIMAL(10,2) price such as 17999.00 exactly.

Add four GST amounts as a double and as a BigDecimal, and compare the totals.

Example 2 · GST with double versus BigDecimal

Runs in: a Maven project with the MySQL driver and the ShopLite database

MoneyTypesDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class MoneyTypesDemo {    public static void main(String[] args) throws SQLException {        String sql = "SELECT name, price, price * 0.18 AS gst FROM products "                + "WHERE category_id = 4 ORDER BY product_id";        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            double gstAsDouble = 0;            BigDecimal gstExact = BigDecimal.ZERO;            try (ResultSet rs = st.executeQuery(sql)) {                while (rs.next()) {                    BigDecimal gst = rs.getBigDecimal("gst");                    System.out.println(rs.getString("name") + ": price " + rs.getBigDecimal("price") + ", GST " + gst);                    gstAsDouble += rs.getDouble("gst");     // wrong for money                    gstExact = gstExact.add(gst);           // right for money                }            }            System.out.println("Total GST with double:     " + gstAsDouble);            System.out.println("Total GST with BigDecimal: " + gstExact.setScale(2, RoundingMode.HALF_UP));
            // getInt on a DECIMAL silently drops the paise            try (ResultSet one = st.executeQuery("SELECT 199.99 AS cable_price")) {                one.next();                System.out.println("getInt(199.99) = " + one.getInt("cable_price"));            }        }    }}
Output
boAt Airdopes 141: price 1299.00, GST 233.8200
Mi Power Bank 20000mAh: price 2199.00, GST 395.8200
Logitech M331 Silent Mouse: price 849.00, GST 152.8200
USB-C Cable 1m: price 199.00, GST 35.8200
Total GST with double:     818.2800000000001
Total GST with BigDecimal: 818.28
getInt(199.99) = 199

What this code does

  • Every price prints exactly (1299.00), and MySQL's price * 0.18 keeps four decimal places (233.8200).
  • Adding the same four GST values gives 818.2800000000001 as double but exactly 818.28 as BigDecimal, rounded once at the end.
  • getInt on 199.99 returns 199: the paise vanish with no error.

ShopLite stores every price as DECIMAL(10,2), so 17999.00 in MySQL is exactly 17999.00 in Java. A double stores numbers in binary, and most decimal fractions such as 0.82 have no exact binary form: each value is off by a tiny amount, and adding many values makes the error visible. On a bill, an invoice or a UPI refund, even one paisa of difference is a bug.

When you multiply in SQL (price * 0.18), MySQL keeps more decimal places, so round once, at the end, with setScale(2, RoundingMode.HALF_UP).

Find the bug

Which line loses money?

Tap the line that can change a price or a total.

The GST of four products is added into a BigDecimal total.

Round 1 of 3
Rule: money columns are DECIMAL in MySQL and BigDecimal in Java, from the getter to the final print. Never getDouble, never getInt.

DATE and DATETIME to LocalDate and LocalDateTime

LocalDateTime is a Java date and time with no time zone. It matches the MySQL DATETIME type and is read with rs.getObject("ordered_at", LocalDateTime.class).

Read order dates as LocalDateTime and LocalDate, then count the days since the customer joined.

Example 3 · Order dates as LocalDateTime and LocalDate

Runs in: a Maven project with the MySQL driver and the ShopLite database

DatesDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.util.Locale;
public class DatesDemo {    static final DateTimeFormatter SHOW = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a", Locale.ENGLISH);
    public static void main(String[] args) throws SQLException {        String sql = "SELECT c.full_name, c.created_at, o.order_id, o.ordered_at, DATE(o.ordered_at) AS order_day "                + "FROM customers c JOIN orders o ON o.customer_id = c.customer_id "                + "WHERE c.customer_id = 1 ORDER BY o.ordered_at";        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement();             ResultSet rs = st.executeQuery(sql)) {
            while (rs.next()) {                LocalDateTime joined = rs.getObject("created_at", LocalDateTime.class);   // DATETIME                LocalDateTime orderedAt = rs.getObject("ordered_at", LocalDateTime.class);                LocalDate orderDay = rs.getObject("order_day", LocalDate.class);         // DATE                long days = ChronoUnit.DAYS.between(joined.toLocalDate(), orderDay);
                System.out.println(rs.getString("full_name") + ", order " + rs.getInt("order_id"));                System.out.println("  placed " + orderedAt.format(SHOW) + " (" + orderDay.getDayOfWeek() + ")");                System.out.println("  " + days + " days after joining on " + joined.toLocalDate());            }        }    }}
Output
Asha Rao, order 1
  placed 02 Jul 2026, 10:12 AM (THURSDAY)
  59 days after joining on 2026-05-04
Asha Rao, order 3
  placed 18 Jul 2026, 01:05 PM (SATURDAY)
  75 days after joining on 2026-05-04
Asha Rao, order 10
  placed 30 Aug 2026, 12:25 PM (SUNDAY)
  118 days after joining on 2026-05-04

What this code does

  • getObject("ordered_at", LocalDateTime.class) gives a LocalDateTime, formatted with an English pattern; DATE(o.ordered_at) comes back as a LocalDate.
  • ChronoUnit.DAYS.between counts days from the signup date to the order day: 59 days from 4 May to 2 July.

getObject(column, Type.class) reads a column straight into the Java type you name: LocalDate.class for a DATE and LocalDateTime.class for a DATETIME. You then have the normal java.time methods: formatting, getDayOfWeek(), ChronoUnit.DAYS.between.

Older code uses getDate and getTimestamp, which return the old java.sql.Date and java.sql.Timestamp. They mix in your computer's time zone and have an awkward API, so new code asks for LocalDate and LocalDateTime directly. MySQL TIMESTAMP is stored in UTC and converted with the connection's time zone, so the same row can read differently if the server and application zones differ. ShopLite uses DATETIME, which is returned exactly as written.

NULL columns: hidden zeros and how to see them

NULL in SQL means "no value": a customer who gave no phone, a category with no parent. Object getters return Java null for it, but primitive getters return a hidden 0 or false.

Read a NULL parent as an int and a NULL phone as text, and see what each does.

Example 4 · The hidden zero and the null crash

Runs in: a Maven project with the MySQL driver and the ShopLite database

NullTrapDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class NullTrapDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            try (ResultSet rs = st.executeQuery(                    "SELECT name, parent_id FROM categories WHERE category_id <= 3 ORDER BY category_id")) {                while (rs.next()) {                    int parentId = rs.getInt("parent_id");   // NULL becomes 0                    System.out.println(rs.getString("name") + " -> parent " + parentId);                }            }
            try (ResultSet rs = st.executeQuery(                    "SELECT full_name, phone FROM customers WHERE customer_id IN (2, 3) ORDER BY customer_id")) {                while (rs.next()) {                    String phone = rs.getString("phone");    // NULL becomes null                    System.out.println(rs.getString("full_name") + " -> phone " + phone                            + ", length " + phone.length());                }            }        }    }}
Output
Electronics -> parent 0
Mobiles -> parent 1
Laptops -> parent 1
Ravi Kumar -> phone 9876543202, length 10
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "phone" is null
	at NullTrapDemo.main(NullTrapDemo.java:26)

What this code does

  • Electronics has parent_id = NULL, but getInt returns 0, so the program claims a parent 0 that does not exist.
  • Meena Iyer has no phone. getString correctly returns null, and phone.length() then crashes with a NullPointerException (the output shows the error from a Maven build).

Example 5 · Two fixes for NULL

Runs in: a Maven project with the MySQL driver and the ShopLite database

NullFixDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class NullFixDemo {    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));             Statement st = con.createStatement()) {
            System.out.println("Fix 1: getInt, then wasNull()");            try (ResultSet rs = st.executeQuery(                    "SELECT name, parent_id FROM categories WHERE category_id <= 3 ORDER BY category_id")) {                while (rs.next()) {                    int parentId = rs.getInt("parent_id");                    boolean noParent = rs.wasNull();          // asks about the LAST column read                    System.out.println("  " + rs.getString("name") + " -> "                            + (noParent ? "top level" : "parent " + parentId));                }            }
            System.out.println("Fix 2: getObject(column, Integer.class)");            try (ResultSet rs = st.executeQuery(                    "SELECT name, parent_id FROM categories WHERE category_id <= 3 ORDER BY category_id")) {                while (rs.next()) {                    Integer parentId = rs.getObject("parent_id", Integer.class);   // null stays null                    System.out.println("  " + rs.getString("name") + " -> "                            + (parentId == null ? "top level" : "parent " + parentId));                }            }
            System.out.println("Text columns: check for null before using the value");            try (ResultSet rs = st.executeQuery(                    "SELECT full_name, phone FROM customers WHERE customer_id IN (2, 3) ORDER BY customer_id")) {                while (rs.next()) {                    String phone = rs.getString("phone");                    System.out.println("  " + rs.getString("full_name") + " -> "                            + (phone == null ? "no phone given" : phone));                }            }        }    }}
Output
Fix 1: getInt, then wasNull()
  Electronics -> top level
  Mobiles -> parent 1
  Laptops -> parent 1
Fix 2: getObject(column, Integer.class)
  Electronics -> top level
  Mobiles -> parent 1
  Laptops -> parent 1
Text columns: check for null before using the value
  Ravi Kumar -> 9876543202
  Meena Iyer -> no phone given

What this code does

  • Fix 1 reads with getInt and asks wasNull() straight after. Fix 2 reads an Integer with getObject("parent_id", Integer.class), which is null for NULL.
  • For text, the value is already null; the program checks it before using it and prints a friendly message instead.

Getters that return primitives cannot return null: getInt returns 0 for NULL, getBoolean returns false and getDouble returns 0.0. This hidden zero is a common source of wrong reports.

There are two fixes. Call rs.wasNull() right after the getter, or read the column with getObject("parent_id", Integer.class), which returns an Integer that is null for NULL. The second fix keeps the value and the "no value" case together, so it suits records and Optional.

Predict the output

What does NULL become?

Electronics has parent_id NULL. Pick what is printed.

Round 1 of 3

The column is read with a primitive getter.

ResultSet rs = st.executeQuery("SELECT parent_id FROM categories WHERE category_id = 1");
rs.next();
System.out.println(rs.getInt("parent_id"));
wasNull() only answers for the column you read last. Call it immediately after that getter, before reading any other column.

A type-mapping table to keep next to your code

Keep this table of getters, one per MySQL column type used in ShopLite, open while you write JDBC code.

Java
int id              = rs.getInt("product_id");                      // INTlong orders         = rs.getLong("orders");                         // BIGINT, COUNT(*)String sku          = rs.getString("sku");                          // VARCHAR, CHARboolean active      = rs.getBoolean("is_active");                   // BOOLEAN = TINYINT(1)BigDecimal price    = rs.getBigDecimal("price");                    // DECIMALLocalDate day       = rs.getObject("order_day", LocalDate.class);   // DATELocalDateTime at    = rs.getObject("ordered_at", LocalDateTime.class); // DATETIME, TIMESTAMPInteger parentId    = rs.getObject("parent_id", Integer.class);     // INT that may be NULLString phone        = rs.getString("phone");                        // VARCHAR that may be NULL
  • A column that allows NULL gets a wrapper type (Integer, Long) via getObject(col, Integer.class), or a wasNull() check.
  • Text and BigDecimal getters already return null for NULL; check before calling methods on the value.
  • Asking for an impossible conversion fails: getObject("name", LocalDate.class) throws SQLDataException: Cannot convert string ... to java.time.LocalDate value.
  • getInt on a text column fails at run time, for example getInt("sku") throws SQLDataException: Cannot determine value type from string 'ACC-AD141'. The getter must match the column.

Fix the error

Fix the getter

Read the real error, then pick the line that fixes it.

Round 1 of 2

The SKU column is text, such as ACC-AD141.

ResultSet rs = st.executeQuery("SELECT sku FROM products");
rs.next();
int sku = rs.getInt("sku");

Error

SQLDataException: Cannot determine value type from string 'ACC-AD141'

Next step

Check your understanding

12 quick questions