….
🧬 Java Data Types – Understand What Goes Where
In Java, data types define the kind of data a variable can hold. This helps the compiler allocate memory and ensure you don’t accidentally assign text to a number or vice versa.
At GoNimbus, we believe mastering data types is the key to writing bug-free, optimized Java programs.
📦 Two Main Categories of Data Types
Java data types are divided into:
Category | Description |
---|---|
Primitive | Built-in types for simple values |
Non-Primitive | Objects and more complex structures |
Let’s explore each.
1️⃣ Primitive Data Types
Java has 8 built-in primitive types:
Type | Description | Size | Example Value |
---|---|---|---|
int | Whole numbers | 4 bytes | 25 , -100 , 0 |
float | Decimal numbers (single precision) | 4 bytes | 3.14f , -7.5f |
double | Decimal numbers (double precision) | 8 bytes | 99.99 , -0.001 |
char | A single character | 2 bytes | 'A' , '9' |
boolean | True or false | 1 bit | true , false |
byte | Small integers (-128 to 127) | 1 byte | 100 , -50 |
short | Medium-range integers | 2 bytes | 5000 , -1500 |
long | Large whole numbers | 8 bytes | 150000L , -99999L |
✅ Quick facts:
- Use
float
for memory-efficient decimals (addf
suffix) - Use
long
for big numbers (addL
suffix) - Use
boolean
for condition flags and checks
👨💻 Example – Using Primitives
public class PrimitiveDemo {
public static void main(String[] args) {
int age = 25;
float score = 95.5f;
char grade = 'A';
boolean passed = true;
System.out.println("Age: " + age);
System.out.println("Score: " + score);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + passed);
}
}
2️⃣ Non-Primitive Data Types
Also called reference types, these include:
Type | Description |
---|---|
String | A sequence of characters (text) |
Arrays | A collection of values (fixed-size) |
Classes | Custom objects and blueprints |
Interfaces | Contracts that classes can implement |
Let’s start with the most common one: String
.
📘 String: Most Used Non-Primitive Type
String city = "Hyderabad";
System.out.println("City: " + city);
✅ Strings support powerful built-in methods:
System.out.println(city.length()); // Output: 9
System.out.println(city.toUpperCase()); // Output: HYDERABAD
📌 While
String
may feel like a primitive, it’s actually an object (with methods!).
🧠 GoNimbus Tips for Choosing the Right Type
- Use
int
for counting items or IDs - Use
float
/double
for prices, weights, scores - Use
char
for gender, grades, initials - Use
boolean
for true/false conditions - Use
String
for names, messages, text inputs
⚠️ Be Careful With Type Mismatch
int age = "twenty"; // ❌ Error – type mismatch
boolean active = "true"; // ❌ Error – needs true/false without quotes
Use appropriate types without quotes unless it’s a String
.