Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Why Java Collections Cannot Directly Store Primitives Types?
Next article icon

Why Java Collections Cannot Directly Store Primitives Types?

Last Updated : 02 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Primitive types are the most basic data types available within the Java language. Such types serve only one purpose — containing pure, simple values of a kind. Since java is a Statically typed language where each variable and expression type is already known at compile-time, thus you can not define a new operation for such primitive types.

Illustration:

Invalid : vector.addElement(3) ; Valid   : vector.addElelment("3") ;

Conclusion:

  • Java primitive types are not referenced types. For example, int is not an Object.
  • Java does generics using type-erasure of reference types. For example, A List<?> is really a List<Object> at run-time.

Collections are the framework used to store and manipulate a group of objects. Java Collection means a single unit of objects. Since the above two statements are true, generic Java collections can not store primitive types directly.

Wrapper Class provides a way to use primitive data types (int, boolean, etc..) as objects or a Wrapper class is a class whose object wraps or contains primitive data types. It gives birth to two concepts as follows:

  1. Autoboxing
  2. Unboxing
Primitive Data TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

Autoboxing is the automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For instance:

  • Conversion of int to Integer
  • Conversion of long to Long
  • Conversion of double to Double, etc.

Unboxing is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.

Illustration: Autoboxing

Java
// Importing input output classes import java.io.*;  class GFG {      // Main driver method     public static void main(String args[])     {          // Custom input         Integer i = new Integer(21);          // Boxing         Integer j = 5;         System.out.println("i=" + i + "\n j=" + j);     } } 

Output:

i=21 j=5

Illustration 2: Unboxing 

Java
// Import input output classes import java.io.*;  // Class public class GFG {      // MAin driver method     public static void main(String args[])     {          // Custom input         Integer i = new Integer(50);          // Unboxing         int a = i;          // Unboxing         int b = i.intValue();          // Print and display         System.out.println("a=" + a + "\nb=" + b);     } } 

Output: 

a=50 b=50

Implementation: While using the collection java compiler create a wrapper Object from the primitive type and adds it to the collection using generics.

Example 1: 

Java
// Java Program to illustrate Collections // are not directly storing primitives types  // Importing input output classes import java.io.*; // Importing all classes from // java.util package import java.util.*;  // Class class GFG {      // Main driver method     public static void main(String[] args)     {          // Creating a list of elements of Integer type.         List<Integer> list = new ArrayList<Integer>();          // Iterating over elements of List object         for (int i = 0; i < 10; i++) {             // Adding the int primitives type values              // If elements are added  using add() method             // then compiler automatically treats as             // add(Integer.valueOf(i))             list.add(i);             //  This is what compiler does and             // hence the goal achieved.              // Print the primitive values             System.out.println(i);         }     } } 

Output
0 1 2 3 4 5 6 7 8 9


Example 2: Collections to store Primitive datatype 

Java
// Java Program to illustrate Collections // are not directly storing primitives types  // Importing Map and HashMap classes // from java.util package import java.util.HashMap; import java.util.Map;  // Class public class GFG {      // Main driver method     public static void main(String[] args) throws Exception     {          // Creating an object of Map type         Map map = new HashMap();          // Creating int wrapper object         // Custom input         Integer var = new Integer(21);          // Storing int to map         map.put("key", var);          // Getting int value from map         Integer refVar = (Integer)map.get("key");          // Get the integer value from wrapper object         int i = refVar.intValue();              // Display message for successful compilation       System.out.print("Successfully compiled and executed");     } } 

Output: 

Successfully compiled and executed


 


Next Article
Why Java Collections Cannot Directly Store Primitives Types?

A

aarushi_bagri
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2020
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    Primitive data type vs. Object data type in Java with Examples
    Data Types in Java Every variable in java has a data type. Data types specify the size and type of values that can be stored in an identifier. Java language is rich in its data types. The variety of data types available allow the programmer to select the type appropriate to the need of the applicati
    6 min read
    Java Collections Interview Questions and Answers
    Java Collection Framework was introduced in JDK 1.2 which contains all the collection classes and interfaces. Java Collection is a framework that provides a mechanism to store and manipulate the collection of objects. It allows developers to access prepackaged data structures and algorithms for mani
    15+ min read
    Why We Need Collection Framework in Java?
    A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classe
    3 min read
    Collection vs Collections in Java with Example
    Collection: Collection is a interface present in java.util package. It is used to represent a group of individual objects as a single unit. It is similar to the container in the C++ language. The collection is considered as the root interface of the collection framework. It provides several classes
    3 min read
    Primitive Data Types vs Non Primitive Data Types in Python
    Python, known for its versatility and user-friendliness, is a dynamic language that doesn't explicitly categorize data types into primitive and non-primitive as some languages like Java do. However, for clarity and understanding, it's useful to draw parallels and discuss similar concepts. In this ar
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences