Java Data Types β Primitive & Non-Primitive
A complete beginner's guide to all Java data types β 8 primitive types, non-primitive reference types, sizes, ranges, default values, literals, wrapper classes, autoboxing, and type casting with working code examples.
Last Updated
March 2026
Read Time
18 min
Level
Beginner
Java Data Types β Overview
In the previous chapter, we learned about Java Blocks β code blocks, static blocks, instance blocks, and scope rules. Now we cover one of the most foundational topics in Java: Data Types.
Every variable in Java has a data type β it tells the compiler two things: what kind of value the variable can hold, and how much memory to allocate. Java is a statically typed language, which means you must declare the data type of every variable at compile time. This is what makes Java programs reliable, predictable, and fast.
- βΆ
What you will learn: Both categories of Java data types, all 8 primitive types in depth, non-primitive reference types, Java literals, wrapper classes, autoboxing/unboxing, type casting, and how to choose the right type for your use case.
Two Categories of Java Data Types
Java data types fall into exactly two categories. Understanding the fundamental difference between them is the first step to mastering Java memory management and object-oriented programming.
// PRIMITIVE β value stored directly in the variable
int age = 21; // 'age' holds the value 21 directly
// NON-PRIMITIVE β variable holds a reference (memory address)
String name = "Rahul"; // 'name' holds the address of the String object
// the actual characters 'R','a','h','u','l' are on the heap
// null means the reference variable points to nothing
String city = null; // city holds no address β not pointing to any objectPrimitive Data Types β All 8 Types
Java has exactly 8 primitive data types. Their sizes are fixed by the Java specification β unlike C/C++ where sizes can vary by platform. This platform independence is a key part of Java's Write Once, Run Anywhere guarantee.
byte, short, int, long β for whole numbers. int is the default choice. Use long for very large numbers. Use byte/short only when memory is critically limited.
float, double β for decimal numbers. double is the default choice (and the default for decimal literals). Use float only when memory is tightly constrained.
char β stores a single Unicode character using 16-bit UTF-16 encoding. Can also store any integer from 0 to 65,535 representing a Unicode code point.
boolean β stores only true or false. Used for conditions, flags, and logical decisions. Cannot be cast to/from numeric types (unlike C/C++).
Integer Types β byte, short, int, long
Java has four integer types for storing whole numbers (no decimal part). They differ only in size and therefore the range of values they can hold. int is the most commonly used integer type.
byte β 1 Byte
byte is the smallest integer type β 1 byte (8 bits). Range: -128 to 127. Used when memory saving is critical β in large arrays, file/network I/O streams, or image pixel data.
byte minByte = -128; // minimum value
byte maxByte = 127; // maximum value
byte pixelValue = 64; // grayscale pixel β 0 to 127 range
byte fileFlag = 0x0A; // hexadecimal literal β value is 10
// Overflow β byte wraps around
byte overflow = (byte) 128; // 128 overflows β becomes -128
System.out.println(overflow); // -128short β 2 Bytes
short is 2 bytes (16 bits). Range: -32,768 to 32,767. Rarely used in modern Java β int is preferred unless you are working with binary protocols, audio samples, or legacy systems.
short minShort = -32768; // minimum value
short maxShort = 32767; // maximum value
short year = 2026; // fits comfortably in a short
short audioSample = 15000; // raw PCM audio sampleint β 4 Bytes (Default Integer Type)
int is 4 bytes (32 bits). Range: -2,147,483,648 to 2,147,483,647 (about Β±2.1 billion). This is the default integer type in Java β integer literals like 42 are int by default. Use int for counting, indexing, loop variables, and general arithmetic.
int age = 21;
int year = 2026;
int population = 1400000000; // India population β fits in int
int maxInt = Integer.MAX_VALUE; // 2147483647
int minInt = Integer.MIN_VALUE; // -2147483648
// Numeric literals with underscore (Java 7+) β for readability
int oneMillion = 1_000_000; // same as 1000000
int cardNumber = 1234_5678_9012_3456; // not valid β too large for int
// Integer arithmetic
int a = 10, b = 3;
System.out.println(a / b); // 3 β integer division, truncates
System.out.println(a % b); // 1 β remainder (modulo)long β 8 Bytes
long is 8 bytes (64 bits). Range: -9.2 Γ 10ΒΉβΈ to 9.2 Γ 10ΒΉβΈ. Use long when your value exceeds the int range β world population, millisecond timestamps, file sizes in bytes, database IDs. Must add L or l suffix to long literals (uppercase L preferred β lowercase l looks like 1).
long worldPopulation = 8_100_000_000L; // 8.1 billion β exceeds int
long fileSize = 10_737_418_240L; // 10 GB in bytes
long epochMs = 1_700_000_000_000L; // Unix timestamp in ms
long maxLong = Long.MAX_VALUE; // 9223372036854775807
// Missing L suffix β compile error if value > Integer.MAX_VALUE
// long big = 8100000000; β ERROR: integer number too large
long big = 8_100_000_000L; // β
correct with L suffix
System.out.println("World population: " + worldPopulation);Output
World population: 8100000000Floating-Point Types β float, double
Java has two floating-point types for storing decimal numbers. Both follow the IEEE 754 standard. The key difference is precision and memory size.
float β 4 Bytes, Single Precision
float is 4 bytes (32 bits) β single-precision IEEE 754. Accurate to approximately 7 significant decimal digits. Must add f or F suffix to float literals β otherwise the compiler treats them as double.
float pi = 3.14f; // 'f' suffix required
float price = 99.99f;
float tempC = 36.6f; // body temperature
float maxFloat = Float.MAX_VALUE; // ~3.4 Γ 10^38
// Without 'f' suffix β compile error
// float x = 3.14; β ERROR: possible lossy conversion from double to float
// Precision limitation of float
float f1 = 1.0f / 3.0f;
System.out.println(f1); // 0.33333334 β only ~7 digits accuratedouble β 8 Bytes, Double Precision (Default)
double is 8 bytes (64 bits) β double-precision IEEE 754. Accurate to approximately 15β16 significant decimal digits. Decimal literals like 3.14 are double by default. Prefer double for all general decimal calculations.
double pi = 3.141592653589793; // no suffix needed
double salary = 75000.50;
double distance = 384400.0; // moon distance in km
double maxDouble = Double.MAX_VALUE; // ~1.8 Γ 10^308
// Better precision than float
double d1 = 1.0 / 3.0;
System.out.println(d1); // 0.3333333333333333 β ~15 digits accurate
// Scientific notation literal
double avogadro = 6.022e23; // 6.022 Γ 10^23
double electron = 1.6e-19; // 1.6 Γ 10^-19 coulombs
System.out.println(avogadro); // 6.022E23Output
0.3333333333333333 6.022E23- βΆ
β οΈ Floating-point precision warning: Neither float nor double can represent all decimal values exactly β this is a property of IEEE 754 binary representation. Example:
0.1 + 0.2does not equal exactly0.3in Java (or any language using IEEE 754). For exact decimal arithmetic (money, banking), usejava.math.BigDecimal.
Character Type β char
char is a 2-byte (16-bit) unsigned integer that stores a single character using UTF-16 Unicode encoding. Range: 0 to 65,535 (Unicode code points \u0000 to \uFFFF). Unlike C/C++ where char is 1 byte (ASCII only), Java's char supports the full Unicode character set.
// Character literals β enclosed in SINGLE quotes
char letter = 'A';
char digit = '7';
char space = ' ';
char newline = '\n'; // escape sequence
char tab = '\t'; // escape sequence
// Unicode escape sequence
char rupee = '\u20B9'; // βΉ Indian Rupee symbol
char heart = '\u2665'; // β₯ Heart symbol
char omega = '\u03A9'; // Ξ© Omega symbol
// char can be treated as an unsigned integer
char ch = 'A';
System.out.println(ch); // A
System.out.println((int) ch); // 65 β ASCII/Unicode value of 'A'
System.out.println(ch + 1); // 66 β arithmetic on char returns int
System.out.println((char)(ch + 1)); // B β cast back to char
// char arithmetic β classic use
for (char c = 'A'; c <= 'E'; c++) {
System.out.print(c + " "); // A B C D E
}Output
A 65 66 B A B C D ECommon Escape Sequences for char
Boolean Type β boolean
boolean stores only two values: true or false. It is used for conditions, flags, control-flow decisions, and any binary state. The actual memory size is JVM-dependent (often treated as a 32-bit int internally for alignment, though it represents only 1 bit of information).
boolean isLoggedIn = true;
boolean isExpired = false;
boolean hasPassed = true;
// Boolean from comparison expressions
int score = 85;
boolean distinction = score >= 90; // false β 85 is not >= 90
boolean firstClass = score >= 60; // true
// Boolean in control flow
if (isLoggedIn) {
System.out.println("Welcome back!");
}
// Boolean from method return
String name = "Java";
boolean startsWithJ = name.startsWith("J"); // true
boolean isEmpty = name.isEmpty(); // false
System.out.println("Distinction : " + distinction);
System.out.println("First Class : " + firstClass);
System.out.println("Starts with J: " + startsWithJ);Output
Welcome back! Distinction : false First Class : true Starts with J: true- βΆ
β οΈ Java vs C/C++: In Java,
booleanis not interchangeable with integers. You cannot writeif (1)or cast a boolean to int.trueandfalseare the only valid values β period. - βΆ
π‘ Naming convention: Boolean variables and methods are typically named with the
is,has,can, orshouldprefix βisActive,hasPermission,canEditβ making the intent immediately clear.
Java Literals β Writing Values in Code
A literal is a fixed value written directly in the source code β the actual data itself, not a variable or expression. Java supports several forms of literals for different data types.
Integer Literals
// Decimal (base 10) β default, no prefix
int decimal = 255;
// Binary (base 2) β prefix 0b or 0B (Java 7+)
int binary = 0b11111111; // same as 255
// Octal (base 8) β prefix 0 (zero)
int octal = 0377; // same as 255
// Hexadecimal (base 16) β prefix 0x or 0X
int hex = 0xFF; // same as 255
// Underscore separator (Java 7+) β improves readability
int million = 1_000_000;
long creditCard = 1234_5678_9012_3456L;
int rgb = 0xFF_A5_00; // orange color in hex
System.out.println(decimal + " " + binary + " " + octal + " " + hex);Output
255 255 255 255Floating-Point Literals
double d1 = 3.14; // standard decimal β double by default
double d2 = 3.14d; // explicit double suffix (optional)
float f1 = 3.14f; // float β 'f' suffix REQUIRED
// Scientific (exponential) notation
double avogadro = 6.022e23; // 6.022 Γ 10^23
double planck = 6.626e-34; // 6.626 Γ 10^-34
// Special values
double posInf = Double.POSITIVE_INFINITY; // 1.0 / 0.0
double negInf = Double.NEGATIVE_INFINITY; // -1.0 / 0.0
double nan = Double.NaN; // 0.0 / 0.0 β Not a Number
System.out.println(1.0 / 0.0); // Infinity
System.out.println(-1.0 / 0.0); // -Infinity
System.out.println(0.0 / 0.0); // NaNOutput
Infinity -Infinity NaNchar, boolean, and String Literals
// char literal β SINGLE quotes, exactly ONE character
char grade = 'A';
char unicode = '\u20B9'; // βΉ
// boolean literals β only two values
boolean t = true;
boolean f = false;
// String literal β DOUBLE quotes (non-primitive, but very common)
String name = "Tech Sustainify";
// Text Block (Java 15+) β multi-line String literal
String json = """
{
"name": "Java",
"version": 21
}
""";
// null literal β for any reference type
String city = null;Non-Primitive (Reference) Data Types
Non-primitive types are also called reference types because a variable of this type stores a reference (memory address) to where the object data lives on the heap β not the data itself. All non-primitive types ultimately extend java.lang.Object.
import java.util.ArrayList;
public class NonPrimitiveDemo {
public static void main(String[] args) {
// String
String language = "Java";
System.out.println(language.length()); // 4
System.out.println(language.toUpperCase()); // JAVA
// Array
int[] scores = {95, 82, 78, 91};
System.out.println(scores[0]); // 95
System.out.println(scores.length); // 4
// null reference
String city = null;
System.out.println(city); // null
// city.length(); β NullPointerException at runtime!
// ArrayList (class from java.util)
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Apple");
System.out.println(fruits); // [Mango, Apple]
}
}Output
4 JAVA 95 4 null [Mango, Apple]String β Most Used Non-Primitive Type
String is by far the most commonly used non-primitive type in Java. It represents an immutable sequence of Unicode characters. Once created, a String's value cannot be changed β any modification creates a new String object.
// Two ways to create a String
String s1 = "Hello"; // String literal β stored in String Pool
String s2 = new String("Hello"); // new object on heap β NOT recommended
// String is immutable
String name = "Java";
name.toUpperCase(); // does NOT change 'name'
System.out.println(name); // Java β unchanged
name = name.toUpperCase(); // reassign the reference to a new String
System.out.println(name); // JAVA
// String concatenation
String firstName = "Rahul";
String lastName = "Sharma";
String fullName = firstName + " " + lastName; // "Rahul Sharma"
// Useful String methods
System.out.println(fullName.length()); // 12
System.out.println(fullName.charAt(0)); // R
System.out.println(fullName.contains("Rahul")); // true
System.out.println(fullName.replace("Rahul", "Priya")); // Priya Sharma
System.out.println(fullName.substring(6)); // Sharma
System.out.println(fullName.toLowerCase()); // rahul sharma
System.out.println(" Java ".trim()); // Java
// == vs .equals() for Strings
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b); // true β same pool object
System.out.println(a == c); // false β different heap objects
System.out.println(a.equals(c)); // true β same content- βΆ
β οΈ Always use
.equals()to compare String content β not==. The==operator compares references (memory addresses), not the actual characters. This is one of the most common beginner bugs in Java. - βΆ
π‘ String Pool: When you write
String s = "Java", Java checks if"Java"already exists in the String Pool (a special area of the heap). If yes, the same object is reused β no new allocation. This is whyString a = "Java"; String b = "Java";givesa == b β true.
Wrapper Classes & Autoboxing / Unboxing
Wrapper classes are object representations of Java's 8 primitive types. They exist because many parts of Java (like collections, generics, reflection) require objects, not primitives. Every primitive type has exactly one corresponding wrapper class.
Autoboxing and Unboxing (Java 5+)
Autoboxing is the automatic conversion of a primitive to its wrapper class. Unboxing is the reverse β automatic conversion of a wrapper to its primitive. Java does this conversion automatically wherever needed.
import java.util.ArrayList;
public class WrapperDemo {
public static void main(String[] args) {
// --- Autoboxing: primitive β Wrapper ---
int primitiveInt = 42;
Integer wrappedInt = primitiveInt; // autoboxed automatically
System.out.println(wrappedInt); // 42
// --- Unboxing: Wrapper β primitive ---
Integer wrapperVal = 100;
int primitiveVal = wrapperVal; // unboxed automatically
System.out.println(primitiveVal); // 100
// --- ArrayList requires objects, not primitives ---
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // autoboxed: int 10 β Integer(10)
numbers.add(20);
numbers.add(30);
int sum = 0;
for (int n : numbers) { // each Integer is unboxed to int
sum += n;
}
System.out.println("Sum: " + sum); // 60
// --- Wrapper utility methods ---
String numStr = "2026";
int parsed = Integer.parseInt(numStr); // String β int
String binary = Integer.toBinaryString(255); // "11111111"
String hex = Integer.toHexString(255); // "ff"
System.out.println(parsed); // 2026
System.out.println(binary); // 11111111
System.out.println(hex); // ff
// --- Character utility ---
char ch = 'a';
System.out.println(Character.isLetter(ch)); // true
System.out.println(Character.toUpperCase(ch)); // A
System.out.println(Character.isDigit('5')); // true
}
}Output
42 100 Sum: 60 2026 11111111 ff true A true- βΆ
β οΈ Autoboxing performance: Autoboxing creates new objects on the heap. In performance-critical loops, avoid autoboxing millions of times β it adds GC pressure. Use primitive arrays instead of
ArrayList<Integer>when performance matters. - βΆ
β οΈ NullPointerException trap: If a wrapper variable is
nulland you try to unbox it, Java throws aNullPointerException. Example:Integer x = null; int y = x;β NullPointerException at runtime.
Type Casting β Widening & Narrowing
Type casting is the process of converting a value from one data type to another. Java supports two kinds of casting for primitive types β and they behave very differently.
1. Widening Casting (Implicit / Automatic)
Converting a smaller type to a larger type. Java does this automatically β no code needed, no data loss. The hierarchy: byte β short β int β long β float β double
byte b = 42;
short s = b; // byte β short (auto)
int i = s; // short β int (auto)
long l = i; // int β long (auto)
float f = l; // long β float (auto)
double d = f; // float β double (auto)
System.out.println("byte : " + b); // 42
System.out.println("short : " + s); // 42
System.out.println("int : " + i); // 42
System.out.println("long : " + l); // 42
System.out.println("float : " + f); // 42.0
System.out.println("double : " + d); // 42.0
// char to int β char's Unicode value is used
char ch = 'A';
int val = ch; // char β int (auto)
System.out.println(val); // 65Output
byte : 42 short : 42 int : 42 long : 42 float : 42.0 double : 42.0 652. Narrowing Casting (Explicit / Manual)
Converting a larger type to a smaller type. Must be done manually by writing the target type in parentheses. Data loss may occur β the extra bits are simply discarded.
double d = 9.99;
int i = (int) d; // double β int: decimal truncated (not rounded)
System.out.println(d); // 9.99
System.out.println(i); // 9 β 0.99 is lost
// int to byte β overflow may occur
int bigInt = 130;
byte b = (byte) bigInt; // 130 is outside byte range (-128 to 127)
System.out.println(b); // -126 β data corruption due to overflow
// Narrowing the full chain
double source = 1234.56;
long toLong = (long) source; // 1234
int toInt = (int) toLong; // 1234
short toShort= (short)toInt; // 1234 (fits)
byte toByte = (byte) toShort; // 1234 % 256 = 210 β wraps to -46
System.out.println("double β long : " + toLong);
System.out.println("long β int : " + toInt);
System.out.println("int β short : " + toShort);
System.out.println("short β byte : " + toByte);Output
9.99 9 -126 double β long : 1234 long β int : 1234 int β short : 1234 short β byte : -46How to Choose the Right Data Type
Choosing the right data type makes your code correct, efficient, and readable. Here is a practical decision guide for real-world Java development:
Use int for counters, ages, IDs, indices, loop variables. Switch to long only when values might exceed 2.1 billion β timestamps, file sizes, world-scale counts.
Use double for prices, measurements, scientific values, percentages. Only use float if memory is critically constrained (GPU buffers, ML model weights).
Never use float or double for money β they cannot represent 0.1 exactly. Use java.math.BigDecimal for financial calculations requiring exact precision.
Use char for individual characters, grade letters, menu options. For sequences of characters always use String.
Use boolean for flags, conditions, enable/disable switches. Name it with is/has/can prefix: isActive, hasRole, canEdit.
Use byte for raw binary data, file I/O buffers, image pixels, network packets. Use short only in legacy protocols or large arrays where each byte matters.
Complete Java Program β Putting It All Together
Let us write one complete program that uses all 8 primitive types, String, arrays, wrapper class utility, and type casting β all in a single realistic student information system.
import java.util.Scanner;
/**
* StudentProfile.java
* Demonstrates all 8 primitive types, String, array, wrapper classes,
* literals, and type casting in one realistic program.
*/
public class StudentProfile {
// Class constants using appropriate types
static final int MAX_MARKS = 100;
static final double PASS_PERCENT = 40.0;
static final char HIGHEST_GRADE = 'O';
public static void main(String[] args) {
// ---- 8 PRIMITIVE TYPES ----
byte rollNumber = 42; // byte: small whole number
short batchYear = 2026; // short: year fits in short
int studentId = 1_00_001; // int: large ID with underscore
long aadhaarNum = 1234_5678_9012L; // long: 12-digit Aadhaar
float attendance = 87.5f; // float: percentage
double gpa = 8.75; // double: GPA precision
char section = 'A'; // char: section label
boolean isActive = true; // boolean: enrollment status
// ---- STRING ----
String name = "Rahul Sharma";
String course = "B.Tech CSE";
String college = "Tech Sustainify University";
// ---- ARRAY ----
int[] subjectMarks = {88, 92, 79, 95, 85};
// ---- CALCULATIONS using appropriate types ----
int totalMarks = 0;
for (int mark : subjectMarks) {
totalMarks += mark;
}
double percentage = (totalMarks / (double)(subjectMarks.length * MAX_MARKS)) * 100;
// ---- TYPE CASTING ----
int roundedGpa = (int) gpa; // narrowing: 8.75 β 8
double longToDouble = (double) studentId; // widening: int β double
// ---- WRAPPER CLASS UTILITY ----
String gpaStr = Double.toString(gpa); // double β String
String idBinary = Integer.toBinaryString(studentId % 256); // binary
char sectionUpper = Character.toUpperCase(section); // already upper
// ---- GRADE using char ----
char grade;
if (percentage >= 90) grade = 'O'; // Outstanding
else if (percentage >= 75) grade = 'A';
else if (percentage >= 60) grade = 'B';
else if (percentage >= PASS_PERCENT) grade = 'C';
else grade = 'F';
boolean hasPassed = percentage >= PASS_PERCENT;
// ---- DISPLAY ----
System.out.println("ββββββββββββββββββββββββββββββββββββββββ");
System.out.println("β STUDENT PROFILE β");
System.out.println("β βββββββββββββββββββββββββββββββββββββββ£");
System.out.printf ("β Name : %-24sβ%n", name);
System.out.printf ("β Course : %-24sβ%n", course);
System.out.printf ("β College : %-24sβ%n", college);
System.out.printf ("β Roll No : %-24dβ%n", (int) rollNumber);
System.out.printf ("β Section : %-24cβ%n", sectionUpper);
System.out.printf ("β Batch : %-24dβ%n", (int) batchYear);
System.out.printf ("β GPA : %-24sβ%n", gpaStr);
System.out.printf ("β GPA (int) : %-24dβ%n", roundedGpa);
System.out.printf ("β Attendance: %-23.1f%%β%n", attendance);
System.out.printf ("β Total : %-24dβ%n", totalMarks);
System.out.printf ("β Percentage: %-23.2f%%β%n", percentage);
System.out.printf ("β Grade : %-24cβ%n", grade);
System.out.printf ("β Status : %-24sβ%n", hasPassed ? "PASS" : "FAIL");
System.out.printf ("β Active : %-24bβ%n", isActive);
System.out.println("ββββββββββββββββββββββββββββββββββββββββ");Output
ββββββββββββββββββββββββββββββββββββββββ β STUDENT PROFILE β β βββββββββββββββββββββββββββββββββββββββ£ β Name : Rahul Sharma β β Course : B.Tech CSE β β College : Tech Sustainify Universityβ β Roll No : 42 β β Section : A β β Batch : 2026 β β GPA : 8.75 β β GPA (int) : 8 β β Attendance: 87.5% β β Total : 439 β β Percentage: 87.80% β β Grade : A β β Status : PASS β β Active : true β ββββββββββββββββββββββββββββββββββββββββPractice This Code β Live Editor
Java Data Types β Interview Questions
These are the most frequently asked Java interview questions on data types β from beginner to intermediate level.
Practice Questions β Test Your Knowledge
Test your understanding of Java Data Types. Try to answer each question before revealing the answer.
1. What is the output? int a = 5; int b = 2; System.out.println(a / b); System.out.println(a % b);
Easy2. Will this compile? long l = 3000000000; Explain.
Medium3. What is the output? char c = 'A'; System.out.println(c + 1); System.out.println((char)(c + 1));
Medium4. What data type would you use to store a 12-digit Aadhaar number? Why?
Easy5. What is the output and why? double d = 0.1 + 0.2; System.out.println(d); System.out.println(d == 0.3);
Medium6. What is the difference between String s1 = 'Java' and String s2 = new String('Java')? Which is better?
Medium7. What is the result of (byte)(200)? Explain the calculation.
Hard8. Can you store the value 65535 in a char? Can you store -1 in a char?
HardSummary β What You Learned in Java Data Types
You have now mastered the complete Java type system β from the 8 primitive types to non-primitive reference types, wrapper classes, literals, and casting. Here is a quick recap:
The next step is understanding Java Variables in depth β declaration, initialization, scope, naming rules, the var keyword, and the difference between local, instance, and static variables. Continue to the next chapter: Java Variables β