1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Data Types
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
27Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Data Types

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
27Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Data Types

Overview

Data Types define the exact size and format of data stored in a variable, allowing the JVM to optimize memory usage perfectly. Java splits its data types into two massive categories: Primitives and Reference Types.

Primitive Types are the raw, foundational building blocks. They hold simple values directly in Stack memory and have virtually no performance overhead. There are exactly 8 primitive types in Java: - Integers: byte (1 byte), short (2 bytes), int (4 bytes, the default), long (8 bytes, for massive numbers). - Decimals: float (4 bytes, less precise), double (8 bytes, the default for decimals). - Characters: char (2 bytes, holds a single Unicode character). - Booleans: boolean (1 bit, holds true/false).

Reference Types are complex objects (like String, Scanner, or your own custom classes). Instead of holding the actual data, a reference variable holds the memory address pointing to the massive object stored in the Heap memory.

Syntax

Notice the mandatory 'L' for long and 'f' for float. If you forget the 'f', Java assumes it is a double and throws a compilation error. Explicit casting requires putting the target type in parentheses.

Primitives and Casting
java
public class Main {
    public static void main(String[] args) {
        // --- 8 Primitive Types ---
        byte smallNum = 127;           // Max size is 127
        short mediumNum = 32000;       // Max size is ~32,000
        int defaultNum = 2000000000;   // The default integer choice
        long hugeNum = 9000000000000L; // Suffix 'L' required for long
        
        float price = 19.99f;          // Suffix 'f' required for float
        double precisePrice = 19.9999; // The default decimal choice
        
        char letter = 'A';             // Uses SINGLE quotes
        boolean isJavaFun = true;      // true or false
        
        // --- Type Casting ---
        
        // Implicit Casting (Automatic, smaller to larger)
        int myInt = 9;
        double myDouble = myInt;       // Becomes 9.0 automatically
        
        // Explicit Casting (Manual, larger to smaller, risks data loss!)
        double preciseNum = 9.78;
        int roundedNum = (int) preciseNum; // Becomes 9 (decimal is chopped off!)
    }
}

Common Pitfalls

  • Integer Overflow. If you add 1 to the absolute maximum value an int can hold (2.14 billion), it wraps around to negative 2.14 billion! If you are dealing with global populations or massive finances, always use long.
  • Forgetting the 'f' suffix on a float. float x = 3.14; will fail to compile because 3.14 is considered a double by default, which is too large to fit in a float.
  • Using double/float for exact currency calculations. Floats and doubles suffer from floating-point arithmetic precision errors (e.g., 0.1 + 0.2 might equal 0.300000000004). For real banking apps, use BigDecimal instead.

Interview Questions

What is the difference between Primitive types and Wrapper classes?

Primitives (like int, double) hold raw values directly in the stack and are incredibly fast. Wrapper classes (like Integer, Double) are full Objects that wrap the primitive data, providing utility methods (like Integer.parseInt()). Wrapper classes are required when using generic collections like ArrayList.

Why do we need explicit casting when converting a double to an int?

Because a double takes up 8 bytes of memory and holds decimal places, while an int only takes 4 bytes and holds whole numbers. Java forces you to explicitly cast it using (int) to acknowledge that you are actively choosing to lose the decimal data (truncation).

Real-World Example

NASA's Mars Rover software must carefully manage memory. Instead of using massive 8-byte long variables for simple sensor flags (like 0 to 100), they might explicitly use 1-byte byte types to preserve ultra-limited onboard RAM.

example
java
// Optimizing memory footprint
byte currentGear = 2;       // Only uses 1 byte
long distanceToEarth = 12000000000L; // Requires 8 bytes

Check Your Knowledge

Test your understanding of Data Types with these quick questions.

Question 1

Which data type is the default choice for storing decimal numbers in Java?

Question 2

What happens during explicit casting from `double` (e.g., 9.99) to `int`?

Question 3

