In Java, a data type defines the type of data that a variable can hold. It determines the size and type of values that can be stored in memory. Java provides a variety of data types, which can be broadly categorized into primitive and non-primitive data types.
Primitive Data Types
Integer Types
1. byte
Stores small integer values from -128 to 127.
Example:
public class DataTypeExample {
public static void main(String[] args) {
byte smallNumber = 110;
System.out.println("Byte Value: " + smallNumber);
}
}
2. short
Stores medium-range integer values from -32,768 to 32,767.
Example:
public class DataTypeExample {
public static void main(String[] args) {
short mediumNumber = 32000;
System.out.println("Short Value: " + mediumNumber);
}
}
3. int: Stores large integer values from -2,147,483,648 to 2,147,483,647.
Example:
public class DataTypeExample {
public static void main(String[] args) {
int largeNumber = 1000000;
System.out.println("Int Value: " + largeNumber);
}
}
4. long: Stores very large integer values. Must be suffixed with L
(e.g., 10000000000L
).
Example
public class DataTypeExample {
public static void main(String[] args) {
long veryLargeNumber = 10000000000L;
System.out.println("Long Value: " + veryLargeNumber);
}
}
Floating-Point Types
1. float: Used for decimal numbers with single precision. Must be suffixed with f (e.g., 10.5f).
Example:
public class DataTypeExample {
public static void main(String[] args) {
float decimalValue = 5.75f;
System.out.println("Float Value: " + decimalValue);
}
}
2. double: Used for decimal numbers with double precision (default for floating-point literals).
Example:
public class DataTypeExample {
public static void main(String[] args) {
double largeDecimalValue = 20.99;
System.out.println("Double Value: " + largeDecimalValue);
}
}
Character Type
1. char: Stores a single 16-bit Unicode character.
Example:
public class DataTypeExample {
public static void main(String[] args) {
char letter = 'A';
System.out.println("Character Value: " + letter);
}
}
Boolean Type
1. boolean: Stores only true or false.
Example:
public class DataTypeExample {
public static void main(String[] args) {
boolean isJavaFun = true;
System.out.println("Boolean Value: " + isJavaFun);
}
}
2. Non-Primitive Data Types
a. String: Stores a sequence of characters.
Example:
public class DataTypeExample {
public static void main(String[] args) {
String message = "Hello, Java!";
System.out.println("String Value: " + message);
}
}
b. Array: Stores a collection of values of the same type.
Example:
public class DataTypeExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
System.out.println("Array Value at Index 2: " + numbers[2]);
}
}