Primitive data types
In Java, data types are fundamental building blocks that define the nature of data stored in a variable. Primitive data types are the simplest and most basic data types in Java, representing single values without any structure. They are not objects and are stored directly in memory.
Java Primitive Data Types
Java has eight primitive data types, which can be categorized into four groups: integers, floating-point numbers, characters, and booleans.
1. Integers
- byte: 8-bit signed integer. Range: -128 to 127.
- short: 16-bit signed integer. Range: -32,768 to 32,767.
- int: 32-bit signed integer. Range: -2^31 to 2^31 – 1.
- long: 64-bit signed integer. Range: -2^63 to 2^63 – 1.
2. Floating-Point Numbers
- float: 32-bit floating-point. Example:
3.14f
. - double: 64-bit floating-point. Example:
3.14
.
3. Characters
- char: 16-bit Unicode character. Example:
'A'
,'\u0041'
.
4. Boolean
- boolean: Represents true or false.
Java Code Examples
Integers Example
public class IntegerExample {
public static void main(String[] args) {
byte myByte = 10;
short myShort = 1000;
int myInt = 100000;
long myLong = 1000000000L; // Note the 'L' at the end for a long literal
System.out.println("byte: " + myByte);
System.out.println("short: " + myShort);
System.out.println("int: " + myInt);
System.out.println("long: " + myLong);
}
}
Floating-Point Example
public class FloatDoubleExample {
public static void main(String[] args) {
float myFloat = 3.14f;
double myDouble = 3.14;
System.out.println("float: " + myFloat);
System.out.println("double: " + myDouble);
}
}
Character Example
public class CharExample {
public static void main(String[] args) {
char myChar = 'A';
char unicodeChar = '\u0041';
System.out.println("char: " + myChar);
System.out.println("unicodeChar: " + unicodeChar);
}
}
Boolean Example
public class BooleanExample {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishBoring = false;
System.out.println("Java is fun? " + isJavaFun);
System.out.println("Is fish boring? " + isFishBoring);
}
}
Summary
Understanding primitive data types in Java is crucial for writing efficient and reliable programs. Each data type serves a specific purpose, and choosing the right type for your variables ensures proper memory usage and program behavior. The examples provided demonstrate how to declare and use different primitive data types in Java.