Java Data Types
Data types in Java specify the size and type of values that can be stored in an identifier. They determine the possible values for that type, the operations that can be done on values of that type, and the way the values of that type are stored.
Key Topics
1. Primitive Data Types
Primitive data types are the most basic data types available in Java. There are eight primitive data types:
byte
: 8-bit integer data type. Range: -128 to 127.short
: 16-bit integer data type. Range: -32,768 to 32,767.int
: 32-bit integer data type. Range: -231 to 231-1.long
: 64-bit integer data type. Range: -263 to 263-1.float
: Single-precision 32-bit floating point. Used for decimal values.double
: Double-precision 64-bit floating point. Used for decimal values.boolean
: Represents one bit of information with only two possible values:true
andfalse
.char
: Single 16-bit Unicode character. Range: '\u0000' to '\uffff'.
Example
public class PrimitiveTypes {
public static void main(String[] args) {
byte b = 100;
short s = 10000;
int i = 100000;
long l = 100000000L;
float f = 10.5f;
double d = 20.5;
boolean bool = true;
char c = 'A';
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("boolean: " + bool);
System.out.println("char: " + c);
}
}
Output:
byte: 100
short: 10000
int: 100000
long: 100000000
float: 10.5
double: 20.5
boolean: true
char: A
short: 10000
int: 100000
long: 100000000
float: 10.5
double: 20.5
boolean: true
char: A
2. Non-Primitive Data Types
Non-primitive data types are also called reference types. They include:
- Strings: A sequence of characters. Example:
String str = "Hello";
- Arrays: A container that holds a fixed number of values of a single type. Example:
int[] arr = {1, 2, 3};
- Classes: A blueprint for creating objects. Example:
class MyClass {}
- Interfaces: An abstract type used to specify a behavior that classes must implement. Example:
interface MyInterface {}
Example
public class NonPrimitiveTypes {
public static void main(String[] args) {
String str = "Hello, World!";
int[] arr = {1, 2, 3, 4, 5};
MyClass obj = new MyClass();
System.out.println("String: " + str);
System.out.print("Array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
class MyClass {
// Class code here
}
Output:
String: Hello, World!
Array: 1 2 3 4 5
Array: 1 2 3 4 5
Key Takeaways
- Understanding data types is fundamental to Java programming.
- Primitive types are predefined and named by a reserved keyword.
- Non-primitive types are created by the programmer and are not defined by Java.