Primitive Data Types and Wrapper Classes

 

1. Primitive Data Types in Java

Java has 8 primitive data types, which are the most basic types of data built into the language. They are not objects and are stored directly in memory for performance.

TypeSizeDefault ValueDescriptionExample
byte1 byte (8-bit)0Small integers (-128 to 127)byte a = 10;
short2 bytes0Larger than byte (-32,768 to 32,767)short b = 1000;
int4 bytes0Common for integersint c = 12345;
long8 bytes0LVery large integerslong d = 100000L;
float4 bytes0.0fSingle-precision decimalfloat e = 3.14f;
double8 bytes0.0dDouble-precision decimal (default)double f = 3.14159;
char2 bytes'\u0000'Single 16-bit Unicode characterchar g = 'A';
boolean1 bit (virtual)falseLogical true/falseboolean h = true;

📦 2. Wrapper Classes in Java

Java provides wrapper classes in the java.lang package for each primitive data type. These allow primitives to be treated as objects.

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

🔍 Why Use Wrapper Classes?

  • Required when working with collections like ArrayList, which only store objects.

  • Useful for type conversion, parsing from strings, and using object methods.

  • Enable null values (primitives cannot be null).


🔁 Autoboxing and Unboxing

Java automatically converts between primitives and wrappers:

ConceptDescriptionExample
Autoboxingprimitive ➝ object (wrapper class)Integer x = 10;
Unboxingobject ➝ primitiveint y = x;

✅ Example Code


public class WrapperExample { public static void main(String[] args) { int num = 5; // primitive Integer obj = num; // autoboxing int num2 = obj; // unboxing System.out.println("Primitive: " + num); System.out.println("Wrapper: " + obj); System.out.println("Unboxed: " + num2); } }

📝 Summary Table

FeaturePrimitive TypeWrapper Class
Memory Efficient
Part of Object Hierarchy
Works with Collections
Can be null
Autoboxed/Unboxed

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java