Data Types in Java
Introduction to Data Types in Java
Data types in Java specify the size, type, and operations of data that can be stored in a variable. In Java, a statically-typed language, every variable must be declared with a data type. The data type of a variable determines how much space it occupies in memory and what kind of operations can be performed on it.
Java categorizes data types into primitive types, reference types, and wrapper classes.
Primitive Data Types
Primitive data types are built-in Java types that are not objects; they represent raw values. They include:
byte
: 8-bit signed integershort
: 16-bit signed integerint
: 32-bit signed integerlong
: 64-bit signed integerfloat
: 32-bit floating-point numberdouble
: 64-bit floating-point numberchar
: 16-bit Unicode characterboolean
: true or false
byte exampleByte = 100;
short exampleShort = 5000;
int exampleInt = 123456;
long exampleLong = 12345678910L;
float exampleFloat = 3.14f;
double exampleDouble = 3.14159;
char exampleChar = 'A';
boolean exampleBoolean = true;
Reference Data Types
Reference data types refer to objects and hence they are stored by reference. Examples include:
-
Basic Reference Types:
class
: Holds a reference to a class.interface
: A reference to an implemented interface.enum
: A special data type that enables for variables to be a set of predefined constants.lambda
: A reference to a lambda expression.String
: A reference to a string.Runnable
: A reference to a runnable object.Record
: A reference to a record.
// Class
class ExampleClass {
// Code...
}
// Interface
interface ExampleInterface {
// Code...
}
// Enum
enum Size {SMALL, MEDIUM, LARGE}
Size exampleSize = Size.MEDIUM;
// Lambda
Runnable exampleRunnable = () -> System.out.println("Running");
// Lambda with parameters
Comparator<Integer> exampleComparator = (a, b) -> a - b;
// Lambda with return statement
Function<Integer, Integer> exampleFunction = (a) -> {
return a * a;
};
// String
String exampleString = "Hello, World!";
// Runnable
Runnable exampleRunnable = () -> {
// Code...
};
// Record
record ExampleRecord(int id, String name) {
// Code...
}
-
Collections and Iterators:
array
: A reference to a dynamically allocated array.List
: A reference to a dynamically sized collection of elements.Map
: A reference to a collection of key-value pairs.Set
: A reference to a collection that contains no duplicate elements.Iterator
: A reference to an object that enables traversal through a collection.
// array
int[] exampleArray = new int[5];
// List
List<String> exampleList = new ArrayList<>();
// Map
Map<String, Integer> exampleMap = new HashMap<>();
// Set
Set<String> exampleSet = new HashSet<>();
// Iterator
Iterator<String> exampleIterator = exampleList.iterator();
-
Concurrency and IO:
Thread
: A reference to a thread of execution.Exception
: A reference to an exception object.Annotation
: A reference to an annotation.Socket
: A reference to a network communication endpoint.File
: A reference to a file or directory in the file system.Scanner
: A reference to an object used to parse primitive types and strings from an input stream.
// Thread
Thread exampleThread = new Thread(() -> {
// Code...
});
// Exception
try {
// Code...
} catch (Exception e) {
// Code...
}
// Annotation
@interface ExampleAnnotation {
// Code...
}
// Socket
Socket exampleSocket = new Socket("localhost", 8080);
// File
File exampleFile = new File("example.txt");
// Scanner
Scanner exampleScanner = new Scanner(System.in);
Wrapper Classes
Java also provides a set of wrapper classes that correspond to the primitive data types. These wrapper classes are used to create objects from primitive data types, and to perform operations on primitive data types. The wrapper classes are:
Byte
: Wrapper class forbyte
Short
: Wrapper class forshort
Integer
: Wrapper class forint
Long
: Wrapper class forlong
Float
: Wrapper class forfloat
Byte exampleWrappedByte = 100;
Short exampleWrappedShort = 5000;
Integer exampleWrappedInt = 123456;
Long exampleWrappedLong = 12345678910L;
Float exampleWrappedFloat = 3.14f;
Double exampleWrappedDouble = 3.14159;
Character exampleWrappedChar = 'A';
Boolean exampleWrappedBoolean = true;
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int
to an Integer
, a double
to a Double
, etc. Similarly, unboxing is the reverse process:
// Autoboxing
Integer autoBoxedInt = 10; // int to Integer
// Unboxing
int unboxedInt = autoBoxedInt; // Integer to int
Differences Between Primitive and Wrapper Classes
Aspect | Primitive Types | Wrapper Classes |
---|---|---|
Type | Basic data type | Class type (Object) |
Storage | Stack | Heap |
Default Value | Has default value (e.g., 0 for int) | Null (if not initialized) |
Size | Fixed size | Larger than primitives due to object overhead |
Speed | Fast | Slower than primitives due to additional processing |
Utility | Limited to basic arithmetic and logical operations | Comes with methods for conversion, comparison, etc. |
Usage in Generics | Not applicable | Can be used with generics and collections |
Nullability | Cannot be null | Can be null |
Conclusion
In this article, we discussed the different data types and access modifiers in Java. We learned about primitive types, reference types, and wrapper classes, and how they differ from each other. We also explored the four access modifiers in Java and their use cases. Understanding these concepts is essential for writing efficient and secure Java code.