Data Types in Java
In Java, every variable you use must have a declared type. Data type determines how much memory is allocated and what kind of operations you can perform on that data.
In Java, every variable you use must have a declared type. Data type determines how much memory is allocated and what kind of operations you can perform on that data.
Java data types are broadly categorized into two groups:
Java has 8 primitive data types, and each has a specific purpose and memory size.
| Type | Size | Default Value | Description |
|---|---|---|---|
byte | 1 byte | 0 | Useful for saving memory in large arrays |
short | 2 bytes | 0 | Shorter-range integers |
int | 4 bytes | 0 | Standard integer type |
long | 8 bytes | 0L | Larger-range integers |
float | 4 bytes | 0.0f | Single-precision decimals |
double | 8 bytes | 0.0d | Double-precision decimals |
char | 2 bytes | '\u0000' | Single character (Unicode) |
boolean | ~1 bit | false | True or false values |
public class PrimitiveExample {
public static void main(String[] args) {
int age = 25;
double salary = 45600.75;
char grade = 'A';
boolean isEmployed = true;
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Employed: " + isEmployed);
}
}
Age: 25
Salary: 45600.75
Grade: A
Employed: true
Non-primitive types are created by the programmer and can hold multiple values or have behavior. These include:
String – A sequence of charactersArrays – Collection of variables of the same typeClasses and Interfaces – Blueprint for objectspublic class NonPrimitiveExample {
public static void main(String[] args) {
String name = "Arjun";
int[] scores = {85, 90, 78};
System.out.println("Name: " + name);
System.out.println("Scores:");
for (int score : scores) {
System.out.println(score);
}
}
}
Name: Arjun
Scores:
85
90
78
Understanding how Java enforces type safety is crucial when working with literals. Java is a statically typed language, meaning types are checked at compile-time, helping catch errors early and ensuring predictability in program behavior.
Java does not allow assigning a float or double literal to an int variable without an explicit cast. This prevents accidental loss of precision or data.
public class TypeMismatchExample {
public static void main(String[] args) {
// int x = 3.14; // Compile-time error
int x = (int) 3.14; // Works but loses decimal
System.out.println(x);
}
}
3
While casting may resolve the error, it’s usually better to use the right data type from the start to preserve intent and accuracy.
Java treats numeric literals as int by default for integers and double for decimals. If you intend to use a long or float, suffixes like L or F must be added.
public class SuffixExample {
public static void main(String[] args) {
long population = 7800000000L;
float pi = 3.14159F;
double gravity = 9.8; // no suffix needed, double is default
System.out.println(population);
System.out.println(pi);
System.out.println(gravity);
}
}
7800000000
3.14159
9.8
Without the correct suffix, you'll either encounter a compilation error (for long) or a potential precision mismatch (for float).
Java primitives like byte and short have narrow ranges. Arithmetic operations that exceed their limits will silently wrap around (overflow), leading to unexpected results.
public class OverflowDemo {
public static void main(String[] args) {
byte b = 127;
b += 1; // wraps around to -128
System.out.println(b);
}
}
-128
For arithmetic-heavy applications, use int or long to avoid such silent overflows.
Even seasoned developers stumble over these classic pitfalls. Here’s how you can avoid them:
Java enforces definite assignment. Local variables must be explicitly initialized before use—otherwise, the compiler will throw an error.
public class InitErrorExample {
public static void main(String[] args) {
int x;
System.out.println(x);
}
}
InitErrorExample.java:4: error: variable x might not have been initialized
System.out.println(x);
^
1 error
ERROR!
error: compilation failed
Class-level fields are auto-initialized (e.g. int to 0, boolean to false), but local variables are not.
Attempting to combine different types (e.g. int with String) or assign a higher precision type to a lower one without casting will lead to compile-time errors.
public class IncompatibleTypesExample {
public static void main(String[] args) {
double d = 5.5;
int i = (int) d; // Explicit cast
System.out.println(i); // Output: 5
}
}
5
Use casting carefully as it may lead to data truncation or loss of precision.
== vs .equals() for reference types:Beginners often confuse these two when comparing strings or objects.
== checks whether references point to the same object..equals() checks whether the objects have the same content.public class StringComparisonExample {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same content)
}
}
false
true
When comparing object values, always use .equals() unless you're explicitly checking for reference equality.
byte b = 127;
b += 1;
System.out.println(b);