Introduction
Data types in Java define what kind of values a variable can hold. Understanding data types is crucial for writing correct and efficient Java programs.
Primitive Data Types
Java has 8 primitive data types divided into 4 categories:
Integer Types
| Type | Size | Range | Default |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | 0 |
| short | 2 bytes | -32,768 to 32,767 | 0 |
| int | 4 bytes | -2^31 to 2^31-1 | 0 |
| long | 8 bytes | -2^63 to 2^63-1 | 0L |
public class IntegerTypes {
public static void main(String[] args) {
byte b = 100;
short s = 10000;
int i = 100000;
long l = 10000000000L; // Note the L suffix
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
}
}
Floating-Point Types
| Type | Size | Precision | Default |
|---|---|---|---|
| float | 4 bytes | 6-7 decimal digits | 0.0f |
| double | 8 bytes | 15-16 decimal digits | 0.0d |
public class FloatingTypes {
public static void main(String[] args) {
float price = 99.99f; // Note the f suffix
double pi = 3.14159265358979;
System.out.println("Price: " + price);
System.out.println("PI: " + pi);
}
}
Character Type
public class CharType {
public static void main(String[] args) {
char letter = 'A';
char unicode = '\u0041'; // Also 'A'
char number = 65; // Also 'A' (ASCII value)
System.out.println(letter);
System.out.println(unicode);
System.out.println(number);
}
}
Boolean Type
public class BooleanType {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Is fish tasty? " + isFishTasty);
}
}
Reference Types
Reference types hold references to objects rather than the actual values.
String
String name = "JavaCompiler.in";
String greeting = new String("Hello");
Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
Objects
Student student = new Student();
Summary
- Java has 8 primitive types for basic values
- Reference types hold object references
- Choose the right type for your data needs
- Use int for most integer operations, double for decimals
Frequently Asked Questions
What are primitive data types in Java?
Java has 8 primitive data types: byte, short, int, long (integers), float, double (decimals), char (characters), and boolean (true/false).
What is the difference between int and Integer?
int is a primitive type that stores the actual value, while Integer is a wrapper class (reference type) that wraps the int value in an object. Integer can be null, int cannot.