How many primitive data types exist in Java?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Data Types

Overview

Data Types define the exact size and format of data stored in a variable, allowing the JVM to optimize memory usage perfectly. Java splits its data types into two massive categories: Primitives and Reference Types.

Primitive Types are the raw, foundational building blocks. They hold simple values directly in Stack memory and have virtually no performance overhead. There are exactly 8 primitive types in Java: - Integers: byte (1 byte), short (2 bytes), int (4 bytes, the default), long (8 bytes, for massive numbers). - Decimals: float (4 bytes, less precise), double (8 bytes, the default for decimals). - Characters: char (2 bytes, holds a single Unicode character). - Booleans: boolean (1 bit, holds true/false).

Reference Types are complex objects (like String, Scanner, or your own custom classes). Instead of holding the actual data, a reference variable holds the memory address pointing to the massive object stored in the Heap memory.

Syntax

Notice the mandatory 'L' for long and 'f' for float. If you forget the 'f', Java assumes it is a double and throws a compilation error. Explicit casting requires putting the target type in parentheses.

Primitives and Casting
java
public class Main {
    public static void main(String[] args) {
        // --- 8 Primitive Types ---
        byte smallNum = 127;           // Max size is 127
        short mediumNum = 32000;       // Max size is ~32,000
        int defaultNum = 2000000000;   // The default integer choice
        long hugeNum = 9000000000000L; // Suffix 'L' required for long
        
        float price = 19.99f;          // Suffix 'f' required for float
        double precisePrice = 19.9999; // The default decimal choice
        
        char letter = 'A';             // Uses SINGLE quotes
        boolean isJavaFun = true;      // true or false
        
        // --- Type Casting ---
        
        // Implicit Casting (Automatic, smaller to larger)
        int myInt = 9;
        double myDouble = myInt;       // Becomes 9.0 automatically
        
        // Explicit Casting (Manual, larger to smaller, risks data loss!)
        double preciseNum = 9.78;
        int roundedNum = (int) preciseNum; // Becomes 9 (decimal is chopped off!)
    }
}

Common Pitfalls

  • Integer Overflow. If you add 1 to the absolute maximum value an int can hold (2.14 billion), it wraps around to negative 2.14 billion! If you are dealing with global populations or massive finances, always use long.
  • Forgetting the 'f' suffix on a float. float x = 3.14; will fail to compile because 3.14 is considered a double by default, which is too large to fit in a float.
  • Using double/float for exact currency calculations. Floats and doubles suffer from floating-point arithmetic precision errors (e.g., 0.1 + 0.2 might equal 0.300000000004). For real banking apps, use BigDecimal instead.

Interview Questions

What is the difference between Primitive types and Wrapper classes?

Primitives (like int, double) hold raw values directly in the stack and are incredibly fast. Wrapper classes (like Integer, Double) are full Objects that wrap the primitive data, providing utility methods (like Integer.parseInt()). Wrapper classes are required when using generic collections like ArrayList.

Why do we need explicit casting when converting a double to an int?

Because a double takes up 8 bytes of memory and holds decimal places, while an int only takes 4 bytes and holds whole numbers. Java forces you to explicitly cast it using (int) to acknowledge that you are actively choosing to lose the decimal data (truncation).

Real-World Example

NASA's Mars Rover software must carefully manage memory. Instead of using massive 8-byte long variables for simple sensor flags (like 0 to 100), they might explicitly use 1-byte byte types to preserve ultra-limited onboard RAM.

example
java
// Optimizing memory footprint
byte currentGear = 2;       // Only uses 1 byte
long distanceToEarth = 12000000000L; // Requires 8 bytes

Check Your Knowledge

Test your understanding of Data Types with these quick questions.

Question 1

Which data type is the default choice for storing decimal numbers in Java?

Question 2

What happens during explicit casting from `double` (e.g., 9.99) to `int`?

Question 3

How many primitive data types exist in Java?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A